
package com.yunzhupaas.cm.service.impl;

import com.yunzhupaas.cm.entity.*;
import com.yunzhupaas.cm.mapper.ContractMapper;
import com.yunzhupaas.cm.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.cm.model.contract.*;
import org.springframework.stereotype.Service;
import com.yunzhupaas.base.service.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.yunzhupaas.util.GeneraterSwapUtil;
import java.sql.Connection;
import java.sql.SQLException;
import lombok.Cleanup;
import com.yunzhupaas.database.plugins.DynamicSourceGeneratorInterface;
import com.yunzhupaas.database.util.DynamicDataSourceUtil;
import org.apache.commons.collections4.CollectionUtils;
import com.yunzhupaas.i18n.util.I18nUtil;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.constant.MsgCode;
import java.math.BigDecimal;
import cn.hutool.core.util.ObjectUtil;
import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.yunzhupaas.base.model.ColumnDataModel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yunzhupaas.model.QueryAllModel;
import java.text.SimpleDateFormat;
import com.yunzhupaas.util.*;
import java.util.*;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.permission.entity.UserEntity;
import com.github.pagehelper.PageHelper;
/**
 *
 * 合同管理
 * 版本： V5.2.7
 * 版权： Copyright @ 2025  深圳市乐程软件有限公司版权所有
 * 作者： 深圳市乐程软件有限公司
 * 日期： 2026-05-20
 */
@Service
public class ContractServiceImpl extends SuperServiceImpl<ContractMapper, ContractEntity> implements ContractService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private ProductSubjectService productSubjectService;
    @Autowired
    private MaterialSubjectService materialSubjectService;
    @Autowired
    private WorktypeSubjectService worktypeSubjectService;
    @Autowired
    private AssetSubjectService assetSubjectService;
    @Autowired
    private TaskSubjectService taskSubjectService;
    @Autowired
    private PaymentPlanService paymentPlanService;
    @Override
    public List<ContractEntity> getList(ContractPagination contractPagination){
        return getTypeList(contractPagination,contractPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<ContractEntity> getTypeList(ContractPagination contractPagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("cm_contract",ContractEntity.class);
        tableClassMap.put("cm_product_subject",ProductSubjectEntity.class);
        tableClassMap.put("cm_worktype_subject",WorktypeSubjectEntity.class);
        tableClassMap.put("cm_asset_subject",AssetSubjectEntity.class);
        tableClassMap.put("cm_material_subject",MaterialSubjectEntity.class);
        tableClassMap.put("cm_task_subject",TaskSubjectEntity.class);
        tableClassMap.put("cm_payment_plan",PaymentPlanEntity.class);

        MPJLambdaWrapper<ContractEntity> wrapper = JoinWrappers
                .lambda("cm_contract",ContractEntity.class)
                .selectCollection(ProductSubjectEntity.class,ContractEntity::getProductSubject)
                .leftJoin(ProductSubjectEntity.class,"cm_product_subject",ProductSubjectEntity::getContractId,ContractEntity::getContractId)
                .selectCollection(WorktypeSubjectEntity.class,ContractEntity::getWorktypeSubject)
                .leftJoin(WorktypeSubjectEntity.class,"cm_worktype_subject",WorktypeSubjectEntity::getContractId,ContractEntity::getContractId)
                .selectCollection(AssetSubjectEntity.class,ContractEntity::getAssetSubject)
                .leftJoin(AssetSubjectEntity.class,"cm_asset_subject",AssetSubjectEntity::getContractId,ContractEntity::getContractId)
                .selectCollection(MaterialSubjectEntity.class,ContractEntity::getMaterialSubject)
                .leftJoin(MaterialSubjectEntity.class,"cm_material_subject",MaterialSubjectEntity::getContractId,ContractEntity::getContractId)
                .selectCollection(TaskSubjectEntity.class,ContractEntity::getTaskSubject)
                .leftJoin(TaskSubjectEntity.class,"cm_task_subject",TaskSubjectEntity::getContractId,ContractEntity::getContractId)
                .selectCollection(PaymentPlanEntity.class,ContractEntity::getPaymentPlan)
                .leftJoin(PaymentPlanEntity.class,"cm_payment_plan",PaymentPlanEntity::getContractId,ContractEntity::getContractId)
                .selectAll(ContractEntity.class);
        MPJLambdaWrapper<ContractEntity> wrapper2 = JoinWrappers
                .lambda("cm_contract",ContractEntity.class)
                .leftJoin(ProductSubjectEntity.class,"cm_product_subject",ProductSubjectEntity::getContractId,ContractEntity::getContractId)
                .leftJoin(WorktypeSubjectEntity.class,"cm_worktype_subject",WorktypeSubjectEntity::getContractId,ContractEntity::getContractId)
                .leftJoin(AssetSubjectEntity.class,"cm_asset_subject",AssetSubjectEntity::getContractId,ContractEntity::getContractId)
                .leftJoin(MaterialSubjectEntity.class,"cm_material_subject",MaterialSubjectEntity::getContractId,ContractEntity::getContractId)
                .leftJoin(TaskSubjectEntity.class,"cm_task_subject",TaskSubjectEntity::getContractId,ContractEntity::getContractId)
                .leftJoin(PaymentPlanEntity.class,"cm_payment_plan",PaymentPlanEntity::getContractId,ContractEntity::getContractId)
                .distinct().select(ContractEntity::getContractId);

        QueryAllModel queryAllModel = new QueryAllModel();
        queryAllModel.setWrapper(wrapper);
        queryAllModel.setClassMap(tableClassMap);
        queryAllModel.setDbLink(ContractConstant.DBLINKID);
        //数据过滤
        boolean isPc = ServletUtil.getHeader("yunzhupaas-origin").equals("pc");
        String columnData = !isPc ? ContractConstant.getAppColumnData() : ContractConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());
        queryAllModel.setRuleJson(ruleJson);
        //高级查询
        boolean hasSuperQuery =  true;
        if (hasSuperQuery) {
            queryAllModel.setSuperJson(contractPagination.getSuperQueryJson());
        }
        //数据权限
        boolean pcPermission = true;
        boolean appPermission = false;
        if (isPc && pcPermission) {
            queryAllModel.setModuleId(contractPagination.getMenuId());
        }
        if (!isPc && appPermission) {
            queryAllModel.setModuleId(contractPagination.getMenuId());
        }
        //拼接复杂条件
        wrapper = generaterSwapUtil.getConditionAllTable(queryAllModel);
        if(wrapper == null) return new ArrayList<>();
        queryAllModel.setWrapper(wrapper2);
        wrapper2 = generaterSwapUtil.getConditionAllTable(queryAllModel);
        //其他条件拼接
        otherConditions(contractPagination, wrapper, isPc);
        otherConditions(contractPagination, wrapper2, isPc);

        if("0".equals(dataType)){
            com.github.pagehelper.Page<Object> objects = PageHelper.startPage((int) contractPagination.getCurrentPage(), (int) contractPagination.getPageSize(), true);
            List<ContractEntity> userIPage = this.selectJoinList(ContractEntity.class, wrapper2);
            List<Object> collect = userIPage.stream().map(t -> t.getContractId()).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(collect)){
                wrapper.in(ContractEntity::getContractId,collect);
            }
            List<ContractEntity> result = this.selectJoinList(ContractEntity.class, wrapper);
            return contractPagination.setData(result,objects.getTotal());
        }else{
            List<ContractEntity> list = this.selectJoinList(ContractEntity.class, wrapper);
            if("2".equals(dataType)){
                List<Object> selectIds = Arrays.asList(contractPagination.getSelectIds());
                return list.stream().filter(t -> selectIds.contains(t.getContractId())).collect(Collectors.toList());
            }else{
                return list;
            }
        }

    }

    /**
    * 其他条件拼接
    */
    private void otherConditions(ContractPagination contractPagination, MPJLambdaWrapper<ContractEntity> wrapper, boolean isPc) {
        String databaseName;
        try {
            @Cleanup Connection cnn = DynamicDataSourceUtil.getCurrentConnection();
            databaseName = cnn.getMetaData().getDatabaseProductName().trim();
        } catch (SQLException e) {
            throw new DataException(e.getMessage());
        }
        //流程数据隔离
        List<String> flowIds = generaterSwapUtil.getFlowIds(contractPagination.getFlowId());
        wrapper.in(ContractEntity::getFlowId,flowIds);
        //关键词
        if(ObjectUtil.isNotEmpty(contractPagination.getYunzhupaasKeyword())){
        }
        //普通查询
        if(isPc){
            if(ObjectUtil.isNotEmpty(contractPagination.getContractName())){
                String value = contractPagination.getContractName() instanceof List ?
                    JsonUtil.getObjectToString(contractPagination.getContractName()) :
                    String.valueOf(contractPagination.getContractName());
                wrapper.like(ContractEntity::getContractName,value);
            }

            if(ObjectUtil.isNotEmpty(contractPagination.getOrgId())){
                List<String> idList = new ArrayList<>();
                try {
                    String[][] orgId = JsonUtil.getJsonToBean(contractPagination.getOrgId(),String[][].class);
                    for(int i=0;i<orgId.length;i++){
                        if(orgId[i].length>0){
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(orgId[i])));
                        }
                    }
                }catch (Exception e1){
                    try {
                        List<String> orgId = JsonUtil.getJsonToList(contractPagination.getOrgId(),String.class);
                        if(orgId.size()>0){
                            idList.add(JsonUtil.getObjectToString(orgId));
                        }
                    }catch (Exception e2){
                        idList.add(String.valueOf(contractPagination.getOrgId()));
                    }
                }
                wrapper.and(t->{
                    idList.forEach(tt->{
                        if(StringUtil.isNotEmpty(tt) && "Microsoft SQL Server".equalsIgnoreCase(databaseName)){
                            tt = tt.replaceFirst("\\[","[[]");
                        }
                        t.like(ContractEntity::getOrgId, tt).or();
                    });
                });
            }

            if(ObjectUtil.isNotEmpty(contractPagination.getContractCategory())){
                List<String> idList = new ArrayList<>();
                try {
                    String[][] contractCategory = JsonUtil.getJsonToBean(contractPagination.getContractCategory(),String[][].class);
                    for(int i=0;i<contractCategory.length;i++){
                        if(contractCategory[i].length>0){
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(contractCategory[i])));
                        }
                    }
                }catch (Exception e1){
                    try {
                        List<String> contractCategory = JsonUtil.getJsonToList(contractPagination.getContractCategory(),String.class);
                        if(contractCategory.size()>0){
                            idList.addAll(contractCategory);
                        }
                    }catch (Exception e2){
                        idList.add(String.valueOf(contractPagination.getContractCategory()));
                    }
                }
                wrapper.and(t->{
                    idList.forEach(tt->{
                        if(StringUtil.isNotEmpty(tt) && "Microsoft SQL Server".equalsIgnoreCase(databaseName)){
                            tt = tt.replaceFirst("\\[","[[]");
                        }
                        t.like(ContractEntity::getContractCategory, tt).or();
                    });
                });
            }

            if(ObjectUtil.isNotEmpty(contractPagination.getContractCode())){
                String value = contractPagination.getContractCode() instanceof List ?
                    JsonUtil.getObjectToString(contractPagination.getContractCode()) :
                    String.valueOf(contractPagination.getContractCode());
                wrapper.like(ContractEntity::getContractCode,value);
            }

        }
        //排序
        if(StringUtil.isEmpty(contractPagination.getSidx())){
                wrapper.orderByDesc(ContractEntity::getContractId);
        }else{
            try {
                String[] split = contractPagination.getSidx().split(",");
                for(String sidx:split){
                ContractEntity contractEntity = new ContractEntity();
                    String oderTableField = contractEntity.getClass().getAnnotation(TableName.class).value();
                    boolean descFlag = sidx.startsWith("-");
                    String sidxField = descFlag ? sidx.substring(1) : sidx;
                    try{
                        Field declaredField = contractEntity.getClass().getDeclaredField(sidxField);
                        declaredField.setAccessible(true);
                        sidxField = declaredField.getAnnotation(TableField.class).value();
                    }catch (Exception e){
                    }
                    String finalOderTableField = oderTableField;
                    String finalSidxField = sidxField;
                    Object select = wrapper.getSelectColumns().stream().filter(t -> Objects.equals(finalOderTableField, t.getTableAlias())
                            && Objects.equals(finalSidxField, t.getColumn())).findFirst().orElse(null);
                    oderTableField = oderTableField + "." + sidxField;
                    if (select == null) {
                        wrapper.select(oderTableField);
                    }
                    if (descFlag) {
                        wrapper.orderByDesc(oderTableField);
                    } else {
                        wrapper.orderByAsc(oderTableField);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public ContractEntity getInfo(String contractid){
        MPJLambdaWrapper<ContractEntity> wrapper = JoinWrappers
                .lambda("cm_contract",ContractEntity.class)
                .selectCollection(ProductSubjectEntity.class,ContractEntity::getProductSubject)
                .leftJoin(ProductSubjectEntity.class,"cm_product_subject",ProductSubjectEntity::getContractId,ContractEntity::getContractId)
                .selectCollection(WorktypeSubjectEntity.class,ContractEntity::getWorktypeSubject)
                .leftJoin(WorktypeSubjectEntity.class,"cm_worktype_subject",WorktypeSubjectEntity::getContractId,ContractEntity::getContractId)
                .selectCollection(AssetSubjectEntity.class,ContractEntity::getAssetSubject)
                .leftJoin(AssetSubjectEntity.class,"cm_asset_subject",AssetSubjectEntity::getContractId,ContractEntity::getContractId)
                .selectCollection(MaterialSubjectEntity.class,ContractEntity::getMaterialSubject)
                .leftJoin(MaterialSubjectEntity.class,"cm_material_subject",MaterialSubjectEntity::getContractId,ContractEntity::getContractId)
                .selectCollection(TaskSubjectEntity.class,ContractEntity::getTaskSubject)
                .leftJoin(TaskSubjectEntity.class,"cm_task_subject",TaskSubjectEntity::getContractId,ContractEntity::getContractId)
                .selectCollection(PaymentPlanEntity.class,ContractEntity::getPaymentPlan)
                .leftJoin(PaymentPlanEntity.class,"cm_payment_plan",PaymentPlanEntity::getContractId,ContractEntity::getContractId)
                .selectAll(ContractEntity.class);
        wrapper.and(
            t->t.eq(ContractEntity::getContractId, contractid )
            .or().eq(ContractEntity::getFlowTaskId, contractid)
        );
        return this.selectJoinOne(ContractEntity.class,wrapper);
    }
    @Override
    public void create(ContractEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String contractid, ContractEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ContractEntity entity){
        if(entity!=null){
            this.removeById(entity.getContractId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(ContractForm form,int i) {
        List<String> flowIds = generaterSwapUtil.getFlowIds(form.getFlowId());
        boolean isUp =StringUtil.isNotEmpty(form.getContractId()) && !form.getContractId().equals("0");
        Object id= null;
        String countRecover = "";
        String fieldTipName = "";
        String canNotNull = I18nUtil.getMessageStr("sys.validate.textRequiredSuffix", "不能为空");
        String canNotRepeated = I18nUtil.getMessageStr("EXIST103", "不能重复");
        if (isUp){
            id = form.getContractId();
        }
        //主表字段验证
            fieldTipName =  "合同类型"; 
            fieldTipName =  "引用模版"; 
            fieldTipName =  "合同名称"; 
                if(StringUtil.isEmpty(form.getContractName())){
                    return fieldTipName + canNotNull;
                }
            fieldTipName =  "合同编码"; 
            fieldTipName =  "归属组织"; 
            fieldTipName =  "归属项目"; 
            fieldTipName =  "合同分类"; 
            fieldTipName =  "签约日期"; 
            fieldTipName =  "开始日期"; 
            fieldTipName =  "结束日期"; 
            fieldTipName =  "是否子合同"; 
            fieldTipName =  "关联合同"; 
            fieldTipName =  "经办人"; 
            fieldTipName =  "打印合同模版"; 
            fieldTipName =  "备注"; 
            fieldTipName =  "我方类型"; 
            fieldTipName =  "我方单位"; 
            fieldTipName =  "我方名称"; 
            fieldTipName =  "合作方类型"; 
            fieldTipName =  "合作单位"; 
            fieldTipName =  "合作方名称"; 
            fieldTipName =  "第三方类型"; 
            fieldTipName =  "第三方单位"; 
            fieldTipName =  "第三方名称"; 
            fieldTipName =  "原合同金额"; 
            fieldTipName =  "最终签约金额"; 
            fieldTipName =  "签约金额大写"; 
            fieldTipName =  "税额"; 
            fieldTipName =  "不含税金额"; 
            fieldTipName =  "合同附件"; 
        //子表字段验证
            if (form.getProductSubjectList()!=null){

                    fieldTipName =  "产品清单" 
                            + "-" +  "产品名称"; 

                        for(ProductSubjectModel t : form.getProductSubjectList()){
                            if( t.getProductId() != null ){
                                t.setProductId(t.getProductId());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "产品清单" 
                            + "-" +  "品牌"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "规格型号"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "数量"; 

                        for(ProductSubjectModel t : form.getProductSubjectList()){
                            if( t.getQuantity() != null ){
                                t.setQuantity(t.getQuantity());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "产品清单" 
                            + "-" +  "单价"; 

                        for(ProductSubjectModel t : form.getProductSubjectList()){
                            if( t.getUnitPrice() != null ){
                                t.setUnitPrice(t.getUnitPrice());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "产品清单" 
                            + "-" +  "单位"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "币种"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "总金额"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "折扣类型"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "折扣值"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "最终金额"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "税率"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "税额"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "保修期"; 


                    fieldTipName =  "产品清单" 
                            + "-" +  "保修条款"; 

            }
            if (form.getMaterialSubjectList()!=null){

                    fieldTipName =  "材料清单" 
                            + "-" +  "材料名称"; 

                        for(MaterialSubjectModel t : form.getMaterialSubjectList()){
                            if( t.getMaterialId() != null ){
                                t.setMaterialId(t.getMaterialId());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "材料清单" 
                            + "-" +  "品牌"; 


                    fieldTipName =  "材料清单" 
                            + "-" +  "数量"; 

                        for(MaterialSubjectModel t : form.getMaterialSubjectList()){
                            if( t.getQuantity() != null ){
                                t.setQuantity(t.getQuantity());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "材料清单" 
                            + "-" +  "单价"; 

                        for(MaterialSubjectModel t : form.getMaterialSubjectList()){
                            if( t.getUnitPrice() != null ){
                                t.setUnitPrice(t.getUnitPrice());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "材料清单" 
                            + "-" +  "单位"; 


                    fieldTipName =  "材料清单" 
                            + "-" +  "币种"; 


                    fieldTipName =  "材料清单" 
                            + "-" +  "总金额"; 


                    fieldTipName =  "材料清单" 
                            + "-" +  "税率"; 


                    fieldTipName =  "材料清单" 
                            + "-" +  "税额"; 


                    fieldTipName =  "材料清单" 
                            + "-" +  "保修期"; 


                    fieldTipName =  "材料清单" 
                            + "-" +  "保修条款"; 

            }
            if (form.getWorktypeSubjectList()!=null){

                    fieldTipName =  "人力清单" 
                            + "-" +  "工种"; 

                        for(WorktypeSubjectModel t : form.getWorktypeSubjectList()){
                            if( t.getWorkTypeId() != null ){
                                t.setWorkTypeId(t.getWorkTypeId());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "人力清单" 
                            + "-" +  "数量"; 

                        for(WorktypeSubjectModel t : form.getWorktypeSubjectList()){
                            if( t.getQuantity() != null ){
                                t.setQuantity(t.getQuantity());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "人力清单" 
                            + "-" +  "销售单价"; 

                        for(WorktypeSubjectModel t : form.getWorktypeSubjectList()){
                            if( StringUtil.isNotEmpty(t.getUnitPrice()) ){
                                t.setUnitPrice(t.getUnitPrice().trim());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "人力清单" 
                            + "-" +  "数量单位"; 


                    fieldTipName =  "人力清单" 
                            + "-" +  "币种"; 


                    fieldTipName =  "人力清单" 
                            + "-" +  "总金额"; 


                    fieldTipName =  "人力清单" 
                            + "-" +  "折扣类型"; 


                    fieldTipName =  "人力清单" 
                            + "-" +  "折扣值"; 


                    fieldTipName =  "人力清单" 
                            + "-" +  "最终金额"; 


                    fieldTipName =  "人力清单" 
                            + "-" +  "税率"; 


                    fieldTipName =  "人力清单" 
                            + "-" +  "税额"; 


                    fieldTipName =  "人力清单" 
                            + "-" +  "工种描述"; 

            }
            if (form.getAssetSubjectList()!=null){

                    fieldTipName =  "资产租赁" 
                            + "-" +  "资产名称"; 

                        for(AssetSubjectModel t : form.getAssetSubjectList()){
                            if( t.getAssetId() != null ){
                                t.setAssetId(t.getAssetId());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "资产租赁" 
                            + "-" +  "开始日期"; 


                    fieldTipName =  "资产租赁" 
                            + "-" +  "结束日期"; 


                    fieldTipName =  "资产租赁" 
                            + "-" +  "租赁天数"; 

                        for(AssetSubjectModel t : form.getAssetSubjectList()){
                            if( t.getQuantity() != null ){
                                t.setQuantity(t.getQuantity());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "资产租赁" 
                            + "-" +  "租赁单价"; 

                        for(AssetSubjectModel t : form.getAssetSubjectList()){
                            if( t.getUnitPrice() != null ){
                                t.setUnitPrice(t.getUnitPrice());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "资产租赁" 
                            + "-" +  "单位"; 


                    fieldTipName =  "资产租赁" 
                            + "-" +  "币种"; 


                    fieldTipName =  "资产租赁" 
                            + "-" +  "总金额"; 


                    fieldTipName =  "资产租赁" 
                            + "-" +  "折扣类型"; 


                    fieldTipName =  "资产租赁" 
                            + "-" +  "折扣值"; 


                    fieldTipName =  "资产租赁" 
                            + "-" +  "最终金额"; 


                    fieldTipName =  "资产租赁" 
                            + "-" +  "税率"; 


                    fieldTipName =  "资产租赁" 
                            + "-" +  "税额"; 

            }
            if (form.getTaskSubjectList()!=null){

                    fieldTipName =  "工作量清单" 
                            + "-" +  "任务名称"; 

                        for(TaskSubjectModel t : form.getTaskSubjectList()){
                            if( StringUtil.isNotEmpty(t.getTaskName()) ){
                                t.setTaskName(t.getTaskName().trim());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "工作量清单" 
                            + "-" +  "任务描述"; 


                    fieldTipName =  "工作量清单" 
                            + "-" +  "数量"; 

                        for(TaskSubjectModel t : form.getTaskSubjectList()){
                            if( t.getQuantity() != null ){
                                t.setQuantity(t.getQuantity());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "工作量清单" 
                            + "-" +  "单价"; 

                        for(TaskSubjectModel t : form.getTaskSubjectList()){
                            if( t.getUnitPrice() != null ){
                                t.setUnitPrice(t.getUnitPrice());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "工作量清单" 
                            + "-" +  "单位"; 


                    fieldTipName =  "工作量清单" 
                            + "-" +  "币种"; 


                    fieldTipName =  "工作量清单" 
                            + "-" +  "总金额"; 


                    fieldTipName =  "工作量清单" 
                            + "-" +  "折扣类型"; 


                    fieldTipName =  "工作量清单" 
                            + "-" +  "折扣值"; 


                    fieldTipName =  "工作量清单" 
                            + "-" +  "最终金额"; 


                    fieldTipName =  "工作量清单" 
                            + "-" +  "税率"; 


                    fieldTipName =  "工作量清单" 
                            + "-" +  "税额"; 


                    fieldTipName =  "工作量清单" 
                            + "-" +  "备注"; 

            }
            if (form.getPaymentPlanList()!=null){

                    fieldTipName =  "付款计划" 
                            + "-" +  "序号"; 


                    fieldTipName =  "付款计划" 
                            + "-" +  "款项名称"; 

                        for(PaymentPlanModel t : form.getPaymentPlanList()){
                            if( StringUtil.isNotEmpty(t.getPaymentName()) ){
                                t.setPaymentName(t.getPaymentName().trim());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "付款计划" 
                            + "-" +  "款项类型"; 

                        for(PaymentPlanModel t : form.getPaymentPlanList()){
                            if( t.getBillingItemId() != null ){
                                t.setBillingItemId(t.getBillingItemId());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "付款计划" 
                            + "-" +  "付款条件"; 

                        for(PaymentPlanModel t : form.getPaymentPlanList()){
                            if( StringUtil.isNotEmpty(t.getPaymentCondition()) ){
                                t.setPaymentCondition(t.getPaymentCondition().trim());
                            }
                            else{
                                return fieldTipName + canNotNull;
                            }
                        }

                    fieldTipName =  "付款计划" 
                            + "-" +  "预计付款日期"; 


                    fieldTipName =  "付款计划" 
                            + "-" +  "付款比例"; 


                    fieldTipName =  "付款计划" 
                            + "-" +  "付款金额"; 


                    fieldTipName =  "付款计划" 
                            + "-" +  "备注"; 

            }
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param contractForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(ContractForm contractForm,String id, boolean isSave) throws Exception{
        List<Map<String, Object>> formOperates = contractForm.getFormOperates();
        List<String> hasOperate = new ArrayList<>();
        boolean noOperate = false;
        if(CollectionUtils.isNotEmpty(formOperates)){
            for (Map<String, Object> formOperate : formOperates) {
                String formOperateId = formOperate.get("id").toString();
                boolean formOperateWrite = formOperate.get("write") ==null? false : (boolean) formOperate.get("write");
                if(formOperateWrite){
                    hasOperate.add(formOperateId);
                }
            }
        }else{
            noOperate = true;
        }
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        contractForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(ContractConstant.getFormData(),contractForm,ContractConstant.TABLERENAMES),ContractForm.class);
        ContractEntity entity = JsonUtil.getJsonToBean(contractForm, ContractEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        entity.setFlowId(contractForm.getFlowId());
        if(isSave){
            entity.setFlowTaskId(mainUuid);
                if(hasOperate.contains("contract_code") || noOperate){
                        entity.setContractCode(generaterSwapUtil.getBillNumber("contractCode", false));
                }
            entity.setContractId(mainUuid);
        } else {
                if(hasOperate.contains("contract_code") || noOperate){
                    if(StringUtil.isEmpty(entity.getContractCode()) ){
                        entity.setContractCode(generaterSwapUtil.getBillNumber("contractCode", false));
                    }
                }
        }
        boolean b = this.saveOrUpdate(entity);
    ContractEntity info = this.getInfo(mainUuid);
    if (info == null) throw new RuntimeException(MsgCode.FA001.get());

        //ProductSubject子表数据新增修改
        QueryWrapper<ProductSubjectEntity> ProductSubjectqueryWrapper = new QueryWrapper<>();
        ProductSubjectqueryWrapper.lambda().eq(ProductSubjectEntity::getContractId, info.getContractId());
        if(!isSave && !CollectionUtils.isNotEmpty(contractForm.getProductSubjectList())){
            productSubjectService.remove(ProductSubjectqueryWrapper);
        }
        if (CollectionUtils.isNotEmpty(contractForm.getProductSubjectList())){
            List<ProductSubjectEntity> tableProductList = JsonUtil.getJsonToList(contractForm.getProductSubjectList(),ProductSubjectEntity.class);
            //移除的数据
            List<Object> childIds = tableProductList.stream().filter(t->t.getSubjectId()!=null).map(ProductSubjectEntity::getSubjectId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(childIds)){
                ProductSubjectqueryWrapper.lambda().notIn(ProductSubjectEntity::getSubjectId,childIds);
            }
            productSubjectService.remove(ProductSubjectqueryWrapper);
            for(ProductSubjectEntity entitys : tableProductList){
                entitys.setContractId(entity.getContractId());
                if(entitys.getSubjectId()==null){
                    entitys.setSubjectId(RandomUtil.uuId());
                }
                productSubjectService.saveOrUpdate(entitys);
            }
        }
        //MaterialSubject子表数据新增修改
        QueryWrapper<MaterialSubjectEntity> MaterialSubjectqueryWrapper = new QueryWrapper<>();
        MaterialSubjectqueryWrapper.lambda().eq(MaterialSubjectEntity::getContractId, info.getContractId());
        if(!isSave && !CollectionUtils.isNotEmpty(contractForm.getMaterialSubjectList())){
            materialSubjectService.remove(MaterialSubjectqueryWrapper);
        }
        if (CollectionUtils.isNotEmpty(contractForm.getMaterialSubjectList())){
            List<MaterialSubjectEntity> tableMaterialList = JsonUtil.getJsonToList(contractForm.getMaterialSubjectList(),MaterialSubjectEntity.class);
            //移除的数据
            List<Object> childIds = tableMaterialList.stream().filter(t->t.getSubjectId()!=null).map(MaterialSubjectEntity::getSubjectId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(childIds)){
                MaterialSubjectqueryWrapper.lambda().notIn(MaterialSubjectEntity::getSubjectId,childIds);
            }
            materialSubjectService.remove(MaterialSubjectqueryWrapper);
            for(MaterialSubjectEntity entitys : tableMaterialList){
                entitys.setContractId(entity.getContractId());
                if(entitys.getSubjectId()==null){
                    entitys.setSubjectId(RandomUtil.uuId());
                }
                materialSubjectService.saveOrUpdate(entitys);
            }
        }
        //WorktypeSubject子表数据新增修改
        QueryWrapper<WorktypeSubjectEntity> WorktypeSubjectqueryWrapper = new QueryWrapper<>();
        WorktypeSubjectqueryWrapper.lambda().eq(WorktypeSubjectEntity::getContractId, info.getContractId());
        if(!isSave && !CollectionUtils.isNotEmpty(contractForm.getWorktypeSubjectList())){
            worktypeSubjectService.remove(WorktypeSubjectqueryWrapper);
        }
        if (CollectionUtils.isNotEmpty(contractForm.getWorktypeSubjectList())){
            List<WorktypeSubjectEntity> tableWorktypeList = JsonUtil.getJsonToList(contractForm.getWorktypeSubjectList(),WorktypeSubjectEntity.class);
            //移除的数据
            List<Object> childIds = tableWorktypeList.stream().filter(t->t.getSubjectId()!=null).map(WorktypeSubjectEntity::getSubjectId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(childIds)){
                WorktypeSubjectqueryWrapper.lambda().notIn(WorktypeSubjectEntity::getSubjectId,childIds);
            }
            worktypeSubjectService.remove(WorktypeSubjectqueryWrapper);
            for(WorktypeSubjectEntity entitys : tableWorktypeList){
                entitys.setContractId(entity.getContractId());
                if(entitys.getSubjectId()==null){
                    entitys.setSubjectId(RandomUtil.uuId());
                }
                worktypeSubjectService.saveOrUpdate(entitys);
            }
        }
        //AssetSubject子表数据新增修改
        QueryWrapper<AssetSubjectEntity> AssetSubjectqueryWrapper = new QueryWrapper<>();
        AssetSubjectqueryWrapper.lambda().eq(AssetSubjectEntity::getContractId, info.getContractId());
        if(!isSave && !CollectionUtils.isNotEmpty(contractForm.getAssetSubjectList())){
            assetSubjectService.remove(AssetSubjectqueryWrapper);
        }
        if (CollectionUtils.isNotEmpty(contractForm.getAssetSubjectList())){
            List<AssetSubjectEntity> tableAssetList = JsonUtil.getJsonToList(contractForm.getAssetSubjectList(),AssetSubjectEntity.class);
            //移除的数据
            List<Object> childIds = tableAssetList.stream().filter(t->t.getSubjectId()!=null).map(AssetSubjectEntity::getSubjectId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(childIds)){
                AssetSubjectqueryWrapper.lambda().notIn(AssetSubjectEntity::getSubjectId,childIds);
            }
            assetSubjectService.remove(AssetSubjectqueryWrapper);
            for(AssetSubjectEntity entitys : tableAssetList){
                entitys.setContractId(entity.getContractId());
                if(entitys.getSubjectId()==null){
                    entitys.setSubjectId(RandomUtil.uuId());
                }
                assetSubjectService.saveOrUpdate(entitys);
            }
        }
        //TaskSubject子表数据新增修改
        QueryWrapper<TaskSubjectEntity> TaskSubjectqueryWrapper = new QueryWrapper<>();
        TaskSubjectqueryWrapper.lambda().eq(TaskSubjectEntity::getContractId, info.getContractId());
        if(!isSave && !CollectionUtils.isNotEmpty(contractForm.getTaskSubjectList())){
            taskSubjectService.remove(TaskSubjectqueryWrapper);
        }
        if (CollectionUtils.isNotEmpty(contractForm.getTaskSubjectList())){
            List<TaskSubjectEntity> tableTaskList = JsonUtil.getJsonToList(contractForm.getTaskSubjectList(),TaskSubjectEntity.class);
            //移除的数据
            List<Object> childIds = tableTaskList.stream().filter(t->t.getSubjectId()!=null).map(TaskSubjectEntity::getSubjectId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(childIds)){
                TaskSubjectqueryWrapper.lambda().notIn(TaskSubjectEntity::getSubjectId,childIds);
            }
            taskSubjectService.remove(TaskSubjectqueryWrapper);
            for(TaskSubjectEntity entitys : tableTaskList){
                entitys.setContractId(entity.getContractId());
                if(entitys.getSubjectId()==null){
                    entitys.setSubjectId(RandomUtil.uuId());
                }
                taskSubjectService.saveOrUpdate(entitys);
            }
        }
        //PaymentPlan子表数据新增修改
        QueryWrapper<PaymentPlanEntity> PaymentPlanqueryWrapper = new QueryWrapper<>();
        PaymentPlanqueryWrapper.lambda().eq(PaymentPlanEntity::getContractId, info.getContractId());
        if(!isSave && !CollectionUtils.isNotEmpty(contractForm.getPaymentPlanList())){
            paymentPlanService.remove(PaymentPlanqueryWrapper);
        }
        if (CollectionUtils.isNotEmpty(contractForm.getPaymentPlanList())){
            List<PaymentPlanEntity> tableField3494b2 = JsonUtil.getJsonToList(contractForm.getPaymentPlanList(),PaymentPlanEntity.class);
            //移除的数据
            List<Object> childIds = tableField3494b2.stream().filter(t->t.getPaymentPlanId()!=null).map(PaymentPlanEntity::getPaymentPlanId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(childIds)){
                PaymentPlanqueryWrapper.lambda().notIn(PaymentPlanEntity::getPaymentPlanId,childIds);
            }
            paymentPlanService.remove(PaymentPlanqueryWrapper);
            for(PaymentPlanEntity entitys : tableField3494b2){
                entitys.setContractId(entity.getContractId());
                if(entitys.getPaymentPlanId()==null){
                    entitys.setPaymentPlanId(RandomUtil.uuId());
                }
                paymentPlanService.saveOrUpdate(entitys);
            }
        }
    }
}
