<template>
    <BasicModal v-bind="$attrs" @register="registerModal"  width="1000px"
                    :minHeight="100"
:cancelText="t('common.cancelText','取消')"
:okText="t('common.okText','确定')"
                    @ok="handleSubmit" :closeFunc="onClose">
      <template #title>
        <a-space :size="10">
          <div class="text-16px font-medium">{{ title }}</div>
              <a-space-compact size="small" block  v-if="dataForm.id">
                <a-tooltip :title="t('common.prevRecord')">
                  <a-button size="small" :disabled="getPrevDisabled" @click="handlePrev">
                    <i class="icon-ym icon-ym-caret-left text-10px"></i>
                  </a-button>
                </a-tooltip>
                <a-tooltip :title="t('common.nextRecord')">
                  <a-button size="small" :disabled="getNextDisabled" @click="handleNext">
                    <i class="icon-ym icon-ym-caret-right text-10px"></i>
                  </a-button>
                </a-tooltip>
              </a-space-compact>
        </a-space>
      </template>
        <template #insertFooter>
          <div class="float-left mt-5px">
            <yunzhupaasCheckboxSingle v-model:value="submitType" :label="continueText" />
          </div>
        </template>
        <a-row class="dynamic-form ">
            <a-form :colon="false" size="middle" layout= "horizontal" 
            labelAlign= "right" 
 :labelCol="{ style: { width: '100px' } }"             :model="dataForm" :rules="dataRule" ref="formRef">
            <a-row :gutter="15">
                <!-- 具体表单 -->
    <a-col :span="12" class="ant-col-item"  >
        <a-form-item   
  name="contract_temp_code" >
<template #label>合同模版编码 
</template> <YunzhupaasInput    v-model:value="dataForm.contract_temp_code"  @change="changeData('contract_temp_code',-1)"  
 placeholder="请输入"   :allowClear='true'  :style='{"width":"100%"}' :maskConfig = "maskConfig.contract_temp_code" :showCount = "false"     >
</YunzhupaasInput>
        </a-form-item>
    </a-col>
    <a-col :span="12" class="ant-col-item"  >
        <a-form-item   
  name="contract_temp_name" >
<template #label>合同模版名称 
</template> <YunzhupaasInput    v-model:value="dataForm.contract_temp_name"  @change="changeData('contract_temp_name',-1)"  
 placeholder="请输入"   :allowClear='true'  :style='{"width":"100%"}' :maskConfig = "maskConfig.contract_temp_name" :showCount = "false"     >
</YunzhupaasInput>
        </a-form-item>
    </a-col>
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="remark" >
<template #label>备注 
</template> <YunzhupaasTextarea    v-model:value="dataForm.remark"  @change="changeData('remark',-1)"  
 placeholder="请输入"   :allowClear='true'  :style='{"width":"100%"}' :autoSize='{"minRows":3,"maxRows":3}'  :showCount = "false"     >
</YunzhupaasTextarea>
        </a-form-item>
    </a-col>
            <a-col :span="24" class="ant-col-item">
                <a-tabs  v-model:activeKey="state.activetabformItem45e7a2"  tabPosition="left" class="mb-20" >
                <a-tab-pane   tab="合同框架" key="1" forceRender>
                <a-row :gutter="15">
                <table class="table-grid-box" :style='{"--borderType":"solid","--borderColor":"#E2E0E0","--borderWidth":"1px"}'>
                <tbody
>
                <tr
>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="is_framework" >
<template #label>框架合同 
                        <BasicHelp  text="是：只有合同基本信息和合同主体，无合同清单、金额、付款计划。否：反之"  /></template> <YunzhupaasSwitch    v-model:value="dataForm.is_framework"  @change="changeData('is_framework',-1)"  
    >
</YunzhupaasSwitch>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="is_detail_list" >
<template #label>清单合同 
                        <BasicHelp  text="是：显示合同清单，合同金额根据清单金额汇总生成；否：不显示清单，只显示合同金额与付款计划，合同金额手工录入"  /></template> <YunzhupaasSwitch    v-model:value="dataForm.is_detail_list"  @change="changeData('is_detail_list',-1)"  
    >
</YunzhupaasSwitch>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                </tr>
                <tr
>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="enable_tableProductList" >
<template #label>启用产品清单 
</template> <YunzhupaasSwitch    v-model:value="dataForm.enable_tableProductList"  @change="changeData('enable_tableProductList',-1)"  
    >
</YunzhupaasSwitch>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="enable_tableMaterialList" >
<template #label>启用材料清单 
</template> <YunzhupaasSwitch    v-model:value="dataForm.enable_tableMaterialList"  @change="changeData('enable_tableMaterialList',-1)"  
    >
</YunzhupaasSwitch>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                </tr>
                <tr
>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="enable_tableWorktypeList" >
<template #label>启用人力清单 
</template> <YunzhupaasSwitch    v-model:value="dataForm.enable_tableWorktypeList"  @change="changeData('enable_tableWorktypeList',-1)"  
    >
</YunzhupaasSwitch>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="enable_tableAssetList" >
<template #label>启用资产清单 
</template> <YunzhupaasSwitch    v-model:value="dataForm.enable_tableAssetList"  @change="changeData('enable_tableAssetList',-1)"  
    >
</YunzhupaasSwitch>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                </tr>
                <tr
>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="enable_tableTaskList" >
<template #label>启用任务清单 
</template> <YunzhupaasSwitch    v-model:value="dataForm.enable_tableTaskList"  @change="changeData('enable_tableTaskList',-1)"  
    >
</YunzhupaasSwitch>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
                    </a-row>
                </td>
                </tr>
                <tr
>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
                    </a-row>
                </td>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
                    </a-row>
                </td>
                </tr>
                </tbody>
                </table>
            </a-row>
            </a-tab-pane >
                <a-tab-pane   tab="合同参数" key="2" forceRender>
                <a-row :gutter="15">
                <table class="table-grid-box" :style='{"--borderType":"solid","--borderColor":"#E2E0E0","--borderWidth":"1px"}'>
                <tbody
>
                <tr
>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="contract_type" >
<template #label>合同类型 
</template> <YunzhupaasSelect    v-model:value="dataForm.contract_type"  @change="changeData('contract_type',-1)"  
 placeholder="请选择"   :templateJson="state.interfaceRes.contract_type" :allowClear='true'  :style='{"width":"100%"}' :showSearch='false'          :options="optionsObj.contract_typeOptions"          :fieldNames="optionsObj.contract_typeProps"
    >
</YunzhupaasSelect>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="enable_printing" >
<template #label>启用在线打印 
</template> <YunzhupaasSwitch    v-model:value="dataForm.enable_printing"  @change="changeData('enable_printing',-1)"  
    >
</YunzhupaasSwitch>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                </tr>
                <tr
>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="our_company_type" >
<template #label>我方签约类型 
</template> <YunzhupaasSelect    v-model:value="dataForm.our_company_type"  @change="changeData('our_company_type',-1)"  
 placeholder="请选择"   :templateJson="state.interfaceRes.our_company_type" :allowClear='true'  :style='{"width":"100%"}' :showSearch='false'          :options="optionsObj.our_company_typeOptions"          :fieldNames="optionsObj.our_company_typeProps"
    >
</YunzhupaasSelect>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="second_party_type" >
<template #label>乙方签约类型 
</template> <YunzhupaasSelect    v-model:value="dataForm.second_party_type"  @change="changeData('second_party_type',-1)"  
 placeholder="请选择"   :templateJson="state.interfaceRes.second_party_type" :allowClear='true'  :style='{"width":"100%"}' :showSearch='false'          :options="optionsObj.second_party_typeOptions"          :fieldNames="optionsObj.second_party_typeProps"
    >
</YunzhupaasSelect>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                </tr>
                <tr
>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
    <a-col :span="24" class="ant-col-item"  >
        <a-form-item   
  name="third_party_type" >
<template #label>丙方签约类型 
</template> <YunzhupaasSelect    v-model:value="dataForm.third_party_type"  @change="changeData('third_party_type',-1)"  
 placeholder="请选择"   :templateJson="state.interfaceRes.third_party_type" :allowClear='true'  :style='{"width":"100%"}' :showSearch='false'          :options="optionsObj.third_party_typeOptions"          :fieldNames="optionsObj.third_party_typeProps"
    >
</YunzhupaasSelect>
        </a-form-item>
    </a-col>
                    </a-row>
                </td>
                <td colspan="1" rowspan="1"
>
                    <a-row :gutter="15">
                    </a-row>
                </td>
                </tr>
                </tbody>
                </table>
            </a-row>
            </a-tab-pane >
                <a-tab-pane   tab="打印模版" key="fbb4be" forceRender>
                <a-row :gutter="15">

<a-col :span="24" class="ant-col-item  mb-20px"    >
<a-form-item>
        <yunzhupaasGroupTitle  content="设计子表"  :bordered="false"
 helpMessage=""  />
<a-table :data-source="dataForm.contractPrintingTempList"  
         :columns="contractPrintingTempColumns" size="small" :pagination="false" :scroll="{ x: 'max-content' }"
         :rowSelection="getcontractPrintingTempRowSelection" rowKey="yunzhupaasId">
    <template #headerCell="{ column }">
        <span class="required-sign" v-if="column.required">*</span>
        {{ column.title }}
        <BasicHelp :text="column.tipLabel" v-if="column.tipLabel && column.title" />
    </template>
<template #bodyCell="{ column, index, record }">
    <template v-if="column.key === 'index'">{{ index + 1 }}</template>
    <template v-if="column.key ===  'printing_temp_id' ">
<YunzhupaasPopupTableSelect    v-model:value="record.printing_temp_id"  @change="changeData('contractPrintingTempprinting_temp_id',index)"  
 placeholder="请选择"   :rowIndex="index" :formData="dataForm"
 :templateJson="state.interfaceRes.contractPrintingTempprinting_temp_id" :allowClear='true'  :style='{"width":"100%"}' :showSearch='true'  :field="'printing_temp_id'+index" interfaceId="826713957526931333"
        :columnOptions="optionsObj.contractPrintingTempprinting_temp_idcolumnOptions" propsValue="f_id" relationField="f_full_name" popupType="popover"
 popupTitle="选择数据"  popupWidth="800px"       >
</YunzhupaasPopupTableSelect>
    </template>
    <template v-if="column.key ===  'is_enabled' ">
<YunzhupaasSwitch    v-model:value="record.is_enabled"  @change="changeData('contractPrintingTempis_enabled',index)"  
    >
</YunzhupaasSwitch>
    </template>
    <template v-if="column.key === 'action'">
        <a-space>
            <a-button class="action-btn" type="link" @click="copyContractPrintingTempRow(index)" size="small">                {{t('common.copyText', '复制')}} </a-button>
            <a-button class="action-btn" type="link" color="error" @click="removeContractPrintingTempRow(index,true)" size="small">                {{t('common.delText', '删除')}} </a-button>
        </a-space>
    </template>

</template>
</a-table>
    <a-space class="input-table-footer-btn"  >
        <a-button type ='primary' preIcon="icon-ym icon-ym-btn-add"
            @click="addContractPrintingTempRow"> {{t('common.add1Text','添加')}} </a-button>
        <a-button type ='danger' preIcon="icon-ym icon-ym-btn-clearn"
            @click="batchRemoveContractPrintingTempRow(true)"> {{t('common.batchDelText','批量删除')}} </a-button>
    </a-space>
</a-form-item>
</a-col>
            </a-row>
            </a-tab-pane >
            </a-tabs>
            </a-col>
                <!-- 表单结束 -->
            </a-row>
            </a-form>
        </a-row>
    </BasicModal>
</template>
<script lang="ts" setup>
    import { create, update, getInfo } from './helper/api';
    import { reactive, toRefs, nextTick, ref, unref, computed,toRaw, inject } from 'vue';
    import { BasicModal, useModal } from '@/components/Modal';
    import { yunzhupaasRelationForm } from '@/components/yunzhupaas';
    import { useMessage } from '@/hooks/web/useMessage';
    import { useI18n } from '@/hooks/web/useI18n';
    import { useUserStore } from '@/store/modules/user';
    import type { FormInstance } from 'ant-design-vue';
    import { thousandsFormat , getDateTimeUnit, getTimeUnit} from '@/utils/yunzhupaas';
    import { getDictionaryDataSelector } from '@/api/systemData/dictionary';
    import { getDataInterfaceRes } from '@/api/systemData/dataInterface';
    import dayjs from 'dayjs';
    // 表单权限
    import { usePermission } from '@/hooks/web/usePermission';
    import { cloneDeep } from 'lodash-es';
    import { buildUUID } from '@/utils/uuid';
    import { CaretRightOutlined } from '@ant-design/icons-vue';


    interface State {
dataForm:  any; 
tableRows: any; 
dataRule:  any; 
optionsObj: any; 
childIndex: any; 
isEdit: any; 
interfaceRes:  any; 
//可选范围默认值
ableAll: any; 
//掩码配置
maskConfig:any; 
//定位属性
locationScope:any; 
                        activetabformItem45e7a2:any;
    selectedcontractPrintingTempRowKeys : any; 
extraOptions: any; 
        title: string;
continueText: string;         allList: any[];
        currIndex: number;
        isContinue: boolean;
        submitType: number;
        showContinueBtn: boolean;
    }

    const emit = defineEmits(['reload']);
    const getLeftTreeActiveInfo: (() => any) | null = inject('getLeftTreeActiveInfo', null);
    const userStore = useUserStore();
    const userInfo = userStore.getUserInfo;
    const { createMessage, createConfirm } = useMessage();
    const { t } = useI18n();
    const [registerModal, { openModal, setModalProps }] = useModal();
    const formRef = ref<FormInstance>();
    const contractPrintingTempColumns: any[] = computed(() => {
        let list = [
        {
            title:  '打印模版ID' ,
            dataIndex:  'printing_temp_id' ,
            key:  'printing_temp_id' ,
            width: 350,
            labelWidth: '' ,
            span:'24',
            tipLabel:  '' ,
            required:  false,
            style: {"width":"100%"} ,
            align:  'left' ,
            fixed:  false ,
            formP:  'printing_temp_id' ,
        },
        {
            title:  '是否启用' ,
            dataIndex:  'is_enabled' ,
            key:  'is_enabled' ,
            labelWidth: '' ,
            span:'24',
            tipLabel:  '' ,
            required:  false,
            style:  '',
            align:  'left' ,
            fixed:  false ,
            formP:  'is_enabled' ,
        },
        ];
list.push({ title: t('component.table.action'), showLabel: true, dataIndex: 'action', key: 'action', align: 'center', fixed: 'right', width: 100 });        const indexColumn = { title: t('component.table.index'), showLabel: true, dataIndex: 'index', key: 'index', align: 'center', fixed: 'left', width: 50 };
        //子表复杂表头-处理
        let columnList = list;
        let complexHeaderList: any[] =  []; 
        if (complexHeaderList.length) {
            let childColumns: any[] = [];
            let firstChildColumns: string[] = [];
            for (let i = 0; i < complexHeaderList.length; i++) {
                const e = complexHeaderList[i];
                e.title = e.fullNameI18nCode ? t(e.fullNameI18nCode,e.fullName) : e.fullName;
                e.align = e.align;
                e.children = [];
                e.yunzhupaasKey = 'complexHeader';
                if (e.childColumns?.length) {
                    childColumns.push(...e.childColumns);
                    for (let k = 0; k < e.childColumns.length; k++) {
                        const item = e.childColumns[k];
                        for (let j = 0; j < list.length; j++) {
                            const o = list[j];
                            if (o.key == item && o.fixed !== 'left' && o.fixed !== 'right') e.children.push({ ...o });
                        }
                    }
                }
                if (e.children.length) firstChildColumns.push(e.children[0].key);
            }
            complexHeaderList = complexHeaderList.filter(o => o.children.length);
            let newList: any[] = [];
            for (let i = 0; i < list.length; i++) {
                const e = list[i];
                if (!childColumns.includes(e.key) || e.fixed === 'left' || e.fixed === 'right') {
                    newList.push(e);
                } else {
                    if (firstChildColumns.includes(e.key)) {
                        const item = complexHeaderList.find(o => o.childColumns.includes(e.key));
                        newList.push(item);
                    }
                }
            }
            columnList = newList;
        }
        let columns =  [indexColumn, ...columnList]
        const leftFixedList = columns.filter(o => o.fixed === 'left');
        const rightFixedList = columns.filter(o => o.fixed === 'right');
        const noFixedList = columns.filter(o => o.fixed !== 'left' && o.fixed !== 'right');
        return [...leftFixedList, ...noFixedList, ...rightFixedList];
    });

    const getcontractPrintingTempHasBatchBtn = computed(() =>{
        let flist:any[] = [{"btnIcon":"icon-ym icon-ym-btn-add","show":true,"label":"添加","btnType":"primary","value":"add","labelI18nCode":"common.add1Text"},{"btnIcon":"icon-ym icon-ym-btn-clearn","showConfirm":"true","show":true,"label":"批量删除","btnType":"danger","value":"batchRemove","labelI18nCode":"common.batchDelText"}]
        return flist?.length && flist.some(o => o.value == 'batchRemove' && !!o.show)
    });

    const getcontractPrintingTempRowSelection = computed(() => {
        if (!unref(getcontractPrintingTempHasBatchBtn )) return undefined;
        const rowSelection = {
            selectedRowKeys: state.selectedcontractPrintingTempRowKeys,
            onChange: (selectedRowKeys: string[]) => {
                state.selectedcontractPrintingTempRowKeys = selectedRowKeys;
            },
        };
        return rowSelection;
    });

    const state = reactive<State>({
dataForm: {
        contract_temp_code:undefined,
        contract_temp_name:undefined,
        remark:undefined,
        is_framework:0,
        is_detail_list:1,
        enable_tableProductList:0,
        enable_tableMaterialList:0,
        enable_tableWorktypeList:0,
        enable_tableAssetList:0,
        enable_tableTaskList:0,
        contract_type:'',
        enable_printing:1,
        our_company_type:'PartA',
        second_party_type:'PartB',
        third_party_type:'PartC',
    contractPrintingTempList:[],
},

tableRows:{
        contractPrintingTempList:{
                    printing_temp_id : '',
                    is_enabled : 0,
    enabledmark:undefined
    },
},

dataRule: {
},

optionsObj:{
                contract_typeOptions:[{"fullName":"收入合同","id":"REV"},{"fullName":"支出合同","id":"COS"}],
            contract_typeProps:{"label":"fullName","value":"id"  },
                our_company_typeOptions:[{"fullName":"甲方","id":"PartA"},{"fullName":"乙方","id":"PartB"},{"fullName":"丙方","id":"PartC"}],
            our_company_typeProps:{"label":"fullName","value":"id"  },
                second_party_typeOptions:[{"fullName":"甲方","id":"PartA"},{"fullName":"乙方","id":"PartB"},{"fullName":"丙方","id":"PartC"}],
            second_party_typeProps:{"label":"fullName","value":"id"  },
                third_party_typeOptions:[{"fullName":"甲方","id":"PartA"},{"fullName":"乙方","id":"PartB"},{"fullName":"丙方","id":"PartC"}],
            third_party_typeProps:{"label":"fullName","value":"id"  },
                contractPrintingTempprinting_temp_idcolumnOptions:[ {"label":"打印模版名称","value":"f_full_name"}, {"label":"打印模版描述","value":"f_description"},],
},

childIndex: -1, 
isEdit: false, 
interfaceRes:  {"enable_tableAssetList":[],"is_framework":[],"enable_tableMaterialList":[],"enable_printing":[],"our_company_type":[],"third_party_type":[],"remark":[],"contractPrintingTempprinting_temp_id":[],"enable_tableWorktypeList":[],"contract_type":[],"enable_tableTaskList":[],"contractPrintingTempis_enabled":[],"contract_temp_code":[],"enable_tableProductList":[],"is_detail_list":[],"second_party_type":[],"contract_temp_name":[]}, 
//可选范围默认值
ableAll:{
},

//掩码配置
maskConfig:{
            contract_temp_code: {"prefixType":1,"useUnrealMask":false,"maskType":1,"unrealMaskLength":1,"prefixLimit":0,"suffixLimit":0,"filler":"*","prefixSpecifyChar":"","suffixType":1,"ignoreChar":"","suffixSpecifyChar":""} ,
            contract_temp_name: {"prefixType":1,"useUnrealMask":false,"maskType":1,"unrealMaskLength":1,"prefixLimit":0,"suffixLimit":0,"filler":"*","prefixSpecifyChar":"","suffixType":1,"ignoreChar":"","suffixSpecifyChar":""} ,
},

//定位属性
locationScope:{
},

                        activetabformItem45e7a2:'fbb4be',
    selectedcontractPrintingTempRowKeys : [], 
extraOptions:{
},

        title: "",
 continueText: "",         allList: [],
        currIndex: 0,
        isContinue: false,
        submitType: 0,
        showContinueBtn:  true ,
    });
    const { title,  continueText,  showContinueBtn, dataRule, dataForm, optionsObj, ableAll, maskConfig,submitType } = toRefs(state);

    const getPrevDisabled = computed(() => state.currIndex === 0);
    const getNextDisabled = computed(() => state.currIndex === state.allList.length - 1);
    // 表单权限
    const { hasFormP } = usePermission();

    defineExpose({ init });

    function init(data) {
        state.submitType = 0;
        state.isContinue = false;
        state.title = !data.id ? t('common.add2Text','新增') : t('common.editText','编辑');
 state.continueText = !data.id ? t('common.continueAndAddText','确定并新增') : t('common.continueText','确定并继续');         setFormProps({ continueLoading: false });
        state.dataForm.id = data.id;
        openModal();
        state.allList = data.allList;
        state.currIndex = state.allList.length && data.id ? state.allList.findIndex((item) => item.id === data.id) : 0;
        nextTick(() => {
            getForm().resetFields();
            state.dataForm.contractPrintingTempList = [];
            setTimeout(initData, 0);
        });
    }
    function initData() {
        changeLoading(true);
            state.activetabformItem45e7a2='fbb4be';
        if (state.dataForm.id) {
            getData(state.dataForm.id);
        } else {
            //初始化options

    if (state.dataForm.contractPrintingTempList) {
        for (let i = 0; i < state.dataForm.contractPrintingTempList.length; i++) {
            state.childIndex = i;
            state.dataForm.contractPrintingTempList[i].yunzhupaasId = buildUUID();

        }
    }
            // 设置默认值
            state.dataForm={
        contract_temp_code:undefined,
        contract_temp_name:undefined,
        remark:undefined,
        is_framework:0,
        is_detail_list:1,
        enable_tableProductList:0,
        enable_tableMaterialList:0,
        enable_tableWorktypeList:0,
        enable_tableAssetList:0,
        enable_tableTaskList:0,
        contract_type:'',
        enable_printing:1,
        our_company_type:'PartA',
        second_party_type:'PartB',
        third_party_type:'PartC',
    contractPrintingTempList:[],
            };
            if (getLeftTreeActiveInfo) state.dataForm = {...state.dataForm, ...(getLeftTreeActiveInfo() || {}) };
            state.childIndex = -1;
            changeLoading(false);
        }
    }
    function getForm() {
        const form = unref(formRef);
        if (!form) {
            throw new Error('form is null!');
        }
        return form;
    }
    function getData(id) {
        getInfo(id).then((res) => {
            state.dataForm = res.data || {};

    if (state.dataForm.contractPrintingTempList) {
        for (let i = 0; i < state.dataForm.contractPrintingTempList.length; i++) {
            state.childIndex = i;
            state.dataForm.contractPrintingTempList[i].yunzhupaasId = buildUUID();

        }
    }
            state.childIndex = -1;
            changeLoading(false);
        });
    }
    async function handleSubmit(type) {
        try {
            const values = await getForm()?.validate();
            if (!values) return;
            if(!contractPrintingTempExist()) return;


             setFormProps({ confirmLoading: true });
            const formMethod = state.dataForm.id ? update : create;
            formMethod(state.dataForm)
                    .then((res) => {
                        createMessage.success(res.msg);
                        setFormProps({ confirmLoading: false });
                        if (state.submitType == 1) {
                            initData();
                            state.isContinue = true;
                        } else {
                            setFormProps({ open: false });
                            emit('reload');
                        }
                    })
                    .catch(() => {
                        setFormProps({ confirmLoading: false });
                    });
        } catch (_) {}
    }
    function handlePrev() {
        state.currIndex--;
        handleGetNewInfo();
    }
    function handleNext() {
        state.currIndex++;
        handleGetNewInfo();
    }
    function handleGetNewInfo() {
        changeLoading(true);
        getForm().resetFields();
        const id = state.allList[state.currIndex].id;
        getData(id);
    }
    function setFormProps(data) {
        setModalProps(data);
    }
    function changeLoading(loading) {
        setModalProps({ loading });
    }
    async function onClose() {
        if (state.isContinue) emit('reload');
        return true;
    }

        function changeData(model, index) {
    state.isEdit = false
    state.childIndex = index
    for (let key in state.interfaceRes) {
        if (key != model) {
            let faceReList = state.interfaceRes[key]
            for (let i = 0; i < faceReList.length; i++) {
                let relationField = faceReList[i].relationField;
                if(relationField){
                    let modelAll = relationField.split('-');
                    let faceMode = '';
                    let faceMode2 = modelAll.length == 2?modelAll[0].substring(0, modelAll[0].length-4) +modelAll[1]:""
                    for (let i = 0; i < modelAll.length; i++) {
                        faceMode += modelAll[i];
                    }
                    if (faceMode == model || faceMode2 == model ) {
                        let options = 'get' + key + 'Options';
                        eval(options)(true);
                        changeData(key, index)
                    }
                }
            }
        }
    }
}
function changeDataFormData(type, data, model,index,defaultValue) {
    if(!state.isEdit) {
        if (type == 2) {
            for (let i = 0; i < state.dataForm[data].length; i++) {
                if (index == -1) {
                    state.dataForm[data][i][model] = defaultValue
                } else if (index == i) {
                    state.dataForm[data][i][model] = defaultValue
                }
            }
        } else {
            state.dataForm[data] = defaultValue
        }
    }
}
        function addContractPrintingTempRow(){
        let item = {
        printing_temp_id:'',
        is_enabled:0,
            yunzhupaasId: buildUUID(),
        }
        state.dataForm.contractPrintingTempList.push(item)
        state.childIndex=state.dataForm.contractPrintingTempList.length-1
        state.childIndex = -1
    }

    function removeContractPrintingTempRow(index,showConfirm=false){
        if(showConfirm){
            createConfirm({
                iconType: 'warning',
                title: '提示',
                content: '此操作将永久删除该数据, 是否继续?',
                onOk: () => {
                    state.dataForm.contractPrintingTempList.splice(index, 1);
                },
            });
        }else{
            state.dataForm.contractPrintingTempList.splice(index, 1);
        }
    }

    function copyContractPrintingTempRow(index){
        let item = cloneDeep(state.dataForm.contractPrintingTempList[index]);
        let copyData = {};
        for (let i = 0; i < unref(contractPrintingTempColumns).length; i++) {
            const cur = unref(contractPrintingTempColumns)[i];
            if (cur.key != 'index' && cur.key != 'action') {
                if (cur.children?.length && cur.yunzhupaasKey == 'complexHeader') {
                    for (let j = 0; j < cur.children.length; j++) {
                        copyData[cur.children[j].key] = item[cur.children[j].key];
                    }
                } else {
                    copyData[cur.key] = item[cur.key];
                }
            }
        }
        const copyItem = { ...copyData, yunzhupaasId: buildUUID() };
        state.dataForm.contractPrintingTempList.push(copyItem);
        state.childIndex=state.dataForm.contractPrintingTempList.length-1
        state.childIndex = -1
    }

    function batchRemoveContractPrintingTempRow(showConfirm=false){
        if (!state.selectedcontractPrintingTempRowKeys.length) return createMessage.error('请选择一条数据');
        const handleRemove = ()=>{
            state.dataForm.contractPrintingTempList = state.dataForm.contractPrintingTempList.filter(
                o => !state.selectedcontractPrintingTempRowKeys.includes(o.yunzhupaasId),
            );
            nextTick(() => {
                state.selectedcontractPrintingTempRowKeys = [];
            });
         }
        if(showConfirm){
            createConfirm({
                iconType: 'warning',
                title: '提示',
                content: '此操作将永久删除该数据, 是否继续?',
                onOk: ()=>{
                    handleRemove()
                },
            });
        }else{
            handleRemove()
        }
    }

    function contractPrintingTempExist(){
        let isOk = true;
        for(let i=0;i<state.dataForm.contractPrintingTempList.length;i++){
            const e = state.dataForm.contractPrintingTempList[i];
        }
        return isOk;
    }

        function getcontractPrintingTempprinting_temp_idOptions() {
        const index = state.childIndex
       changeDataFormData(2,'contractPrintingTempList','contractPrintingTempprinting_temp_id',index,'')
    }
function getRelationDate(timeRule, timeType, timeTarget, timeValueData, dataValue) {
    let timeDataValue: any = null;
    let timeValue = Number(timeValueData);
    if (timeRule) {
        if (timeType == 1) {
            timeDataValue = timeValue;
        } else if (timeType == 2) {
            timeDataValue = dataValue;
        } else if (timeType == 3) {
            timeDataValue = new Date().getTime();
        } else if (timeType == 4 || timeType == 5) {
            const type = getTimeUnit(timeTarget);
            const method = timeType == 4 ? 'subtract' : 'add';
            timeDataValue = dayjs()[method](timeValue, type).valueOf();
        }
    }
    return timeDataValue;
}
function getRelationTime(timeRule, timeType, timeTarget, timeValue, formatType, dataValue) {
    let format = formatType == 'HH:mm' ? 'HH:mm:00' : formatType;
    let timeDataValue: any = null;
    if (timeRule) {
        if (timeType == 1) {
            timeDataValue = timeValue || '00:00:00';
            if (timeDataValue.split(':').length == 3) {
                timeDataValue = timeDataValue;
            } else {
                timeDataValue = timeDataValue + ':00';
            }
        } else if (timeType == 2) {
            timeDataValue = dataValue;
        } else if (timeType == 3) {
            timeDataValue = dayjs().format(format);
        } else if (timeType == 4 || timeType == 5) {
            const type = getTimeUnit(timeTarget + 3);
            const method = timeType == 4 ? 'subtract' : 'add';
            timeDataValue = dayjs()[method](timeValue, type).format(format);
        }
    }
    return timeDataValue;
}
</script>
