package org.stm.plan.approve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.stm.common.service.IStCommonService;
import org.stm.common.vo.DutyVo;
import org.stm.plan.approve.constant.ApproveConstant;
import org.stm.plan.approve.entity.StPlanApprove;
import org.stm.plan.approve.mapper.StPlanApproveMapper;
import org.stm.plan.approve.service.IStPlanApproveService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.stm.plan.approve.vo.StPlanApproveVo;
import org.stm.plan.main.constant.PlanFlag;
import org.stm.plan.main.entity.StPlanMan;
import org.stm.plan.main.service.IStPlanManService;
import org.stm.plan.main.vo.StPlanManVo;
import org.stm.utils.UserUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: st_plan_approve
 * @Author: jeecg-boot
 * @Date:   2023-07-16
 * @Version: V1.0
 */
@Service
public class StPlanApproveServiceImpl extends ServiceImpl<StPlanApproveMapper, StPlanApprove> implements IStPlanApproveService {

    @Autowired
    private IStPlanManService iStPlanManService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysDictService iSysDictService;

    @Override
    public void approveCreate(StPlanMan stPlanMan) {
       stPlanMan = iStPlanManService.getById(stPlanMan.getId());
       if(stPlanMan!=null){
           StPlanApprove stPlanApprove = new StPlanApprove();
           stPlanApprove.setCreatedUser(stPlanMan.getUpdatedUser());
           stPlanApprove.setPlanCode(stPlanMan.getPlanCode());
           stPlanApprove.setOptDes(stPlanMan.getOptDes());
           // 计划标志和审核类型转换
           if(PlanFlag.DSH.equals(stPlanMan.getPlanFlag())) {
               stPlanApprove.setApproveType(ApproveConstant.XZJH);
           } else if (PlanFlag.BGDSH.equals(stPlanMan.getPlanFlag())) {
               stPlanApprove.setApproveType(ApproveConstant.BGJH);
           } else if (PlanFlag.FZDSH.equals(stPlanMan.getPlanFlag())) {
               stPlanApprove.setApproveType(ApproveConstant.FZJH);
           }
           stPlanApprove.setApproveUser(stPlanMan.getApproveUser());
           super.save(stPlanApprove);
       }
    }

    @Override
    public IPage<StPlanApprove> defPage(StPlanApproveVo stPlanApproveVo, Integer pageNo, Integer pageSize, Map<String, String[]> parameterMap) {
        String projectName = stPlanApproveVo.getProjectName();
        String projectType = stPlanApproveVo.getProjectType();
        String executeDepCode = stPlanApproveVo.getExecDepCode();
        QueryWrapper<StPlanMan> planManQueryWrapper = new QueryWrapper<>();
        boolean isPlanQuery = false;
        if(StringUtils.isNotEmpty(projectName)){
            planManQueryWrapper.like("PROJECT_NAME","%"+projectName+"%");
            isPlanQuery = true;
        }
        if(StringUtils.isNotEmpty(projectType)){
            planManQueryWrapper.eq("PROJECT_TYPE",projectType);
            isPlanQuery = true;
        }
        if(StringUtils.isNotEmpty(executeDepCode)){
            planManQueryWrapper.eq("EXEC_DEP_CODE",executeDepCode);
            isPlanQuery = true;
        }
        List<String> planCodes = null;
        if(isPlanQuery) {
           List<StPlanMan> stPlanManList = iStPlanManService.list(planManQueryWrapper);
            planCodes = stPlanManList.stream().map(StPlanMan::getPlanCode).collect(Collectors.toList());
        }
        String userCode = UserUtil.getUserCode();
        // 查询用户岗位
        SysUser sysUser = iSysUserService.getUserByName(userCode);
        QueryWrapper<StPlanApprove> approveQueryWrapper  = new QueryWrapper<>();
        // 计划管理岗可以查询所有
        if(!"PL001".equals(sysUser.getPost())) {
            approveQueryWrapper.eq("APPROVE_USER", userCode);
        }
        if(isPlanQuery && CollectionUtils.isEmpty(planCodes)){
            approveQueryWrapper.eq("PLAN_CODE","notExist");
        }else if(!CollectionUtils.isEmpty(planCodes)){
            approveQueryWrapper.in("PLAN_CODE",planCodes);
        }
        approveQueryWrapper.orderByDesc("UPDATED_TIME");
        Page<StPlanApprove> page = new Page<StPlanApprove>(pageNo, pageSize);
        IPage<StPlanApprove> pageList = this.page(page,approveQueryWrapper);
        List<StPlanApprove> voList = new ArrayList<>();
        List<StPlanApprove> list = pageList.getRecords();
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        for(StPlanApprove stPlanApprove:list){
            StPlanApproveVo stPlanApproveVo1 = new StPlanApproveVo();
            StPlanMan stPlanMan = iStPlanManService.getPlanManByCode(stPlanApprove.getPlanCode());
            BeanUtils.copyProperties(stPlanMan,stPlanApproveVo1);
            // 审核过的调整状态
            if(StringUtils.isNotEmpty(stPlanApprove.getApproveFlag())){
                // 翻译和增强处理
                if(ApproveConstant.APPROVE_PASS.equals(stPlanApprove.getApproveFlag())){
                    // 审核通过，设置状态为已生效
                    if(ApproveConstant.FZJH.equals(stPlanApprove.getApproveType())){
                        stPlanApproveVo1.setStatusName("已废止");
                    }else {
                        stPlanApproveVo1.setStatusName(PlanFlag.FLAG_CACHE.get(PlanFlag.YSX));
                    }
                }else{
                    stPlanApproveVo1.setStatusName(PlanFlag.FLAG_CACHE.get(PlanFlag.YBH));
                }
            }else {
                // 翻译和增强处理
                stPlanApproveVo1.setStatusName(PlanFlag.FLAG_CACHE.get(stPlanMan.getPlanFlag()));
            }

            DutyVo dutyVo = SpringContextUtils.getBean(IStCommonService.class).queryDutyByCode(stPlanMan.getHeadCode());
            if(dutyVo!=null){
                stPlanApproveVo1.setHeadName(dutyVo.initDutyNames());
                stPlanApproveVo1.setExecDepName(dutyVo.getDepartName());
            }else{
                stPlanApproveVo1.setHeadName("-");
            }
            DutyVo dutyVo1 = SpringContextUtils.getBean(IStCommonService.class).queryDutyByCode(stPlanMan.getApproveUser());
            if(dutyVo!=null){
                stPlanApproveVo1.setPlanApproveUserName(dutyVo1.initDutyNames());
                stPlanApproveVo1.setApproveDepCodeName(dutyVo1.getDepartName());
            }else{
                stPlanApproveVo1.setPlanApproveUserName("-");
            }
            String name = iSysDictService.queryDictTextByKey("projecttype",stPlanMan.getProjectType());
            if(StringUtils.isNotEmpty(name)){
                stPlanApproveVo1.setProjectTypeName(name);
            }else {
                stPlanApproveVo1.setProjectType("-");
            }

            BeanUtils.copyProperties(stPlanApprove,stPlanApproveVo1);
            SysUser sysUser1 = iSysUserService.getUserByName(stPlanApprove.getCreatedUser());
            if(sysUser1!=null){
                stPlanApproveVo1.setCreateUserName(sysUser1.getRealname());
            }else{
                stPlanApproveVo1.setCreateUserName("-");
            }
            stPlanApproveVo1.setApprovalTypeName(ApproveConstant.APPROVE_CACHE.get(stPlanApproveVo1.getApproveType()));
            voList.add(stPlanApproveVo1);
        }
        pageList.setRecords(voList);
        return pageList;
    }

    private String getNextPlanFlag(String approveFlag,String planFlag){
        // todo 计算状态
        if(ApproveConstant.APPROVE_PASS.equals(approveFlag)){
            // 审核通过，设置状态为已生效
            if(PlanFlag.DSH.equals(planFlag)){
                return PlanFlag.YSX;
            }else if(PlanFlag.BGDSH.equals(planFlag)){
                return PlanFlag.YBG;
            }else if(PlanFlag.FZDSH.equals(planFlag)){
                return PlanFlag.YFZ;
            }
        }else{
            if(PlanFlag.DSH.equals(planFlag)){
                return PlanFlag.YBH;
            }else if(PlanFlag.BGDSH.equals(planFlag)){
                return PlanFlag.BGYBH;
            }else if(PlanFlag.FZDSH.equals(planFlag)){
                return PlanFlag.FZYBH;
            }
        }
        return null;
    }

    @Override
    public boolean updateById(StPlanApprove entity) {
        // 执行完审核，修改plan
        StPlanMan stPlanMan = iStPlanManService.getPlanManByCode(entity.getPlanCode());
        if(stPlanMan==null){
            throw new JeecgBootException("审核的计划不存在");
        }
        StPlanMan newPlanMan = new StPlanMan();
        String nexPflag = getNextPlanFlag(entity.getApproveFlag(),stPlanMan.getPlanFlag());
        newPlanMan.setPlanFlag(nexPflag);
        newPlanMan.setApproveTime(new Date());
        // 设置审核信息
        newPlanMan.setApproveDes(entity.getApproveDes());
        newPlanMan.setId(stPlanMan.getId());
        iStPlanManService.updateById(newPlanMan);
        entity.setApproveTime(newPlanMan.getApproveTime());
        return super.updateById(entity);
    }
}
