package com.jwipc.contract.controller.pc;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.jwipc.constant.DictCode;
import com.jwipc.contract.constant.ModuleConst;
import com.jwipc.contract.dto.ContractCategoryDTO;
import com.jwipc.contract.dto.ContractDetailDTO;
import com.jwipc.contract.dto.ContractMroSaveDTO;
import com.jwipc.contract.dto.ContractReportDTO;
import com.jwipc.contract.entity.Contract;
import com.jwipc.contract.logic.ContractLogic;
import com.jwipc.contract.model.query.ChoseSupplierListQuery;
import com.jwipc.contract.model.query.ContractMangeQuery;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.exception.DaoException;
import com.jwipc.log.annotation.AuditLogInter;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.sys.client.DictClient;
import com.jwipc.sys.client.PurchaseGroupClient;
import com.jwipc.sys.client.TaxClient;
import com.jwipc.sys.client.dto.DictDTO;
import com.jwipc.sys.client.dto.PurchaseGroupDTO;
import com.jwipc.sys.client.dto.TaxDTO;
import com.jwipc.sys.dto.FinancialShareApiResultDTO;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * MRo合同管理控制器
 */
@RestController
@RequestMapping(ModuleConst.MODULE_ROOT + "/mroManage/rest")
@RequiredArgsConstructor
@Slf4j
public class ContractMroRestController {

    @Autowired
    ContractLogic contractLogic;

    private final DictClient dictClient;
    private final TaxClient taxClient;
    @Autowired
    PurchaseGroupClient purchaseGroupClient;

    @AuditLogInter(value = "查询", module = "MRO合同管理查询")
    @RequestMapping("/index/page")
    public PageView listPage(ContractMangeQuery mangeQuery) {
        mangeQuery.setIsMro(1);
        if(LoginUtil.isSupplier()){
            String supplierCode = LoginUtil.getSupplierCode();
            mangeQuery.setSupplierCode(supplierCode);
            mangeQuery.setState(3);
            List<String> collect =new ArrayList<>();
            collect.add(mangeQuery.getContractPurchaseGroup());
        }else{
            List<PurchaseGroupDTO> dtoList = purchaseGroupClient.listAll(LoginUtil.getUserId());
            //判断是否为空，不为空设置采购组list
            if(CollUtil.isNotEmpty(dtoList)){
                List<String> collect = dtoList.stream().map(PurchaseGroupDTO::getPurchaseGroupCode).collect(Collectors.toList());
                mangeQuery.setList(collect);
            }
        }
        return contractLogic.listPage(mangeQuery);
    }


    @PostMapping("/report/export")
    public void reportExport(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final List<ContractReportDTO> exportData = contractLogic.listAll(JSON.parseObject(queryStr, ContractMangeQuery.class));
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"MRO合同报表-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, exportFiled);
    }

    @PostMapping("/updateTime")
    public ResponseEntity updateTime(String ids,String deliveryDate,String invoiceTime) {
        final String[] split = ids.split(StrUtil.COMMA);
        final List<String> idList = Arrays.asList(split);
        contractLogic.updateTime(idList,deliveryDate,invoiceTime);
        return ResponseEntity.ok().build();
    }

    /**
     * 选择 公司主数据/供应商数据
     * @param choseSupplierListQuery
     * @return
     */
    @RequestMapping("/choseSupplierList")
    public PageView choseSupplierList( ChoseSupplierListQuery choseSupplierListQuery ) {
        return contractLogic.choseSupplierList(choseSupplierListQuery);
    }


    @RequestMapping("/choseContractList")
    public PageView choseContractList( ContractMangeQuery mangeQuery ) {
        return contractLogic.choseContractList(mangeQuery);
    }


    @RequestMapping("/getContractCategory")
    public List<ContractCategoryDTO> getContractCategory(Integer mroFlag) {
        return contractLogic.getContractCategory(mroFlag);
    }


    @RequestMapping("/form/save")
    @Transactional
    public ResponseEntity formSave(Contract bean, String dlist ,String mros ,String rowsTableTblist, String isTerminated) {
        //检查合同编码是否存在
        Long count = contractLogic.selectOnlyCode(bean.getContractCode(), bean.getId());
        if (count > 0) {
            throw new DaoException("合同编码已存在，请修改!");
        }
        if (StringUtils.isEmpty(bean.getId())) {
            bean.setCreateTime(LocalDateTime.now());
            bean.setCreateUser(LoginUtil.getUserId());
            if (StrUtil.isNotEmpty(bean.getDataSourcesNo())&&bean.getDataSourcesNo().contains("RFQ")){
                bean.setDataSources(3);
            }
            if ("07".equals(bean.getContractType()) || "08".equals(bean.getContractType())) {
                bean.setContractCode(null);
            }
            contractLogic.insertOrUpdate(bean);
        } else {
            bean.setUpdateTime(LocalDateTime.now());
            bean.setUpdateUser(LoginUtil.getUserId());
            contractLogic.insertOrUpdate(bean);
        }
        contractLogic.saveContractDeatils(bean,dlist,rowsTableTblist,mros);

        // 发起终止
        if ("1".equals(isTerminated)) {
            try {
                contractLogic.submitContractToGx(bean.getId().toString(), bean.getOaProcessId(), "1");
            } catch (DaoException e) {
                log.error("资产合同，共享发起终止异常", e);
                return ResponseEntity.ok("请注意！终止合同保存成功，但提交共享失败");
            }
        }
        return ResponseEntity.ok("");
    }

    @PostMapping("/form/saveMro")
    public ResponseEntity<String> formSaveMro(@RequestBody ContractMroSaveDTO saveDTO) {
        String resultStr = contractLogic.formSave(saveDTO);
        return ResponseEntity.ok(resultStr);
    }

    @RequestMapping("/selectPayListPage")
    public PageView selectPayListPage(ChoseSupplierListQuery choseSupplierListQuery) {
        return contractLogic.selectPayListPage(choseSupplierListQuery);
    }


    @RequestMapping("/selectContractDetailListPage")
    public PageView selectContractDetailListPage(ChoseSupplierListQuery choseSupplierListQuery) {
        return contractLogic.selectContractDetailListPage(choseSupplierListQuery);
    }


    @RequestMapping("/selectContractMroListPage")
    public PageView selectContractMroListPage(ChoseSupplierListQuery choseSupplierListQuery) {
        return contractLogic.selectContractMroListPage(choseSupplierListQuery);
    }


    @RequestMapping("/remove")
    @Transactional
    public ResponseEntity remove(String id) {
        contractLogic.removeContract(id);
        return ResponseEntity.ok(true);
    }

    @RequestMapping("/cancel")
    @Transactional
    public ResponseEntity cancel(String id) {
        contractLogic.removeContract(id);
        return ResponseEntity.ok(true);
    }


    @RequestMapping("/saveSignFile")
    public ResponseEntity saveSignFile(@RequestPart("files") MultipartFile[] files, @RequestParam("fileIds") String[] fileIds, String conId) {
        if(files!=null&&files.length==0){
            throw new DaoException("未上传盖章文件");
        }
        contractLogic.saveSignFile(files,fileIds,conId);
        return ResponseEntity.ok(true);
    }

    /**
     * 提交盖章附件数据到共享平台
     * @param
     * @return
     */
    @RequestMapping("/submitStampFileToGx")
    @Transactional
    public ResponseEntity submitStampFileToGx(String conId,String gxApplyId) {
        List<String> strings = contractLogic.submitStampFileToGx(conId, gxApplyId,"1");
        return ResponseEntity.ok(strings);
    }

    /**
     * 提交合同数据到共享平台
     * @param
     * @return
     */
    @RequestMapping("/submitContractToGx")
    @Transactional
    public ResponseEntity submitContractToGx(String conId,String gxApplyId, String isTerminated) {
        return ResponseEntity.ok(contractLogic.submitContractToGx(conId,gxApplyId, isTerminated));
    }



    @RequestMapping("/sendSign")
    public ResponseEntity sendSign(String conId) {
        contractLogic.sendSign(conId);
        return ResponseEntity.ok(true);
    }


    /**
     * 明细导出
     * @param queryStr 查询条件
     */
    @PostMapping("/detail/export")
    public void detailMroExport(HttpServletResponse response, String queryStr) throws IOException {
        List<ExportDataDTO> exportDataDTOS = new ArrayList<>();

        exportDataDTOS.add(ExportDataDTO.builder().title("资产申请单号").field("purchaseCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("资产申请行项目").field("itemCode").build());
        List<DictDTO> contractItems = dictClient.getDicByType(DictCode.CONTRACT_MRO_SUBJECT.getCode());
        exportDataDTOS.add(ExportDataDTO.builder().title("资产类别").field("subjectCode").selectList(contractItems.stream().map(DictDTO::getName).distinct().toList()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物品名称").field("materialName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("型号规格/参数").field("materialSpec").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("品牌").field("materialBrand").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("数量").field("num").build());
        List<DictDTO> units = dictClient.getDicByType(DictCode.UNIT.getCode());
        exportDataDTOS.add(ExportDataDTO.builder().title("单位").field("basisUnit").selectList(units.stream().map(DictDTO::getName).distinct().toList()).build());
        List<TaxDTO> taxDTOS = taxClient.getAll();
        exportDataDTOS.add(ExportDataDTO.builder().title("税码").field("taxRateCode").selectList(taxDTOS.stream().map(TaxDTO::getTaxName).distinct().toList()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("含税单价").field("price").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("未税单价").field("noTaxPrice").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("使用部门名称").field("useDeptName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("使用部门编码").field("useDeptCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("使用人名称").field("userName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("使用人工号").field("userCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("成本中心编码").field("costCenterCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("成本中心名称").field("costCenterName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("存放地点").field("stockPoint").build());
//        exportDataDTOS.add(ExportDataDTO.builder().title("资产用途").field("mainUses").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("客户编码").field("customerCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("客户").field("customerName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("交货日期").field("deliveryDate").build());

//        ShoppingPayDetailQuery query = JSON.parseObject(queryStr, ShoppingPayDetailQuery.class);
        final List<ContractDetailDTO> exportData = contractLogic.selectContractDetailExportData(queryStr);

        EasyExcelUtils.trendsModelWrite(response,"合同明细导入模板-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, JSON.toJSONString(exportDataDTOS));
    }

    @RequestMapping("/detail/import")
    public ResponseEntity<List<Map<String,String>>> detailMroImport(@RequestPart("file") MultipartFile file){
        List<Map<String,String>> maps = contractLogic.detailMroImport(file);
        return ResponseEntity.ok(maps);
    }

    /**
     * 合同终止校验
     * @param contractId 合同ID
     * @return 校验失败直接抛DaoException
     */
    @RequestMapping("/detail/contractTerminateCheck")
    public ResponseEntity<Boolean> contractTerminateCheck(String contractId) {
        contractLogic.contractTerminateCheck(contractId);
        return ResponseEntity.ok().build();
    }
}
