package com.zcxk.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.zcxk.entity.Dict;
import com.zcxk.entity.UserEntity;
import com.zcxk.entity.VerManageEntity;
import com.zcxk.model.*;
import com.zcxk.service.DictService;
import com.zcxk.service.UserService;
import com.zcxk.service.VerManageService;
import com.zcxk.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * app版本表控制层
 *
 * @author yjy
 * @since 2021-5-13
 */
@RestController
@RequestMapping("/verManage")
@Api(tags = "app版本")
public class VerManageController {
    /**
     * 服务对象
     */
    @Autowired
    private VerManageService verManageService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;

    /**
     * 查询app版本信息
     * @return 单条数据
     */
    @RequestMapping(value = "findVerManage", method = RequestMethod.GET)
    @ApiOperation(value = "查询app版本信息")
    public AjaxMessage<Pagination<VerManageEntity>> findVerManage(
            @ApiParam(value = "页数", required = true)@RequestParam Integer pageNum,
            @ApiParam(value = "条数", required = true)@RequestParam Integer pageSize,
            @ApiParam(value = "版本ID", required = false) @RequestParam(required = false) String verId,
            @ApiParam(value = "产品类型", required = false) @RequestParam(required = false) String productType) {
        IPage<VerManageEntity> iPage = new Page<>(pageNum, pageSize);
        iPage = verManageService.findVerManage(iPage,verId,productType);
        Pagination<VerManageEntity> pages = new Pagination<>(iPage);
        setName(pages.getList());
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    /**
     * 查询app版本信息
     * @return 单条数据
     */
    @RequestMapping(value = "appUpgrade", method = RequestMethod.GET)
    @ApiOperation(value = "app升级")
    public AjaxMessage<List<VerManageEntity>> appUpgrade(
            @ApiParam(value = "产品类型", required = false) @RequestParam(required = false) String productType) {
        List<VerManageEntity> list = verManageService.getUpgradeVer(productType);
        setName(list);
        return new AjaxMessage<>(ResultStatus.OK, list);
    }

    /**
     * 新增APP版本信息
     */
    @PostMapping(value = "addVerManage")
    @ApiOperation(value = "新增版本管理")
    public AjaxMessage<Object> addVerManage(
            @ApiParam(value = "新增版本管理", required = true) @RequestBody VerManageEntity verManageEntity) {
        LoginUser loginUser = UserUtil.getCurrentUser();
        verManageEntity.setCreateBy(loginUser.getId().toString());
        verManageEntity.setStatus(1);
        int result = verManageService.insertSelective(verManageEntity);
        if(result>0){
            return new AjaxMessage<>(ResultStatus.OK);
        }
        return new AjaxMessage<>(ResultStatus.ERROR);
    }

    /**
     * 修改APP版本信息
     */
    @PostMapping(value = "updateVerManage")
    @ApiOperation(value = "修改版本管理")
    public AjaxMessage<Object> updateVerManage(
            @ApiParam(value = "修改版本管理", required = true) @RequestBody VerManageEntity verManageEntity) {
        LoginUser loginUser = UserUtil.getCurrentUser();
        verManageEntity.setUpdateBy(loginUser.getId().toString());
        int result = verManageService.updateByPrimaryKeySelective(verManageEntity);
        if(result>0){
            return new AjaxMessage<>(ResultStatus.OK);
        }
        return new AjaxMessage<>(ResultStatus.ERROR);
    }


    /**
     * 删除APP版本信息
     */
    @RequestMapping(value = "deleteVerManage",method = RequestMethod.DELETE)
    @ApiOperation(value = "删除版本管理")
    public AjaxMessage<Object> deleteVerManage(
            @ApiParam(value = "要删除的版本ID，多个ID之间用逗号隔开", required = true)  @RequestParam String ids){
        String [] idArray = ids.split(",");
        if(idArray.length==0){
            return new AjaxMessage<>(ResultStatus.ERROR,"参数异常");
        }
        List<String> idList = Arrays.asList(idArray);
        int result = verManageService.deleteSelective(idList);
        if(result>0){
            return new AjaxMessage<>(ResultStatus.OK);
        }
        return new AjaxMessage<>(ResultStatus.ERROR);
    }


    /**
     * 获取并设置用户、任务工单类型名称
     * @param result
     */
    private void setName(List<VerManageEntity> result){
        if(result.size()>0){
            try{
                List<Integer> idList = new ArrayList<Integer>();
                for(VerManageEntity verManageEntity:result) {
                    try {
                        if (verManageEntity.getCreateBy() != null) {
                            idList.add(Integer.valueOf(verManageEntity.getCreateBy()));
                        }
                        if (verManageEntity.getUpdateBy() != null) {
                            idList.add(Integer.valueOf(verManageEntity.getUpdateBy()));
                        }
                    }catch (Exception e){

                    }
                }
                List<UserEntity> userEntityList=userService.findUserIdsByUserIds(idList);
                Map<Long,String> userMap = userEntityList.stream().collect(Collectors.toMap(UserEntity::getId, UserEntity::getUsername));
                String parentDictCodes="SYSTEM_PRODUCT_TYPE";
                Map<String,String> dictMap=new HashMap<>();
                for(String parentDictCode:parentDictCodes.split(",")){
                    Dict dict=new Dict();
                    dict.setParentDictCode(parentDictCode);
                    dictMap.putAll(dictService.selectList(dict).stream().collect(Collectors.toMap(Dict::getDictCode, Dict::getDictValue)));
                }
                for(int i = 0; i < result.size(); i++) {
                    VerManageEntity verManage = result.get(i);
                    try {
                        verManage.setProductTypeName(dictMap.get(verManage.getProductType()));
                        if (verManage.getCreateBy() != null) {
                            verManage.setCreateByName(userMap.get(Long.valueOf(verManage.getCreateBy())));
                        }
                        if (verManage.getUpdateBy() != null) {
                            verManage.setUpdateByName(userMap.get(Long.valueOf(verManage.getUpdateBy())));
                        }
                    }catch (Exception e){
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}