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.ContractPayStageDTO;
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.contract.model.query.ContractPayStageQuery;
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.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.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


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

    @Autowired
    ContractLogic contractLogic;

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

    @AuditLogInter(value = "查询", module = "合同付款跟踪")
    @RequestMapping("/index/page")
    public PageView listPage(ContractMangeQuery mangeQuery) {
        mangeQuery.setIsMro(2);
        if(LoginUtil.isSupplier()){
            String supplierCode = LoginUtil.getSupplierCode();
            mangeQuery.setSupplierCode(supplierCode);
            mangeQuery.setState(3);
        }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);
    }

    @AuditLogInter(value = "查询", module = "MRO合同报表")
    @RequestMapping("/report/page")
    public PageView reportPage(ContractMangeQuery mangeQuery) {
        if(LoginUtil.isSupplier()){
            String supplierCode = LoginUtil.getSupplierCode();
            mangeQuery.setSupplierCode(supplierCode);
            mangeQuery.setState(3);
        }
        return contractLogic.reportPage(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) {
        //检查合同编码是否存在
        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);
            }
            contractLogic.insertOrUpdate(bean);
        } else {
            bean.setUpdateTime(LocalDateTime.now());
            bean.setUpdateUser(LoginUtil.getUserId());
            contractLogic.insertOrUpdate(bean);
        }
        contractLogic.saveContractDeatils(bean,dlist,rowsTableTblist,mros);
        return ResponseEntity.ok(true);
    }



    @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("/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);
    }


    @RequestMapping("/getBillByKm")
    @Transactional
    public ResponseEntity getBillByKm(String conId,String oaApplyId) {
        return ResponseEntity.ok(contractLogic.getBillByKm(conId,oaApplyId));
    }


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


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

        List<DictDTO> contractItems = dictClient.getDicByType(ObjectUtil.isNotNull(isSap)&&isSap==1? DictCode.CONTRACT_ITEM_SUBJECT_SAP.getCode():DictCode.CONTRACT_ITEM_SUBJECT.getCode());
        exportDataDTOS.add(ExportDataDTO.builder().title("科目").field("subjectCode").color(IndexedColors.YELLOW.getIndex()).selectList(contractItems.stream().map(DictDTO::getName).distinct().toList()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料名称").field("materialName").color(IndexedColors.YELLOW.getIndex()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("详细规格参数").field("materialSpec").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("品牌").field("materialBrand").build());
        List<DictDTO> units = dictClient.getDicByType(DictCode.UNIT.getCode());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料单位").field("basisUnit").color(IndexedColors.YELLOW.getIndex()).selectList(units.stream().map(DictDTO::getName).distinct().toList()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料组编码").field("materialGroupCode").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("materialCategory").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("单价(含税)").field("price").color(IndexedColors.YELLOW.getIndex()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("需求数量").field("num").color(IndexedColors.YELLOW.getIndex()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("请购单号").field("purchaseCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("请购单行号").field("itemCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("工厂编码").field("factoryCode").color(IndexedColors.YELLOW.getIndex()).build());
        List<DictDTO> contractPayBootItems = dictClient.getDicByType(DictCode.CONTRACT_PAY_BOOT_ITEM.getCode());
        exportDataDTOS.add(ExportDataDTO.builder().title("驱动因素").field("driverAsset").selectList(contractPayBootItems.stream().map(DictDTO::getName).distinct().toList()).build());
        List<DictDTO> currencys = dictClient.getDicByType(DictCode.CURRENCY.getCode());
        exportDataDTOS.add(ExportDataDTO.builder().title("币别").field("currencyCode").selectList(currencys.stream().map(DictDTO::getName).distinct().toList()).color(IndexedColors.YELLOW.getIndex()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("服务客户编码").field("customerCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("请购部门").field("teamName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("请购人").field("requireName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("成本中心编码").field("costCenterCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("成本中心名称").field("costCenterName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("备注").field("bz").build());
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"合同明细导入模板-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", new ArrayList<>(), JSON.toJSONString(exportDataDTOS));
    }

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

    /**
     * 合同收货单页面查询合同明细
     * @param choseSupplierListQuery
     * @return
     */
    @RequestMapping("/selectReceiptContractDetailListPage")
    public PageView selectReceiptContractDetailListPage(ChoseSupplierListQuery choseSupplierListQuery) {
        return contractLogic.selectReceiptContractDetailListPage(choseSupplierListQuery);
    }
}
