package com.artfess.cqxy.processManagermant.manager.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.artfess.base.context.BaseContext;
import com.artfess.base.feign.SystemConfigFeignService;
import com.artfess.base.feign.UCFeignService;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.query.QueryOP;
import com.artfess.base.util.BeanUtils;
import com.artfess.cqxy.contract.manager.ContractManager;
import com.artfess.cqxy.processManagermant.dao.ChangeManagementDao;
import com.artfess.cqxy.processManagermant.manager.ChangeManagementManager;
import com.artfess.cqxy.processManagermant.model.ChangeManagement;
import com.artfess.cqxy.projectManagement.dao.ProjectManagementDao;
import com.artfess.cqxy.projectManagement.enums.ProjectStatusEnum;
import com.artfess.cqxy.projectManagement.manager.ProjectManagementManager;
import com.artfess.cqxy.projectManagement.manager.ProjectPersonnelManager;
import com.artfess.cqxy.projectManagement.model.ProjectManagement;
import com.artfess.cqxy.search.enums.FunctionEnum;
import com.artfess.cqxy.search.manager.GlobalRetrievalManager;
import com.artfess.cqxy.search.model.GlobalRetrieval;
import com.artfess.cqxy.statistics.vo.StatisticsVo;
import com.artfess.cqxy.universal.manager.AccessoryManager;
import com.artfess.cqxy.universal.model.Accessory;
import com.artfess.cqxy.utils.BizUtils;
import com.artfess.poi.util.ExcelUtil;
import com.artfess.sysConfig.persistence.manager.SysDictionaryManager;
import com.artfess.sysConfig.persistence.param.DictModel;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 过程管理 - 变更管理(BizChangeManagement)表服务实现类
 *
 * @author 黎沐华
 * @since 2022-03-03 09:19:50
 */
@Service
public class ChangeManagementManagerImpl extends BaseManagerImpl<ChangeManagementDao, ChangeManagement> implements ChangeManagementManager {

    @Autowired
    private AccessoryManager accessoryManager;

    @Autowired
    private ProjectManagementManager pm;

    @Autowired
    private ContractManager cm;

    @Autowired
    private SystemConfigFeignService scfs;

    @Autowired
    private SysDictionaryManager sdm;

    @Autowired
    private GlobalRetrievalManager grm;

    @Autowired
    private BaseContext baseContext;

    @Autowired
    private ChangeManagementDao changeManagementDao;

    @Autowired
    private ProjectPersonnelManager projectPersonnelManager;

    @Autowired
    private UCFeignService ucFeignService;

    @Autowired
    private ProjectManagementDao projectManagementDao;

    @Override
    public boolean saveOrUpdate(ChangeManagement entity) {
        boolean save = StringUtils.isEmpty(entity.getId());
//        String changeCode = scfs.getNextIdByAlias("gcgl_bgbh");
//        entity.setChangeCode(changeCode.substring(StringUtils.lastOrdinalIndexOf(changeCode,"\"",2)+1, changeCode.lastIndexOf("\"")));
        boolean savedMain = super.saveOrUpdate(entity);
        // 处理附件信息
        List<Accessory> flag = entity.getAccessoryInfo();//处理空指针
        List<Accessory> accessoryList = null == flag ? new ArrayList<>() : flag;
        for (Accessory ele : accessoryList) {
            ele.setSourceId(entity.getId());
            ele.setProjectId(entity.getProjectId());
            ele.setDirectory(ProjectStatusEnum.eleven.getCode());
            ele.setGroup("ChangeManagement");
            ele.setNode(ProjectStatusEnum.eleven.getCode());
            ele.setCreateBy(baseContext.getCurrentUserId());
            ele.setCreateName(baseContext.getCurrentUserName());
            ele.setCreateTime(LocalDateTime.now());
        }
        // 先清空该ID下的所有附件信息再添加
        accessoryManager.removeBySourceId(entity.getId());
        // 如果没有附件则返回true，不进入添加
        boolean saveAcc = accessoryList.size() == 0 || accessoryManager.saveAccess(accessoryList);
        //更新项目状态
        pm.updateStatusById(entity.getProjectId(), Integer.valueOf(ProjectStatusEnum.eleven.getCode()));
        // 同步到检索表
        GlobalRetrieval globalRetrieval= grm.getByBizId(entity.getId());
        handleRetrieval(save || BeanUtils.isEmpty(globalRetrieval) ?new GlobalRetrieval():globalRetrieval,entity);

        return savedMain && saveAcc;
    }

    private void handleRetrieval(GlobalRetrieval globalRetrieval, ChangeManagement entity){
        ProjectManagement projectManagement = pm.getById(entity.getProjectId());
        globalRetrieval.setProjectId(entity.getProjectId());
        globalRetrieval.setProjectName(projectManagement.getProjectName());
        globalRetrieval.setPersonCharge(projectManagement.getProjectManager());
        globalRetrieval.setArchivesType(1);
        globalRetrieval.setBizDataId(entity.getId());
        globalRetrieval.setFunctionCode(FunctionEnum.sicteen.getCode());
        globalRetrieval.setFunctionName(FunctionEnum.sicteen.getName());
        globalRetrieval.setBizTableName(FunctionEnum.sicteen.getTableName());
        globalRetrieval.setDetailsRoteUrl(FunctionEnum.sicteen.getTableRoteUrl());
        globalRetrieval.setTableRoteUrl(FunctionEnum.sicteen.getTableRoteUrl());
        globalRetrieval.setTableApiUrl(FunctionEnum.sicteen.getTableApiUrl());
        globalRetrieval.setDetailsApiUrl(FunctionEnum.sicteen.getDetailsApiUrl());
        globalRetrieval.setFunctionPath(FunctionEnum.sicteen.getFunctionPath());
        globalRetrieval.setDocumentNumber(entity.getChangeCode());
        globalRetrieval.setName(entity.getChangeName());
        globalRetrieval.setSearchTitle(entity.getChangeName()+"_"+entity.getChangeCode()+"_"+entity.getChangeContractName()+"_"+
                entity.getChangeUnit()+"_"+entity.getChangeReason()+"_"+entity.getChangeContent()+"_"+entity.getRemarks());
        grm.saveOrUpdate(globalRetrieval);
    }

    @Override
    public boolean deleteByIds(List<String> ids) {
        // 同步删除检索表中的信息
        for(String ele:ids){
            grm.remove(1,ele);
        }
        return removeByIds(ids);
    }

    @Override
    public ChangeManagement getById(String id) {
        ChangeManagement result = changeManagementDao.getById(id);
        result.setAccessoryInfo(accessoryManager.getAccessoryBySourceId(id));
        return result;
    }

    @Override
    public PageList<ChangeManagement> queryAllByPage(QueryFilter<ChangeManagement> queryFilter) {
//        BizUtils.handleFilter(queryFilter, "bcm", true);
        queryFilter.addFilter("pm.IS_DELE_", "0", QueryOP.EQUAL);
        queryFilter.addFilter("bcm.IS_DELE_", "0", QueryOP.EQUAL);
        queryFilter.addFilter("pm.VALID_FLAG_", 1, QueryOP.EQUAL);

        if(BizUtils.isProjectIdFields(queryFilter.getQuerys())){
            List<String> projectList = BizUtils.handProjectAuthByUser(ucFeignService, projectPersonnelManager, projectManagementDao);
            if(null!=projectList&&projectList.size()>0){
                queryFilter.addFilter("bcm.PROJECT_ID_", projectList, QueryOP.IN);
            }
        }
        IPage<ChangeManagement> result =
                changeManagementDao.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass()));
        // 附件信息处理
        List<ChangeManagement> records = result.getRecords();
        for (ChangeManagement ele : records) {
            ele.setAccessoryInfo(accessoryManager.getAccessoryBySourceId(ele.getId()));
        }

        return new PageList<>(result);
    }



    @Override
    public void importExcelData(MultipartFile file, String projectId, String contractId, String contractName) {
        Assert.notNull(projectId,"项目ID不能为空");
        List<DictModel> chargeType = sdm.queryDictListItemsByCode("gcgl-bglx");
        try(InputStream inputStream = file.getInputStream();) {
            // 获取数据
            List<ChangeManagement> data = ExcelImportUtil.importExcel(inputStream,ChangeManagement.class,new ImportParams());
            for(ChangeManagement ele:data){
                ele.setProjectId(projectId);
                ele.setChangeContractId(contractId);
                ele.setChangeContractName(contractName);
                ele.setChangeType(BizUtils.getDicCodeByValue(chargeType, ele.getChangeType()));
                String changeCode = scfs.getNextIdByAlias("gcgl_bgbh");
                ele.setChangeCode(changeCode.substring(StringUtils.lastOrdinalIndexOf(changeCode,"\"",2)+1, changeCode.lastIndexOf("\"")));
                // 保存数据 & 同步到检索表
                save(ele);
                handleRetrieval(new GlobalRetrieval(),ele);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportDataToExcel(QueryFilter<ChangeManagement> queryFilter, HttpServletResponse response) throws IOException {
        // 获取字典
        List<DictModel> chargeType = sdm.queryDictListItemsByCode("gcgl-bglx");

        // 获取数据
        queryFilter.getPageBean().setPage(-1);
        BizUtils.handleFilter(queryFilter, "bcm", false);

        List<ChangeManagement> data = changeManagementDao.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass())).
                getRecords();
        if(null==data||data.size()==0){
            throw new RuntimeException("没有要导出的的数据！");
        }
        String fileName = "过程管理-变更管理-导出结果";

        // 翻译字典
        for(ChangeManagement ele : data){
            ele.setChangeType(BizUtils.getDicValueByCode(chargeType, ele.getChangeType()));
        }

        // EasyPoi 导出参数、样式、表格格式设置
        ExportParams exportParams = BizUtils.getExportParams(fileName);
        fileName += ".xlsx";

        // 导出下载excel文件
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ChangeManagement.class, data);
        workbook.getSheetAt(0).setColumnWidth(0,5500);
        for(int i = 6;i<9;i++){
            workbook.getSheetAt(0).setColumnWidth(i,7000);
        }
        ExcelUtil.downloadExcel(workbook, fileName, response);
    }

    @Override
    public void updateProjectIdByProiectId(String oldProjectIds, String newProjectId) {
        UpdateWrapper<ChangeManagement> wrapper = new UpdateWrapper<ChangeManagement>()
                .set(StringUtils.isNotBlank(newProjectId), "PROJECT_ID_", newProjectId)
                .in("PROJECT_ID_", Arrays.asList(oldProjectIds.split(",")));
        this.update(wrapper);
    }

    @Override
    public List<Map<String, Object>> queryInvestment(StatisticsVo statisticsVo) {
        List<Map<String, Object>> list = this.baseMapper.queryInvestment(statisticsVo);
        if(null != list){
            List<DictModel> chargeType = sdm.queryDictListItemsByCode("gcgl-bglx");
            for (Map map : list){
                String type = String.valueOf(map.get("type"));
                map.put("typeName", BizUtils.getDicValueByCode(chargeType, type));
            }
        }
        return list;
    }

    @Override
    public List<Map<Integer, Object>> engineeringChangeNumber(StatisticsVo statisticsVo) {
        List<Map<String, Object>> list = this.baseMapper.engineeringChangeNumber(statisticsVo);
        List<Map<Integer, Object>> result = new ArrayList<>();
        if(null != list){
            for (int m = 1; m <= 12; m++) {
                boolean isMouth = true;
                for (Map<String, Object> map : list) {
                    Integer moutn = map.get("mouth") == null ? 0 : (Integer) map.get("mouth");
                    Object total = map.get("total");
                    if (m == moutn) {
                        Map<Integer, Object> mp = new HashMap<>();
                        mp.put(m, total);
                        result.add(mp);
                        isMouth = false;
                    }
                }
                if (isMouth) {
                    Map<Integer, Object> mp = new HashMap<>();
                    mp.put(m, 0);
                    result.add(mp);
                }

            }
        }
        return result;
    }

    @Override
    public BigDecimal SumAmount2(String pid){
        return baseMapper.SumAmount2(pid);
    }


}

