package com.yunzhupaas.cm.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.cm.service.*;
import com.yunzhupaas.cm.entity.*;
import com.yunzhupaas.util.*;
import com.yunzhupaas.cm.model.contract.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yunzhupaas.flowable.entity.TaskEntity;
import jakarta.validation.Valid;
import java.util.*;
import com.yunzhupaas.model.ExcelModel;
import com.yunzhupaas.excel.ExcelExportStyler;
import com.yunzhupaas.excel.ExcelHelper;
import com.yunzhupaas.annotation.YunzhupaasField;
import com.yunzhupaas.base.vo.PageListVO;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.base.vo.DownloadVO;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.base.entity.ProvinceEntity;
import java.io.IOException;
import java.util.stream.Collectors;
import com.yunzhupaas.flowable.entity.TaskEntity;
import com.yunzhupaas.exception.WorkFlowException;
import com.yunzhupaas.model.visualJson.UploaderTemplateModel;
import com.yunzhupaas.base.util.FormExecelUtils;
import org.springframework.web.multipart.MultipartFile;
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.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import com.yunzhupaas.onlinedev.model.ExcelImFieldModel;
import com.yunzhupaas.base.model.OnlineImport.ImportDataModel;
import com.yunzhupaas.base.model.OnlineImport.ImportFormCheckUniqueModel;
import com.yunzhupaas.base.model.OnlineImport.ExcelImportModel;
import com.yunzhupaas.base.model.OnlineImport.VisualImportModel;
import cn.xuyanwu.spring.file.storage.FileInfo;
import lombok.Cleanup;
import com.yunzhupaas.model.visualJson.config.HeaderModel;
import com.yunzhupaas.base.model.ColumnDataModel;
import com.yunzhupaas.base.util.VisualUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 合同管理
 * @版本： V5.2.7
 * @版权： Copyright @ 2025  深圳市乐程软件有限公司版权所有
 * @作者： 深圳市乐程软件有限公司
 * @日期： 2026-05-20
 */
@Slf4j
@RestController
@Tag(name = "合同管理" , description = "4")
@RequestMapping("/api/cm/Contract")
public class ContractController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ContractService contractService;

    @Autowired
    private ProductSubjectService productSubjectService;
    @Autowired
    private MaterialSubjectService materialSubjectService;
    @Autowired
    private WorktypeSubjectService worktypeSubjectService;
    @Autowired
    private AssetSubjectService assetSubjectService;
    @Autowired
    private TaskSubjectService taskSubjectService;
    @Autowired
    private PaymentPlanService paymentPlanService;


    @Autowired
    private ConfigValueUtil configValueUtil;

    /**
    * 列表
    *
    * @param contractPagination
    * @return
    */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ContractPagination contractPagination)throws Exception{
        List<ContractEntity> list= contractService.getList(contractPagination);
        List<Map<String, Object>> realList=new ArrayList<>();
        for (ContractEntity entity : list) {
        Map<String, Object> contractMap=JsonUtil.entityToMap(entity);
        contractMap.put("id", contractMap.get("contract_id"));
        //副表数据
        //子表数据
        List<ProductSubjectEntity> productSubjectList = entity.getProductSubject();
        contractMap.put("tableProductList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(productSubjectList)));
        contractMap.put("productSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(productSubjectList)));
        List<MaterialSubjectEntity> materialSubjectList = entity.getMaterialSubject();
        contractMap.put("tableMaterialList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(materialSubjectList)));
        contractMap.put("materialSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(materialSubjectList)));
        List<WorktypeSubjectEntity> worktypeSubjectList = entity.getWorktypeSubject();
        contractMap.put("tableWorktypeList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(worktypeSubjectList)));
        contractMap.put("worktypeSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(worktypeSubjectList)));
        List<AssetSubjectEntity> assetSubjectList = entity.getAssetSubject();
        contractMap.put("tableAssetList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(assetSubjectList)));
        contractMap.put("assetSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(assetSubjectList)));
        List<TaskSubjectEntity> taskSubjectList = entity.getTaskSubject();
        contractMap.put("tableTaskList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(taskSubjectList)));
        contractMap.put("taskSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(taskSubjectList)));
        List<PaymentPlanEntity> paymentPlanList = entity.getPaymentPlan();
        contractMap.put("tableField3494b2",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(paymentPlanList)));
        contractMap.put("paymentPlanList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(paymentPlanList)));
            realList.add(contractMap);
        }
        //数据转换
        boolean isPc = "pc".equals(ServletUtil.getHeader("yunzhupaas-origin" ));
        realList = generaterSwapUtil.swapDataList(realList, ContractConstant.getFormData(), ContractConstant.getColumnData(), contractPagination.getModuleId(),isPc?false:false);

        //流程状态添加
        generaterSwapUtil.getFlowStatus(realList);
        //返回对象
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO page = JsonUtil.getJsonToBean(contractPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }
    /**
    * 创建
    *
    * @param contractForm
    * @return
    */
    @PostMapping("/{id}")
    @Operation(summary = "创建")
    public ActionResult create(@PathVariable("id") String id, @RequestBody @Valid ContractForm contractForm) {
        String b = contractService.checkForm(contractForm,0);
        if (StringUtil.isNotEmpty(b)){
            return ActionResult.fail(b );
        }
        try{
            contractService.saveOrUpdate(contractForm, id ,true);
        }catch(Exception e){
            return ActionResult.fail(MsgCode.FA028.get());
        }
        return ActionResult.success(MsgCode.SU001.get());
    }
    /**
    * 导出Excel
    *
    * @return
    */
    @Operation(summary = "导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody ContractPagination contractPagination) throws IOException {
        if (StringUtil.isEmpty(contractPagination.getSelectKey())){
            return ActionResult.fail(MsgCode.IMP011.get());
        }
        List<ContractEntity> list= contractService.getList(contractPagination);
        List<Map<String, Object>> realList=new ArrayList<>();
        for (ContractEntity entity : list) {
        Map<String, Object> contractMap=JsonUtil.entityToMap(entity);
        contractMap.put("id", contractMap.get("contract_id"));
        //副表数据
        //子表数据
        List<ProductSubjectEntity> productSubjectList = entity.getProductSubject();
        contractMap.put("tableProductList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(productSubjectList)));
        contractMap.put("productSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(productSubjectList)));
        List<MaterialSubjectEntity> materialSubjectList = entity.getMaterialSubject();
        contractMap.put("tableMaterialList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(materialSubjectList)));
        contractMap.put("materialSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(materialSubjectList)));
        List<WorktypeSubjectEntity> worktypeSubjectList = entity.getWorktypeSubject();
        contractMap.put("tableWorktypeList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(worktypeSubjectList)));
        contractMap.put("worktypeSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(worktypeSubjectList)));
        List<AssetSubjectEntity> assetSubjectList = entity.getAssetSubject();
        contractMap.put("tableAssetList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(assetSubjectList)));
        contractMap.put("assetSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(assetSubjectList)));
        List<TaskSubjectEntity> taskSubjectList = entity.getTaskSubject();
        contractMap.put("tableTaskList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(taskSubjectList)));
        contractMap.put("taskSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(taskSubjectList)));
        List<PaymentPlanEntity> paymentPlanList = entity.getPaymentPlan();
        contractMap.put("tableField3494b2",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(paymentPlanList)));
        contractMap.put("paymentPlanList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(paymentPlanList)));
            realList.add(contractMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, ContractConstant.getFormData(), ContractConstant.getColumnData(), contractPagination.getModuleId(),false);
        String[]keys=!StringUtil.isEmpty(contractPagination.getSelectKey())?contractPagination.getSelectKey():new String[0];
        UserInfo userInfo=userProvider.get();
        String menuFullName = generaterSwapUtil.getMenuName(contractPagination.getMenuId());

            DownloadVO vo=this.creatModelExcel(configValueUtil.getTemporaryFilePath(),realList,keys,userInfo,menuFullName);
        return ActionResult.success(vo);
    }

    /**
    * 导出表格方法
    */
    public DownloadVO creatModelExcel(String path,List<Map<String, Object>>list,String[]keys,UserInfo userInfo,String menuFullName){
        DownloadVO vo=DownloadVO.builder().build();
        List<ExcelExportEntity> entitys=new ArrayList<>();
        if(keys.length>0){
            ExcelExportEntity tableProductListExcelEntity = new ExcelExportEntity("产品清单(tableProductList)","tableProductList");
            List<ExcelExportEntity> tableProductListList = new ArrayList<>();
            ExcelExportEntity tableMaterialListExcelEntity = new ExcelExportEntity("材料清单(tableMaterialList)","tableMaterialList");
            List<ExcelExportEntity> tableMaterialListList = new ArrayList<>();
            ExcelExportEntity tableWorktypeListExcelEntity = new ExcelExportEntity("人力清单(tableWorktypeList)","tableWorktypeList");
            List<ExcelExportEntity> tableWorktypeListList = new ArrayList<>();
            ExcelExportEntity tableAssetListExcelEntity = new ExcelExportEntity("资产租赁(tableAssetList)","tableAssetList");
            List<ExcelExportEntity> tableAssetListList = new ArrayList<>();
            ExcelExportEntity tableTaskListExcelEntity = new ExcelExportEntity("工作量清单(tableTaskList)","tableTaskList");
            List<ExcelExportEntity> tableTaskListList = new ArrayList<>();
            ExcelExportEntity tableField3494b2ExcelEntity = new ExcelExportEntity("付款计划(tableField3494b2)","tableField3494b2");
            List<ExcelExportEntity> tableField3494b2List = new ArrayList<>();
            for(String key:keys){
                switch(key){
                    case "contract_type" :
                    entitys.add(new ExcelExportEntity("合同类型" ,"contract_type"));
                    break;
                    case "contract_temp_id" :
                    entitys.add(new ExcelExportEntity("引用模版" ,"contract_temp_id"));
                    break;
                    case "contract_name" :
                    entitys.add(new ExcelExportEntity("合同名称" ,"contract_name"));
                    break;
                    case "contract_code" :
                    entitys.add(new ExcelExportEntity("合同编码" ,"contract_code"));
                    break;
                    case "org_id" :
                    entitys.add(new ExcelExportEntity("归属组织" ,"org_id"));
                    break;
                    case "project_id" :
                    entitys.add(new ExcelExportEntity("归属项目" ,"project_id"));
                    break;
                    case "contract_category" :
                    entitys.add(new ExcelExportEntity("合同分类" ,"contract_category"));
                    break;
                    case "contract_date" :
                    entitys.add(new ExcelExportEntity("签约日期" ,"contract_date"));
                    break;
                    case "effective_date" :
                    entitys.add(new ExcelExportEntity("开始日期" ,"effective_date"));
                    break;
                    case "expiry_date" :
                    entitys.add(new ExcelExportEntity("结束日期" ,"expiry_date"));
                    break;
                    case "is_sub_contract" :
                    entitys.add(new ExcelExportEntity("是否子合同" ,"is_sub_contract"));
                    break;
                    case "ref_contract_id" :
                    entitys.add(new ExcelExportEntity("关联合同" ,"ref_contract_id"));
                    break;
                    case "major_person_id" :
                    entitys.add(new ExcelExportEntity("经办人" ,"major_person_id"));
                    break;
                    case "print_temp_id" :
                    entitys.add(new ExcelExportEntity("打印合同模版" ,"print_temp_id"));
                    break;
                    case "remark" :
                    entitys.add(new ExcelExportEntity("备注" ,"remark"));
                    break;
                    case "our_company_type" :
                    entitys.add(new ExcelExportEntity("我方类型" ,"our_company_type"));
                    break;
                    case "our_company_id" :
                    entitys.add(new ExcelExportEntity("我方单位" ,"our_company_id"));
                    break;
                    case "our_company_name" :
                    entitys.add(new ExcelExportEntity("我方名称" ,"our_company_name"));
                    break;
                    case "second_party_type" :
                    entitys.add(new ExcelExportEntity("合作方类型" ,"second_party_type"));
                    break;
                    case "second_party_id" :
                    entitys.add(new ExcelExportEntity("合作单位" ,"second_party_id"));
                    break;
                    case "second_party_name" :
                    entitys.add(new ExcelExportEntity("合作方名称" ,"second_party_name"));
                    break;
                    case "third_party_type" :
                    entitys.add(new ExcelExportEntity("第三方类型" ,"third_party_type"));
                    break;
                    case "third_party_id" :
                    entitys.add(new ExcelExportEntity("第三方单位" ,"third_party_id"));
                    break;
                    case "third_party_name" :
                    entitys.add(new ExcelExportEntity("第三方名称" ,"third_party_name"));
                    break;
                    case "contract_money" :
                    entitys.add(new ExcelExportEntity("原合同金额" ,"contract_money"));
                    break;
                    case "final_contract_amount" :
                    entitys.add(new ExcelExportEntity("最终签约金额" ,"final_contract_amount"));
                    break;
                    case "final_amount_upper" :
                    entitys.add(new ExcelExportEntity("签约金额大写" ,"final_amount_upper"));
                    break;
                    case "tax_amount" :
                    entitys.add(new ExcelExportEntity("税额" ,"tax_amount"));
                    break;
                    case "excluding_tax_amount" :
                    entitys.add(new ExcelExportEntity("不含税金额" ,"excluding_tax_amount"));
                    break;
                    case "contract_files" :
                    entitys.add(new ExcelExportEntity("合同附件" ,"contract_files"));
                    break;
                    case "tableProductList-product_id":
                    tableProductListList.add(new ExcelExportEntity("产品名称" ,"product_id"));
                    break;
                    case "tableProductList-brand":
                    tableProductListList.add(new ExcelExportEntity("品牌" ,"brand"));
                    break;
                    case "tableProductList-product_model":
                    tableProductListList.add(new ExcelExportEntity("规格型号" ,"product_model"));
                    break;
                    case "tableProductList-quantity":
                    tableProductListList.add(new ExcelExportEntity("数量" ,"quantity"));
                    break;
                    case "tableProductList-unit_price":
                    tableProductListList.add(new ExcelExportEntity("单价" ,"unit_price"));
                    break;
                    case "tableProductList-quantity_unit":
                    tableProductListList.add(new ExcelExportEntity("单位" ,"quantity_unit"));
                    break;
                    case "tableProductList-currency":
                    tableProductListList.add(new ExcelExportEntity("币种" ,"currency"));
                    break;
                    case "tableProductList-total_amount":
                    tableProductListList.add(new ExcelExportEntity("总金额" ,"total_amount"));
                    break;
                    case "tableProductList-discount_type":
                    tableProductListList.add(new ExcelExportEntity("折扣类型" ,"discount_type"));
                    break;
                    case "tableProductList-discount_value":
                    tableProductListList.add(new ExcelExportEntity("折扣值" ,"discount_value"));
                    break;
                    case "tableProductList-final_amount":
                    tableProductListList.add(new ExcelExportEntity("最终金额" ,"final_amount"));
                    break;
                    case "tableProductList-tax_rate":
                    tableProductListList.add(new ExcelExportEntity("税率" ,"tax_rate"));
                    break;
                    case "tableProductList-tax_amount":
                    tableProductListList.add(new ExcelExportEntity("税额" ,"tax_amount"));
                    break;
                    case "tableProductList-warranty_period":
                    tableProductListList.add(new ExcelExportEntity("保修期" ,"warranty_period"));
                    break;
                    case "tableProductList-warranty_terms":
                    tableProductListList.add(new ExcelExportEntity("保修条款" ,"warranty_terms"));
                    break;
                    case "tableMaterialList-material_id":
                    tableMaterialListList.add(new ExcelExportEntity("材料名称" ,"material_id"));
                    break;
                    case "tableMaterialList-brand":
                    tableMaterialListList.add(new ExcelExportEntity("品牌" ,"brand"));
                    break;
                    case "tableMaterialList-quantity":
                    tableMaterialListList.add(new ExcelExportEntity("数量" ,"quantity"));
                    break;
                    case "tableMaterialList-unit_price":
                    tableMaterialListList.add(new ExcelExportEntity("单价" ,"unit_price"));
                    break;
                    case "tableMaterialList-quantity_unit":
                    tableMaterialListList.add(new ExcelExportEntity("单位" ,"quantity_unit"));
                    break;
                    case "tableMaterialList-currency":
                    tableMaterialListList.add(new ExcelExportEntity("币种" ,"currency"));
                    break;
                    case "tableMaterialList-total_amount":
                    tableMaterialListList.add(new ExcelExportEntity("总金额" ,"total_amount"));
                    break;
                    case "tableMaterialList-tax_rate":
                    tableMaterialListList.add(new ExcelExportEntity("税率" ,"tax_rate"));
                    break;
                    case "tableMaterialList-tax_amount":
                    tableMaterialListList.add(new ExcelExportEntity("税额" ,"tax_amount"));
                    break;
                    case "tableMaterialList-warranty_period":
                    tableMaterialListList.add(new ExcelExportEntity("保修期" ,"warranty_period"));
                    break;
                    case "tableMaterialList-warranty_terms":
                    tableMaterialListList.add(new ExcelExportEntity("保修条款" ,"warranty_terms"));
                    break;
                    case "tableWorktypeList-work_type_id":
                    tableWorktypeListList.add(new ExcelExportEntity("工种" ,"work_type_id"));
                    break;
                    case "tableWorktypeList-quantity":
                    tableWorktypeListList.add(new ExcelExportEntity("数量" ,"quantity"));
                    break;
                    case "tableWorktypeList-unit_price":
                    tableWorktypeListList.add(new ExcelExportEntity("销售单价" ,"unit_price"));
                    break;
                    case "tableWorktypeList-quantity_unit":
                    tableWorktypeListList.add(new ExcelExportEntity("数量单位" ,"quantity_unit"));
                    break;
                    case "tableWorktypeList-currency":
                    tableWorktypeListList.add(new ExcelExportEntity("币种" ,"currency"));
                    break;
                    case "tableWorktypeList-total_amount":
                    tableWorktypeListList.add(new ExcelExportEntity("总金额" ,"total_amount"));
                    break;
                    case "tableWorktypeList-discount_type":
                    tableWorktypeListList.add(new ExcelExportEntity("折扣类型" ,"discount_type"));
                    break;
                    case "tableWorktypeList-discount_value":
                    tableWorktypeListList.add(new ExcelExportEntity("折扣值" ,"discount_value"));
                    break;
                    case "tableWorktypeList-final_amount":
                    tableWorktypeListList.add(new ExcelExportEntity("最终金额" ,"final_amount"));
                    break;
                    case "tableWorktypeList-tax_rate":
                    tableWorktypeListList.add(new ExcelExportEntity("税率" ,"tax_rate"));
                    break;
                    case "tableWorktypeList-tax_amount":
                    tableWorktypeListList.add(new ExcelExportEntity("税额" ,"tax_amount"));
                    break;
                    case "tableWorktypeList-work_description":
                    tableWorktypeListList.add(new ExcelExportEntity("工种描述" ,"work_description"));
                    break;
                    case "tableAssetList-asset_id":
                    tableAssetListList.add(new ExcelExportEntity("资产名称" ,"asset_id"));
                    break;
                    case "tableAssetList-begin_date":
                    tableAssetListList.add(new ExcelExportEntity("开始日期" ,"begin_date"));
                    break;
                    case "tableAssetList-end_date":
                    tableAssetListList.add(new ExcelExportEntity("结束日期" ,"end_date"));
                    break;
                    case "tableAssetList-quantity":
                    tableAssetListList.add(new ExcelExportEntity("租赁天数" ,"quantity"));
                    break;
                    case "tableAssetList-unit_price":
                    tableAssetListList.add(new ExcelExportEntity("租赁单价" ,"unit_price"));
                    break;
                    case "tableAssetList-quantity_unit":
                    tableAssetListList.add(new ExcelExportEntity("单位" ,"quantity_unit"));
                    break;
                    case "tableAssetList-currency":
                    tableAssetListList.add(new ExcelExportEntity("币种" ,"currency"));
                    break;
                    case "tableAssetList-total_amount":
                    tableAssetListList.add(new ExcelExportEntity("总金额" ,"total_amount"));
                    break;
                    case "tableAssetList-discount_type":
                    tableAssetListList.add(new ExcelExportEntity("折扣类型" ,"discount_type"));
                    break;
                    case "tableAssetList-discount_value":
                    tableAssetListList.add(new ExcelExportEntity("折扣值" ,"discount_value"));
                    break;
                    case "tableAssetList-final_amount":
                    tableAssetListList.add(new ExcelExportEntity("最终金额" ,"final_amount"));
                    break;
                    case "tableAssetList-tax_rate":
                    tableAssetListList.add(new ExcelExportEntity("税率" ,"tax_rate"));
                    break;
                    case "tableAssetList-tax_amount":
                    tableAssetListList.add(new ExcelExportEntity("税额" ,"tax_amount"));
                    break;
                    case "tableTaskList-task_name":
                    tableTaskListList.add(new ExcelExportEntity("任务名称" ,"task_name"));
                    break;
                    case "tableTaskList-task_description":
                    tableTaskListList.add(new ExcelExportEntity("任务描述" ,"task_description"));
                    break;
                    case "tableTaskList-quantity":
                    tableTaskListList.add(new ExcelExportEntity("数量" ,"quantity"));
                    break;
                    case "tableTaskList-unit_price":
                    tableTaskListList.add(new ExcelExportEntity("单价" ,"unit_price"));
                    break;
                    case "tableTaskList-quantity_unit":
                    tableTaskListList.add(new ExcelExportEntity("单位" ,"quantity_unit"));
                    break;
                    case "tableTaskList-currency":
                    tableTaskListList.add(new ExcelExportEntity("币种" ,"currency"));
                    break;
                    case "tableTaskList-total_amount":
                    tableTaskListList.add(new ExcelExportEntity("总金额" ,"total_amount"));
                    break;
                    case "tableTaskList-discount_type":
                    tableTaskListList.add(new ExcelExportEntity("折扣类型" ,"discount_type"));
                    break;
                    case "tableTaskList-discount_value":
                    tableTaskListList.add(new ExcelExportEntity("折扣值" ,"discount_value"));
                    break;
                    case "tableTaskList-final_amount":
                    tableTaskListList.add(new ExcelExportEntity("最终金额" ,"final_amount"));
                    break;
                    case "tableTaskList-tax_rate":
                    tableTaskListList.add(new ExcelExportEntity("税率" ,"tax_rate"));
                    break;
                    case "tableTaskList-tax_amount":
                    tableTaskListList.add(new ExcelExportEntity("税额" ,"tax_amount"));
                    break;
                    case "tableTaskList-remark":
                    tableTaskListList.add(new ExcelExportEntity("备注" ,"remark"));
                    break;
                    case "tableField3494b2-plan_seq_num":
                    tableField3494b2List.add(new ExcelExportEntity("序号" ,"plan_seq_num"));
                    break;
                    case "tableField3494b2-payment_name":
                    tableField3494b2List.add(new ExcelExportEntity("款项名称" ,"payment_name"));
                    break;
                    case "tableField3494b2-billing_item_id":
                    tableField3494b2List.add(new ExcelExportEntity("款项类型" ,"billing_item_id"));
                    break;
                    case "tableField3494b2-payment_condition":
                    tableField3494b2List.add(new ExcelExportEntity("付款条件" ,"payment_condition"));
                    break;
                    case "tableField3494b2-plan_date":
                    tableField3494b2List.add(new ExcelExportEntity("预计付款日期" ,"plan_date"));
                    break;
                    case "tableField3494b2-payment_ratio":
                    tableField3494b2List.add(new ExcelExportEntity("付款比例" ,"payment_ratio"));
                    break;
                    case "tableField3494b2-payment_amount":
                    tableField3494b2List.add(new ExcelExportEntity("付款金额" ,"payment_amount"));
                    break;
                    case "tableField3494b2-remark":
                    tableField3494b2List.add(new ExcelExportEntity("备注" ,"remark"));
                    break;
                    default:
                    break;
                }
            }
            if(tableProductListList.size() > 0){
                tableProductListExcelEntity.setList(tableProductListList);
                entitys.add(tableProductListExcelEntity);
            }
            if(tableMaterialListList.size() > 0){
                tableMaterialListExcelEntity.setList(tableMaterialListList);
                entitys.add(tableMaterialListExcelEntity);
            }
            if(tableWorktypeListList.size() > 0){
                tableWorktypeListExcelEntity.setList(tableWorktypeListList);
                entitys.add(tableWorktypeListExcelEntity);
            }
            if(tableAssetListList.size() > 0){
                tableAssetListExcelEntity.setList(tableAssetListList);
                entitys.add(tableAssetListExcelEntity);
            }
            if(tableTaskListList.size() > 0){
                tableTaskListExcelEntity.setList(tableTaskListList);
                entitys.add(tableTaskListExcelEntity);
            }
            if(tableField3494b2List.size() > 0){
                tableField3494b2ExcelEntity.setList(tableField3494b2List);
                entitys.add(tableField3494b2ExcelEntity);
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try{
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size()>0){
                if (list.size()==0){
                    list.add(new HashMap<>());
                }
                //去除空数据
                List<Map<String, Object>> dataList = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    int i = 0;
                    for (String key : keys) {
                        //子表
                        if (key.toLowerCase().startsWith("tablefield")) {
                            String tableField = key.substring(0, key.indexOf("-" ));
                            String field = key.substring(key.indexOf("-" ) + 1);
                            Object o = map.get(tableField);
                            if (o != null) {
                                List<Map<String, Object>> childList = (List<Map<String, Object>>) o;
                                for (Map<String, Object> childMap : childList) {
                                    if (childMap.get(field) != null) {
                                        i++;
                                    }
                                }
                            }
                        } else {
                            Object o = map.get(key);
                            if (o != null) {
                                i++;
                            }
                        }
                    }
                    if (i > 0) {
                        dataList.add(map);
                    }
                }
                List<ExcelExportEntity> mergerEntitys = new ArrayList<>(entitys);
                List<Map<String, Object>> mergerList=new ArrayList<>(dataList);
                //复杂表头-表头和数据处理
                ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(ContractConstant.getColumnData(), ColumnDataModel.class);
                List<HeaderModel> complexHeaderList = columnDataModel.getComplexHeaderList();
                if (!Objects.equals(columnDataModel.getType(), 3) && !Objects.equals(columnDataModel.getType(), 5)) {
                    entitys = VisualUtils.complexHeaderHandel(entitys, complexHeaderList, Objects.equals(columnDataModel.getType(), 4));
                    dataList =  VisualUtils.complexHeaderDataHandel(dataList, complexHeaderList, Objects.equals(columnDataModel.getType(), 4));
                }

                exportParams.setStyle(ExcelExportStyler.class);
                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, dataList);
                VisualUtils.mergerVertical(workbook, mergerEntitys, mergerList);
                ExcelModel excelModel = generaterSwapUtil.getExcelParams(ContractConstant.getFormData(),Arrays.asList(keys));
                ExcelHelper helper = new ExcelHelper();
                helper.init(workbook, exportParams, entitys, excelModel);
                helper.doPreHandle();
                helper.doPostHandle();
            }
            String fileName = menuFullName  +"_"+ DateUtil.dateNow("yyyyMMddHHmmss") + ".xls";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id,@RequestParam(name = "forceDel",defaultValue = "false") boolean forceDel) throws Exception{
        ContractEntity entity= contractService.getInfo(id);
        if(entity!=null){
            if(!forceDel){
                String errMsg = generaterSwapUtil.deleteFlowTask(entity.getFlowTaskId());
                if (StringUtil.isNotEmpty(errMsg)) {
                    throw new DataException(errMsg);
                }
            }
            //主表数据删除
            contractService.delete(entity);
            QueryWrapper<ProductSubjectEntity> queryWrapperProductSubject=new QueryWrapper<>();
            queryWrapperProductSubject.lambda().eq(ProductSubjectEntity::getContractId,entity.getContractId());
            //子表数据删除
            productSubjectService.remove(queryWrapperProductSubject);
            QueryWrapper<MaterialSubjectEntity> queryWrapperMaterialSubject=new QueryWrapper<>();
            queryWrapperMaterialSubject.lambda().eq(MaterialSubjectEntity::getContractId,entity.getContractId());
            //子表数据删除
            materialSubjectService.remove(queryWrapperMaterialSubject);
            QueryWrapper<WorktypeSubjectEntity> queryWrapperWorktypeSubject=new QueryWrapper<>();
            queryWrapperWorktypeSubject.lambda().eq(WorktypeSubjectEntity::getContractId,entity.getContractId());
            //子表数据删除
            worktypeSubjectService.remove(queryWrapperWorktypeSubject);
            QueryWrapper<AssetSubjectEntity> queryWrapperAssetSubject=new QueryWrapper<>();
            queryWrapperAssetSubject.lambda().eq(AssetSubjectEntity::getContractId,entity.getContractId());
            //子表数据删除
            assetSubjectService.remove(queryWrapperAssetSubject);
            QueryWrapper<TaskSubjectEntity> queryWrapperTaskSubject=new QueryWrapper<>();
            queryWrapperTaskSubject.lambda().eq(TaskSubjectEntity::getContractId,entity.getContractId());
            //子表数据删除
            taskSubjectService.remove(queryWrapperTaskSubject);
            QueryWrapper<PaymentPlanEntity> queryWrapperPaymentPlan=new QueryWrapper<>();
            queryWrapperPaymentPlan.lambda().eq(PaymentPlanEntity::getContractId,entity.getContractId());
            //子表数据删除
            paymentPlanService.remove(queryWrapperPaymentPlan);
        }
        return ActionResult.success(MsgCode.SU003.get());
    }
    /**
    * 批量删除
    * @param obj
    * @return
    */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody Object obj){
    Map<String, Object> objectMap = JsonUtil.entityToMap(obj);
    List<String> idList = JsonUtil.getJsonToList(objectMap.get("ids"), String.class);
    String errInfo = "";
    List<String> successList = new ArrayList<>();
        for (String allId : idList){
            try {
                this.delete(allId,false);
                successList.add(allId);
            } catch (Exception e) {
                errInfo = e.getMessage();
            }
        }
        if (successList.size() == 0 && StringUtil.isNotEmpty(errInfo)){
            return ActionResult.fail(errInfo);
        }
        return ActionResult.success(MsgCode.SU003.get());
    }
    /**
    * 编辑
    * @param id
    * @param contractForm
    * @return
    */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid ContractForm contractForm,
                                @RequestParam(value = "isImport", required = false) boolean isImport){
        ContractEntity entity= contractService.getInfo(id);
        if(entity!=null){
            contractForm.setContractId(String.valueOf(entity.getContractId()));

            if (!isImport) {
                String b =  contractService.checkForm(contractForm,1);
                if (StringUtil.isNotEmpty(b)){
                    return ActionResult.fail(b );
                }
            }

            try{
                contractService.saveOrUpdate(contractForm,id,false);
            }catch (DataException e1){
                return ActionResult.fail(e1.getMessage());
            }catch(Exception e){
                return ActionResult.fail(MsgCode.FA029.get());
            }
            return ActionResult.success(MsgCode.SU004.get());
        }else{
            return ActionResult.fail(MsgCode.FA002.get());
        }
    }
    /**
    * 表单信息(详情页)
    * 详情页面使用-转换数据
    * @param id
    * @return
    */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id){
        ContractEntity entity= contractService.getInfo(id);
        if(entity==null){
            return ActionResult.fail(MsgCode.FA001.get());
        }
        Map<String, Object> contractMap=JsonUtil.entityToMap(entity);
        contractMap.put("id", contractMap.get("contract_id"));
        //副表数据
        //子表数据
        List<ProductSubjectEntity> productSubjectList = entity.getProductSubject();
        contractMap.put("tableProductList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(productSubjectList)));
        contractMap.put("productSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(productSubjectList)));
        List<MaterialSubjectEntity> materialSubjectList = entity.getMaterialSubject();
        contractMap.put("tableMaterialList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(materialSubjectList)));
        contractMap.put("materialSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(materialSubjectList)));
        List<WorktypeSubjectEntity> worktypeSubjectList = entity.getWorktypeSubject();
        contractMap.put("tableWorktypeList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(worktypeSubjectList)));
        contractMap.put("worktypeSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(worktypeSubjectList)));
        List<AssetSubjectEntity> assetSubjectList = entity.getAssetSubject();
        contractMap.put("tableAssetList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(assetSubjectList)));
        contractMap.put("assetSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(assetSubjectList)));
        List<TaskSubjectEntity> taskSubjectList = entity.getTaskSubject();
        contractMap.put("tableTaskList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(taskSubjectList)));
        contractMap.put("taskSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(taskSubjectList)));
        List<PaymentPlanEntity> paymentPlanList = entity.getPaymentPlan();
        contractMap.put("tableField3494b2",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(paymentPlanList)));
        contractMap.put("paymentPlanList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(paymentPlanList)));
        boolean isPc = "pc".equals(ServletUtil.getHeader("yunzhupaas-origin" ));
        contractMap = generaterSwapUtil.swapDataDetail(contractMap,ContractConstant.getFormData(),"822512474837222405",isPc?false:false);
        //子表数据
        contractMap.put("productSubjectList",contractMap.get("tableProductList"));
        contractMap.put("materialSubjectList",contractMap.get("tableMaterialList"));
        contractMap.put("worktypeSubjectList",contractMap.get("tableWorktypeList"));
        contractMap.put("assetSubjectList",contractMap.get("tableAssetList"));
        contractMap.put("taskSubjectList",contractMap.get("tableTaskList"));
        contractMap.put("paymentPlanList",contractMap.get("tableField3494b2"));
        return ActionResult.success(contractMap);
    }
    /**
    * 获取详情(编辑页)
    * 编辑页面使用-不转换数据
    * @param id
    * @return
    */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id){
        ContractEntity entity= contractService.getInfo(id);
        if(entity==null){
            return ActionResult.fail(MsgCode.FA001.get());
        }
        Map<String, Object> contractMap=JsonUtil.entityToMap(entity);
        contractMap.put("id", contractMap.get("contract_id"));
        //副表数据
        //子表数据
        List<ProductSubjectEntity> productSubjectList = entity.getProductSubject();
        contractMap.put("tableProductList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(productSubjectList)));
        contractMap.put("productSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(productSubjectList)));
        List<MaterialSubjectEntity> materialSubjectList = entity.getMaterialSubject();
        contractMap.put("tableMaterialList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(materialSubjectList)));
        contractMap.put("materialSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(materialSubjectList)));
        List<WorktypeSubjectEntity> worktypeSubjectList = entity.getWorktypeSubject();
        contractMap.put("tableWorktypeList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(worktypeSubjectList)));
        contractMap.put("worktypeSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(worktypeSubjectList)));
        List<AssetSubjectEntity> assetSubjectList = entity.getAssetSubject();
        contractMap.put("tableAssetList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(assetSubjectList)));
        contractMap.put("assetSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(assetSubjectList)));
        List<TaskSubjectEntity> taskSubjectList = entity.getTaskSubject();
        contractMap.put("tableTaskList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(taskSubjectList)));
        contractMap.put("taskSubjectList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(taskSubjectList)));
        List<PaymentPlanEntity> paymentPlanList = entity.getPaymentPlan();
        contractMap.put("tableField3494b2",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(paymentPlanList)));
        contractMap.put("paymentPlanList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(paymentPlanList)));
        contractMap = generaterSwapUtil.swapDataForm(contractMap,ContractConstant.getFormData(),ContractConstant.TABLEFIELDKEY,ContractConstant.TABLERENAMES);
        return ActionResult.success(contractMap);
    }

}
