package org.jeecg.modules.stm.plan.main.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.stm.common.service.IStCommonService;

import org.jeecg.modules.stm.common.vo.DutyVo;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysCategoryService;
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.springframework.util.ObjectUtils;
import org.jeecg.modules.stm.plan.approve.entity.StPlanApprove;
import org.jeecg.modules.stm.plan.approve.service.IStPlanApproveService;
import org.jeecg.modules.stm.plan.main.constant.PlanFlag;
import org.jeecg.modules.stm.plan.main.entity.StPlanMan;
import org.jeecg.modules.stm.plan.main.event.PlanFlagEvent;
import org.jeecg.modules.stm.plan.main.mapper.StPlanManMapper;
import org.jeecg.modules.stm.plan.main.service.IStPlanManService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.stm.plan.main.vo.StPlanManVo;
import org.jeecg.modules.stm.plan.trance.entity.StPlanTrance;
import org.jeecg.modules.stm.plan.trance.service.IStPlanTranceService;
import org.jeecg.modules.stm.utils.StmConstans;
import org.jeecg.modules.stm.utils.UserUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 计划编制
 * @Author: jeecg-boot
 * @Date:   2023-07-15
 * @Version: V1.0
 */
@Service
public class StPlanManServiceImpl extends ServiceImpl<StPlanManMapper, StPlanMan> implements IStPlanManService {
    private static final String NO_PRE = "PL";
    private static final  int NO_SIZE = 5;

    @Autowired
    private ISysDictService iSysDictService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private IStPlanTranceService iStPlanTranceService;

    @Autowired
    private ISysCategoryService sysCategoryService;
    /**
     * 获取业务号
     * @return
     */
    private String bizNo(){
        QueryWrapper<StPlanMan> wapper = new QueryWrapper();
        wapper.orderByDesc("PLAN_CODE");
        wapper.last("limit 1");
        StPlanMan noUpper = super.baseMapper.selectOne(wapper);
        if(noUpper == null) {
            return NO_PRE+ StringUtils.leftPad("1",NO_SIZE,"0");
        }else{
            // 如果不为空+1
            int no  = Integer.valueOf(noUpper.getPlanCode().replace(NO_PRE,""))+1;
            String str = ""+no;
            return  NO_PRE+StringUtils.leftPad(str,NO_SIZE,"0");
        }
    }

    private void checkPlanDate(StPlanMan entity){
        if(entity==null||entity.getPlanEndDate()==null){
            return;
        }
        if(entity.getPlanEndDate().before(entity.getPlanStartDate())){
            throw new JeecgBootException("计划结束日期不能早于计划开始日期");
        }
    }

    @Override
    public boolean save(StPlanMan entity) {
        String no = bizNo();
        entity.setPlanCode(no);
        entity.setPlanFlag(PlanFlag.BZZ);
        String userCode = UserUtil.getUserCode();
        entity.setCreatedUser(userCode);
        entity.setUpdatedUser(userCode);
        entity.setValid(StmConstans.DEFAULT_VALID);
        checkPlanDate(entity);
        return super.save(entity);
    }

    @Override
    public boolean updateById(StPlanMan entity){
        String userCode = UserUtil.getUserCode();
        entity.setUpdatedUser(userCode);
        checkPlanDate(entity);
        return super.updateById(entity);
    }

    @Override
    public boolean updateByIdOne(StPlanMan entity){

        checkPlanDate(entity);
        return super.updateById(entity);
    }


    @Override
    public <E extends IPage<StPlanMan>> E page(E page, Wrapper<StPlanMan> queryWrapper) {
        IPage<StPlanMan> pageList = super.page(page, queryWrapper);
        List<StPlanMan> voList = new ArrayList<>();
        List<StPlanMan> list = pageList.getRecords();
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        for(StPlanMan stPlanMan:list){
            String tableName = getTableNameByMyBatisPlus();

            StPlanManVo stPlanManVo = new StPlanManVo();
            BeanUtils.copyProperties(stPlanMan,stPlanManVo);
            // 翻译和增强处理
            stPlanManVo.setStatusName(PlanFlag.FLAG_CACHE.get(stPlanManVo.getPlanFlag()));

            DutyVo dutyVo = SpringContextUtils.getBean(IStCommonService.class).queryDutyByCode(stPlanMan.getHeadCode());
            if(dutyVo!=null){
                stPlanManVo.setHeadName(dutyVo.initDutyNames());
                stPlanManVo.setExecDepName(dutyVo.getDepartName());
            }else{
                stPlanManVo.setHeadName("-");
            }
            //String name = iSysDictService.queryDictTextByKey("projecttype",stPlanMan.getProjectType());

            SysCategory sysCategory = null; //sysCategoryService.queryById(stPlanMan.getProjectType());

            if(sysCategory!=null){
                stPlanManVo.setProjectTypeName(sysCategory.getName());
            }else {
                stPlanManVo.setProjectType("-");
            }
            stPlanManVo.setOptDesbak(stPlanManVo.getOptDes());
            voList.add(stPlanManVo);
        }
        pageList.setRecords(voList);
        return (E) pageList;
    }

    @Override
    public void handle(StPlanMan stPlanMan) {
        StPlanMan stPlanManNew = new StPlanMan();
        stPlanManNew.setId(stPlanMan.getId());
        stPlanManNew.setPlanFlag(stPlanMan.getPlanFlag());
        String userCode = UserUtil.getUserCode();
        stPlanManNew.setUpdatedUser(userCode);
        super.updateById(stPlanManNew);
        // 发布状态变更事件
        SpringContextUtils.getApplicationContext().publishEvent(new PlanFlagEvent(stPlanManNew));
    }

    @Override
    public void handleChange(StPlanMan stPlanMan) {
        checkPlanDate(stPlanMan);
        String userCode = UserUtil.getUserCode();
        stPlanMan.setUpdatedUser(userCode);
        fistRecord(stPlanMan.getPlanCode());
        this.updateById(stPlanMan);
        changeRecord(stPlanMan.getPlanCode());
        // 发布状态变更事件
        SpringContextUtils.getApplicationContext().publishEvent(new PlanFlagEvent(stPlanMan));
    }

    @Override
    public StPlanMan getPlanManByCode(String planCode){
        QueryWrapper<StPlanMan> queryWrapperTemp = new QueryWrapper();
        queryWrapperTemp.eq("PLAN_CODE",planCode);
        queryWrapperTemp.last("limit 1");
        StPlanMan stPlanMan = getOne(queryWrapperTemp);
        return stPlanMan;
    }

    @Override
    public IPage<StPlanMan> defPage(StPlanMan stPlanMan, Map<String, String[]> parameterMap, Integer pageNo, Integer pageSize) {
        QueryWrapper<StPlanMan> queryWrapper = QueryGenerator.initQueryWrapper(stPlanMan, parameterMap);
        String [] planFlags = parameterMap.get("planFlag[]");
        if(!ObjectUtils.isEmpty(planFlags)){
            queryWrapper.in("PLAN_FLAG",planFlags);
        }
        String userCode = UserUtil.getUserCode();
        // 查询用户岗位
        SysUser sysUser = iSysUserService.getUserByName(userCode);
        String [] planSelect = parameterMap.get("planSelect");
        // 计划管理岗可以查询所有
        if(!"PL001".equals(sysUser.getPost())&& (planSelect==null || !"1".equals(planSelect[0]))) {
           // queryWrapper.eq("CREATED_USER", userCode); //why mod 20250528
        }
        Page<StPlanMan> page = new Page<StPlanMan>(pageNo, pageSize);
        return this.page(page,queryWrapper);
    }

    private void changeRecord(String planCode) {
        StPlanMan stPlanMan = getPlanManByCode(planCode);
        StPlanTrance stPlanTrance = new StPlanTrance();
        BeanUtils.copyProperties(stPlanMan,stPlanTrance);
        stPlanTrance.setId(null);
        iStPlanTranceService.save(stPlanTrance);
    }

    private void fistRecord(String planCode) {
        QueryWrapper<StPlanTrance> tranceQueryWrapper = new QueryWrapper<>();
        tranceQueryWrapper.eq("PLAN_CODE",planCode);
        long count = iStPlanTranceService.count(tranceQueryWrapper);
        if(count>0){
            return;
        }
        changeRecord(planCode);
    }

    @Override
    public boolean removeById(Serializable id) {
        StPlanMan stPlanMan = this.getById(id);
        if(stPlanMan!=null){
            QueryWrapper<StPlanTrance> tranceQueryWrapper = new QueryWrapper<>();
            tranceQueryWrapper.eq("PLAN_CODE",stPlanMan.getPlanCode());
            iStPlanTranceService.remove(tranceQueryWrapper);
            IStPlanApproveService iStPlanApproveService = SpringContextUtils.getBean(IStPlanApproveService.class);
            QueryWrapper<StPlanApprove> approveQueryWrapper = new QueryWrapper<>();
            approveQueryWrapper.eq("PLAN_CODE",stPlanMan.getPlanCode());
            iStPlanApproveService.remove(approveQueryWrapper);
        }
        return super.removeById(id);
    }



    /**
     * 使用 MyBatis-Plus 的 TableInfoHelper 获取表名
     */
    public  String getTableNameByMyBatisPlus() {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(StPlanMan.class);
        if (tableInfo != null) {
            return tableInfo.getTableName();
        }
        return null;
    }
}
