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

import com.artfess.base.feign.UCFeignService;
import com.artfess.base.query.*;
import com.artfess.base.util.BeanUtils;
import com.artfess.cqxy.bidManagement.manager.BiddingManagementManager;
import com.artfess.cqxy.bidManagement.model.BiddingManagement;
import com.artfess.cqxy.contract.manager.ContractManager;
import com.artfess.cqxy.contract.model.Contract;
import com.artfess.cqxy.designEstimate.manager.EstimateManager;
import com.artfess.cqxy.designEstimate.model.Estimate;
import com.artfess.cqxy.ledger.manager.BiddingLedgerManager;
import com.artfess.cqxy.ledger.vo.BiddingLedgerVo;
import com.artfess.cqxy.projectManagement.dao.ProjectManagementDao;
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.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.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 黎沐华
 * 2022/5/25 15:51
 */
@Service
public class BiddingLedgerManagerImpl implements BiddingLedgerManager {

    @Autowired
    private BiddingManagementManager biddingManager;
    @Autowired
    private ProjectManagementManager projectManager;
    @Autowired
    private EstimateManager estimateManager;
    @Autowired
    private ContractManager contractManager;
    @Autowired
    private SysDictionaryManager sdm;
    @Autowired
    private ProjectPersonnelManager projectPersonnelManager;

    @Autowired
    private UCFeignService ucFeignService;

    @Autowired
    private ProjectManagementDao projectManagementDao;

    @Override
    public PageList<BiddingLedgerVo> queryByPage(QueryFilter<BiddingManagement> queryFilter) {
//        Map<String, Object> result = new HashMap<>(4);
        PageList<BiddingLedgerVo> pageListvo = new PageList<>();
//        queryFilter.withSorter(new FieldSort("PROJECT_TYPE_", Direction.ASC));
//        queryFilter.withSorter(new FieldSort("PROJECT_ID_", Direction.ASC));
        queryFilter.withSorter(new FieldSort("bbm.COMMENCEMENT_DATE_", Direction.ASC));
        if (BizUtils.isProjectIdFields(queryFilter.getQuerys())) {
            List<String> projectList = BizUtils.handProjectAuthByUser(ucFeignService, projectPersonnelManager, projectManagementDao);
            if (null != projectList && projectList.size() > 0) {
                queryFilter.addFilter("bbm.PROJECT_ID_", projectList, QueryOP.IN);
            }
        }
        PageList pageList = biddingManager.queryAllByPage(queryFilter);
        List<BiddingManagement> biddingList = null == pageList.getRows() ? new ArrayList<>() : pageList.getRows();
        pageListvo.setPage(pageList.getPage());
        pageListvo.setTotal(pageList.getTotal());
        pageListvo.setRows(handleAppro(biddingList));
        pageListvo.setPageSize(pageList.getPageSize());
//        result.put("data", handleAppro(biddingList));
//        result.put("total", pageList.getTotal());
//        result.put("page", pageList.getPage());
//        result.put("pageSize", pageList.getPageSize());
        return pageListvo;
    }

    private List<BiddingLedgerVo> handleAppro(List<BiddingManagement> projectList) {
        List<BiddingLedgerVo> data = new ArrayList<>();
        for (BiddingManagement ele : projectList) {
            BiddingLedgerVo temp = new BiddingLedgerVo();
            // 项目信息
            ProjectManagement project = projectManager.getOne(new QueryWrapper<ProjectManagement>()
                    .eq("ID_", ele.getProjectId()).eq("IS_DELE_", "0").last("limit 1"));
            project = BeanUtils.isEmpty(project) ? new ProjectManagement() : project;
            temp.setProjectId(project.getId());
            temp.setProjectName(project.getProjectName());
            temp.setProjectManager(project.getProjectManager());
            temp.setCommencementTime(project.getCommencementTime());
            temp.setCompletionTime(project.getCompletionTime());
            temp.setYear(null != project.getCompletionTime() ? BizUtils.handleDateFormat(project.getCompletionTime()).split("-")[0] + "年" : "");
            // 概算信息
            Estimate estimate = estimateManager.getOne(new QueryWrapper<Estimate>().
                    eq("PROJECT_ID_", ele.getProjectId()).eq("IS_DELE_", "0").orderBy(true, false, "ESTABLISHMENT_DATE_").last("limit 1"));
            estimate = BeanUtils.isEmpty(estimate) ? new Estimate() : estimate;
            String documentNumber = StringUtils.isBlank(estimate.getDocumentNumber()) ? "" : estimate.getDocumentNumber();
            temp.setPreliminaryEstimate(null == estimate.getTotalEstimate() ? "" : estimate.getTotalEstimate());
            temp.setSourceFunds(estimate.getSourceFunds());

            // 招标信息
            List<DictModel> chargeType = sdm.queryDictListItemsByCode("zbfs");
            List<DictModel> hasComplaint = sdm.queryDictListItemsByCode("zbgl-ywts");
            temp.setDocumentNumber(ele.getDocumentNumber());
            temp.setBiddingChargeType(BizUtils.getDicValueByCode(chargeType, ele.getBiddingChargeType()));
            temp.setBidAmountExamine(yuanToWanyuan(ele.getBidAmountExamine()));
            temp.setBidWinner(ele.getBidWinner());
            temp.setBidWinnerPhone(ele.getBidWinnerAgentPhone());
            temp.setBidAmount(yuanToWanyuan(ele.getBidAmount()));
            temp.setActualSettlementAmount(yuanToWanyuan(ele.getActualSettlementAmount()));
            temp.setBiddingAgency(ele.getBiddingAgency());
            temp.setResponsibleUnit(ele.getResponsibleUnit());
            temp.setResponsiblePerson(ele.getResponsiblePerson());
            temp.setProjectBudget(yuanToWanyuan(ele.getProjectBudget()));
            //字典，投标保证金支付方式
            List<DictModel> implementationDic = sdm.queryDictListItemsByCode("zbgl-tbbzjzffs");
            temp.setImplementationPersonnelPhone(StringUtils.isBlank(ele.getImplementationPersonnelPhone()) ? "现金" : BizUtils.getDicValueByCode(implementationDic, ele.getImplementationPersonnelPhone()));
            temp.setImplementationPersonnelPhoneUrl(ele.getImplementationPersonnelPhoneUrl());
            List<DictModel> pbffDic = sdm.queryDictListItemsByCode("zbgl-pbff");
            temp.setImplementationPersonnelName(BizUtils.getDicValueByCode(pbffDic, ele.getImplementationPersonnelName()));
            temp.setCommencementDate(ele.getCommencementDate());
            temp.setFundsSource(StringUtils.isBlank(ele.getFundsSource()) ? "否" : ele.getFundsSource());
            temp.setFundsSourceUrl(ele.getFundsSourceUrl());
            //字段，有无投诉
            temp.setHasComplaint(StringUtils.isBlank(ele.getHasComplaint()) ? "无" : BizUtils.getDicValueByCode(hasComplaint, ele.getHasComplaint()));
            temp.setHasComplaintUrl(ele.getHasComplaintUrl());
            temp.setComplaintSituation(ele.getComplaintSituation());
            temp.setActualPaymentMethod(ele.getActualPaymentMethod());
            List<DictModel> paymentMethodDic = sdm.queryDictListItemsByCode("zbgl-zbdwxz");
            temp.setContractPaymentMethod(BizUtils.getDicValueByCode(paymentMethodDic, ele.getContractPaymentMethod()));
            temp.setBidWinnerAgentName(StringUtils.isBlank(ele.getBidWinnerAgentName()) ? "" : ele.getBidWinnerAgentName() + "\n"
                    + (StringUtils.isBlank(ele.getPayeePhone()) ? "" : ele.getPayeePhone()));
            temp.setCompletionDate(ele.getCompletionDate());
            temp.setPayeeNameAccount(ele.getPayeeNameAccount());
            temp.setPayeePhone(ele.getPayeePhone());
            temp.setRemarks(ele.getRemarks());

            // 合同信息
            QueryWrapper<Contract> contractQueryWrapper = new QueryWrapper<Contract>()
                    .eq("PROJECT_ID_", ele.getProjectId()).eq("IS_DELE_", "0")
                    .like("SECOND_PARTY_", ele.getBidWinner()).last("limit 1");
            Contract contract = contractManager.getOne(contractQueryWrapper);
            contract = BeanUtils.isEmpty(contract) ? new Contract() : contract;

            List<DictModel> moldDic = sdm.queryDictListItemsByCode("zhtgl-htfl");
            temp.setTreatyContents(contract.getTreatyContents());
            temp.setMold(BizUtils.getDicValueByCode(moldDic, contract.getMold()));
            temp.setPayeeAccountPhone(contract.getPayeeAccountPhone());
            temp.setPayType(contract.getTreatyContents());
            // 封进List
            data.add(temp);
        }
        return data;
    }

    public String yuanToWanyuan(String rmb) {
        if (StringUtils.isNotBlank(rmb)) {
            BigDecimal newRmb = new BigDecimal(rmb);
            return newRmb.divide(new BigDecimal(10000)).setScale(2, BigDecimal.ROUND_HALF_UP)
                    .stripTrailingZeros().toPlainString();
        }
        return "";
    }

    @Override
    public void exportDataToExcel(QueryFilter<BiddingManagement> queryFilter, HttpServletResponse response) throws IOException {
        // 文件信息
        String fileName = "";
        String title = "工程建设项目招投标基本情况表";
        for (QueryField qf : queryFilter.getQuerys()) {
            if ("bbm.COMMENCEMENT_DATE_".equalsIgnoreCase(qf.getProperty())) {
                if (QueryOP.BETWEEN.equals(qf.getOperation())){
                    fileName += String.valueOf(Arrays.asList(qf.getValue()).get(0)).split("-")[0].replace("[","")+"年";
                }
                if (QueryOP.EQUAL.equals(qf.getOperation())){
                    fileName += qf.getValue()+"年";
                }
            }
        }

        fileName += "招投标台账";

        // 字典
        List<DictModel> chargeType = sdm.queryDictListItemsByCode("zbfs");
        List<DictModel> hasComplaint = sdm.queryDictListItemsByCode("zbgl-ywts");
        List<DictModel> biddingChargeType = sdm.queryDictListItemsByCode("zbfs");
        List<DictModel> implementationDic = sdm.queryDictListItemsByCode("zbgl-tbbzjzffs");
        List<DictModel> moldDic = sdm.queryDictListItemsByCode("zhtgl-htfl");
        List<DictModel> pbffDic = sdm.queryDictListItemsByCode("zbgl-pbff");

        // 创建excel工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建excel表
        HSSFSheet sheet = workbook.createSheet(fileName);
        //创建样式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        //设置字体
        HSSFFont font = workbook.createFont();
        //设置字体名称
        font.setFontName("宋体");
        cellStyle.setFont(font);
        List<String> informant = new ArrayList<>();
        informant.addAll(Arrays.asList(new String[]{"单位名称", "", "", "", "", "", "", "填报人", "", "", "", "", "", "", "审阅人", "", "", "", "", "", "填报时间", "", ""}));

        // 处理表头
        // 投诉人及联系方式
        List<String> headers = new ArrayList<>();
        headers.addAll(Arrays.asList(new String[]{"序号", "开标日期", "经办人", "项目名称", "项目概算(万元)", "招标代理机构名称",
                "资金来源（含BT、PPP等）", "招标方式", "有无投诉、投诉人及联系方式", "投诉情况", "中标单位", "中标单位代理人姓名、电话", "评审限价（万元）",
                "中标金额（万元）", "开工时间", "竣工时间", "实施施工人（承建人）、电话", "合同约定付款方式", "实际付款方式及情况", "收款人及账号、电话",
                "实际结算金额（万元）", "审计情况及存在主要问题", "备注"}));
        // 标题行写入数据
        // 第一行
        HSSFRow titleRow0 = sheet.createRow(0);
        BizUtils.handelCell(workbook, fileName, titleRow0.createCell(0), title, true);
        // 第二行
        HSSFRow titleRow1 = sheet.createRow(1);
        for (int i = 0; i < informant.size(); i++) {
            BizUtils.handelCell(workbook, fileName, titleRow1.createCell(i), informant.get(i));
        }
        // 第三行
        HSSFRow titleRow2 = sheet.createRow(2);
        for (int i = 0; i < headers.size(); i++) {
            BizUtils.handelCell(workbook, fileName, titleRow2.createCell(i), headers.get(i));
        }
        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 22));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 3));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 15, 16));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 21, 22));

        // 获取数据
//        queryFilter.withSorter(new FieldSort("con.MOLD_",Direction.ASC));
        queryFilter.withSorter(new FieldSort("PROJECT_TYPE_", Direction.ASC));
        queryFilter.withSorter(new FieldSort("PROJECT_ID_", Direction.ASC));
        queryFilter.getPageBean().setPageSize(-1);
        List<BiddingLedgerVo> result = handleAppro(biddingManager.queryAllByPage(queryFilter).getRows());
        List<BiddingLedgerVo> data = null == result ? new ArrayList<>() : result;

        // 数据行,从3行开始,共data.size行
        int row = 3;
        // 当前类型标记
        int currentType = 0;
        // 计数器，当前分类下的序号标记
        int counter = 1;

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = dateFormat.format(new Date());

        for (int i = 0; i < data.size(); i++) {
            HSSFRow listRow = sheet.createRow(row + i);// 创建行
            BiddingLedgerVo ele = data.get(i);
            BizUtils.setDefaultValue(ele);

            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(0), String.valueOf(counter));

            String commencementDate = BizUtils.handleDateFormat(ele.getCommencementDate());
            if (StringUtils.isBlank(commencementDate) || commencementDate.equalsIgnoreCase(nowDate)) {
                commencementDate = " ";
            }
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(1), commencementDate);

            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(2), ele.getProjectManager());
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(3), ele.getProjectName());
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(4), ele.getPreliminaryEstimate());
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(5), ele.getBiddingAgency());
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(6), ele.getSourceFunds());
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(7), BizUtils.getDicValueByCode(biddingChargeType, ele.getBiddingChargeType()));
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(8), ele.getHasComplaint());
            // 投诉情况
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(9), ele.getComplaintSituation());
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(10), ele.getBidWinner());
            //中标单位代理人姓名、电话 字段不对应  xxxPhone 对应 中标人资质等级 :)
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(11), ele.getBidWinnerAgentName() + "\n" + ele.getPayeePhone());
            // 评审限价（万元）
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(12), ele.getBidAmountExamine());
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(13), ele.getBidAmount());

            String commencementTime = BizUtils.handleDateFormat(ele.getCommencementTime());
            if (StringUtils.isBlank(commencementTime) || commencementTime.equalsIgnoreCase(nowDate)) {
                commencementTime = " ";
            }
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(14), commencementTime);

            String completionTime = BizUtils.handleDateFormat(ele.getCompletionTime());
            if (StringUtils.isBlank(completionTime) || completionTime.equalsIgnoreCase(nowDate)) {
                completionTime = " ";
            }
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(15), completionTime);
            //实施施工人（承建人）、电话
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(16), ele.getBidWinnerAgentName() + "\n" + ele.getPayeePhone());

            //合同约定付款方式
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(17), ele.getTreatyContents());
            //实际付款方式及情况
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(18), ele.getPayType());

            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(19), ele.getPayeeNameAccount() + "\n" + ele.getPayeeAccountPhone());

            // 实际结算金额（万元)
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(20), "");
            // 审计情况及存在主要问题
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(21), "");
//            责任人和责任单位
//            BizUtils.handelCell(workbook, cellStyle, fileName, listRow.createCell(23), "");
            BizUtils.handelCell(workbook, cellStyle, font, fileName, listRow.createCell(22), ele.getRemarks());
            counter++;
        }

        sheet.setColumnWidth(0, 1800);
        for (int i = 1; i < headers.size(); i++) {
            sheet.setColumnWidth(i, 4000);
        }

        ExcelUtil.downloadExcel(workbook, fileName, response);
    }

}
