package com.artfess.cqxy.bidManagement.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 cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.artfess.base.context.BaseContext;
import com.artfess.base.feign.SystemConfigFeignService;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.PageBean;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.BeanUtils;
import com.artfess.cqxy.bidManagement.model.BiddingManagement;
import com.artfess.cqxy.projectApproval.model.DecisionAnnualPlan;
import com.artfess.cqxy.projectApproval.model.DecisionBasis;
import com.artfess.cqxy.projectManagement.enums.ProjectStatusEnum;
import com.artfess.cqxy.projectManagement.manager.ProjectManagementManager;
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.cqxy.utils.EasyPoiStyle;
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 com.artfess.cqxy.bidManagement.dao.BiddingManagementDao;
import com.artfess.cqxy.bidManagement.manager.BiddingManagementManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.time.LocalDateTime;
import java.util.*;

/**
 * 招投标管理 - 招标管理表(BiddingManagement)表服务实现类
 *
 * @author 黎沐华
 * @since 2022-04-08 15:32:29
 */
@Service
public class BiddingManagementManagerImpl extends BaseManagerImpl<BiddingManagementDao, BiddingManagement> implements BiddingManagementManager {

    @Autowired
    private AccessoryManager accessoryManager;

    @Autowired
    private SystemConfigFeignService scfs;

    @Autowired
    private SysDictionaryManager sdm;

    @Autowired
    private BaseContext baseContext;

    @Autowired
    private GlobalRetrievalManager grm;

    @Autowired
    private ProjectManagementManager pmm;

    @Override
    public boolean saveOrUpdate(BiddingManagement entity) {
        boolean save = StringUtils.isEmpty(entity.getId());
//        handelEntity(entity);
        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.eight.getCode());
            if(StringUtils.isBlank(ele.getGroup())){
                ele.setGroup("BiddingManagement");
            }
            ele.setNode(ProjectStatusEnum.eight.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);
        //更新项目状态
        pmm.updateStatusById(entity.getProjectId(), Integer.valueOf(ProjectStatusEnum.eight.getCode()));
        // 同步到检索表
        GlobalRetrieval globalRetrieval= grm.getByBizId(entity.getId());
        handleRetrieval(save || BeanUtils.isEmpty(globalRetrieval) ?new GlobalRetrieval():globalRetrieval,entity);

        return savedMain && saveAcc;
    }

    private void handleRetrieval(GlobalRetrieval globalRetrieval,BiddingManagement entity){
        ProjectManagement projectManagement = pmm.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.twelve.getCode());
        globalRetrieval.setFunctionName(FunctionEnum.twelve.getName());
        globalRetrieval.setBizTableName(FunctionEnum.twelve.getTableName());
        globalRetrieval.setDetailsRoteUrl(FunctionEnum.twelve.getTableRoteUrl());
        globalRetrieval.setTableRoteUrl(FunctionEnum.twelve.getTableRoteUrl());
        globalRetrieval.setTableApiUrl(FunctionEnum.twelve.getTableApiUrl());
        globalRetrieval.setDetailsApiUrl(FunctionEnum.twelve.getDetailsApiUrl());
        globalRetrieval.setFunctionPath(FunctionEnum.twelve.getFunctionPath());
        globalRetrieval.setDocumentNumber(entity.getDocumentNumber());
        globalRetrieval.setSearchTitle(entity.getBidWinner()+"_"+entity.getBiddingAgency()+"_"+
                entity.getBiddingAgency()+"_"+entity.getFundsSource()+"_"+entity.getComplaintSituation()+"_"+entity.getBidWinnerAgentName()+"_"+entity.getBidWinnerAgentPhone()+"_"+
                entity.getImplementationPersonnelName()+"_"+entity.getImplementationPersonnelPhone()+"_"+entity.getRemarks()
                +"_"+entity.getActualPaymentMethod()+"_"+entity.getResponsibleUnit()+"_"+entity.getResponsiblePerson()+"_"+entity.getPayeePhone());
        grm.saveOrUpdate(globalRetrieval);
    }

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

    private void handelEntity(BiddingManagement entity) {
        String code = scfs.getNextIdByAlias("ztbgl_zbbh");
        entity.setDocumentNumber(code.substring(StringUtils.lastOrdinalIndexOf(code, "\"", 2) + 1, code.lastIndexOf("\"")));
//        BigDecimal saveMoney = entity.getBiddingFixedPrice().subtract(entity.getBidAmount2());
//        entity.setSaveMoney(saveMoney);
//        NumberFormat nf = NumberFormat.getPercentInstance();
//        nf.setMinimumFractionDigits(2);
//        try {
//            entity.setSaveMoneyRate(nf.format(saveMoney.divide(entity.getBiddingFixedPrice(),BigDecimal.ROUND_HALF_UP).doubleValue()));
//        } catch (Exception e) {
//            entity.setSaveMoneyRate("0");
//        }
//        String ownerUnit = entity.getOwnerUnit();
//        entity.setOwnerUnit(StringUtils.isBlank(ownerUnit)?"重庆西永微电子产业园区开发有限公司":ownerUnit);
    }

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

    @Override
    public PageList<BiddingManagement> queryAllByPage(QueryFilter<BiddingManagement> queryFilter) {
        BizUtils.handleFilter(queryFilter, "bbm", "pm");
        IPage<BiddingManagement> result =
                baseMapper.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass()));
        // 附件信息处理
        List<BiddingManagement> records = result.getRecords();
        for (BiddingManagement ele : records) {
            ele.setAccessoryInfo(accessoryManager.getAccessoryBySourceId(ele.getId()));
        }

        return new PageList<>(result);
    }

    @Override
    public void importExcelData(MultipartFile file, String projectId) {
        Assert.notNull(projectId, "项目ID不能为空");
        // 获取字典
        List<DictModel> biddingChargeType = sdm.queryDictListItemsByCode("zbfs");
//        List<DictModel> fundsSource = sdm.queryDictListItemsByCode("zbgl-zjly");
//        List<DictModel> winnerType = sdm.queryDictListItemsByCode("zbgl-zbdwxz");
//        List<DictModel> complaints = sdm.queryDictListItemsByCode("zbgl-sfyts");

        try(InputStream inputStream = file.getInputStream();) {
            // 获取数据，翻译字典
            List<BiddingManagement> data = ExcelImportUtil.importExcel(inputStream,BiddingManagement.class,new ImportParams());
            for(BiddingManagement ele:data){
                ele.setProjectId(projectId);
                ele.setBiddingChargeType(BizUtils.getDicCodeByValue(biddingChargeType, ele.getBiddingChargeType()));
                // 保存数据 & 同步到检索表
                save(ele);
                handleRetrieval(new GlobalRetrieval(),ele);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportDatatoExcel(QueryFilter<BiddingManagement> queryFilter, HttpServletResponse response) throws IOException {
        // 获取字典
        List<DictModel> chargeType = sdm.queryDictListItemsByCode("zbfs");
        List<DictModel> complaints = sdm.queryDictListItemsByCode("zbgl-sfyts");
        List<DictModel> payType = sdm.queryDictListItemsByCode("zbgl-tbbzjzffs");
        List<DictModel> judgeMethod = sdm.queryDictListItemsByCode("zbgl-pbff");
        List<DictModel> isLegal = sdm.queryDictListItemsByCode("zbgl-sfwfwg");
        List<DictModel> hasComplaint = sdm.queryDictListItemsByCode("zbgl-ywts");
        List<DictModel> investmentProperties = sdm.queryDictListItemsByCode("zbgl-zbdwxz");

        String fileName = "招标信息-导出结果";

        // 获取数据
        BizUtils.handleFilter(queryFilter, "bbm", "pm");
        List<BiddingManagement> data =
                baseMapper.queryAllByPage(
                        convert2IPage(new PageBean(0, -1, false)),
                        convert2Wrapper(queryFilter, currentModelClass())).
                    getRecords();
        if(null==data||data.size()==0){
            throw new RuntimeException("没有要导出的的数据！");
        }

        // 翻译字典
        for(BiddingManagement ele : data){
            ele.setBiddingChargeType(BizUtils.getDicValueByCode(chargeType, ele.getBiddingChargeType()));
            ele.setImplementationPersonnelPhone(BizUtils.getDicValueByCode(payType, ele.getImplementationPersonnelPhone()));
            ele.setImplementationPersonnelName(BizUtils.getDicValueByCode(judgeMethod, ele.getImplementationPersonnelName()));
            ele.setFundsSource(BizUtils.getDicValueByCode(isLegal, ele.getFundsSource()));
            ele.setHasComplaint(BizUtils.getDicValueByCode(hasComplaint, ele.getHasComplaint()));
            ele.setContractPaymentMethod(BizUtils.getDicValueByCode(investmentProperties, ele.getContractPaymentMethod()));
        }

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

        // 导出下载excel文件
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, BiddingManagement.class, data);
        ExcelUtil.downloadExcel(workbook, fileName, response);
    }

    @Override
    public void updateProjectIdByProiectId(String oldProjectIds, String newProjectId) {
        UpdateWrapper<BiddingManagement> wrapper = new UpdateWrapper<BiddingManagement>()
                .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);
        List<DictModel> chargeType = sdm.queryDictListItemsByCode("zbfs");
        if(null != list){
            for(DictModel dic : chargeType){
                String name = dic.getName();
                String value = dic.getValue();
                boolean isExistence = true;
                for(Map<String, Object> map : list){
                    String type = map.get("type")==null? "" : String.valueOf(map.get("type"));
                    if(type.equalsIgnoreCase(value)){
                        map.put("typeName", name);
                        isExistence = false;
                        break;
                    }
                }
                if(isExistence){
                    Map<String, Object> map = new HashMap<>();
                    map.put("type", value);
                    map.put("typeName", name);
                    map.put("total", 0);
                    list.add(map);
                }
            }

        }
        return list;
    }
}

