<template>
  <a-spin :spinning="spinning" tip="加载中...">
    <div class="page-bg-wrap formViewStyle">
      <a-form ref="formRef" :model="formState" :rules="rules" v-bind="layout">
        <Card title="合同档案" :bordered="false" >
          <a-row>
            <a-col :span="8">
              <a-form-item label="合同号" name="kNo">
                <a-input v-model:value="formState.kNo" :disabled="isDisable" style="width: 65%" /><a-button  v-if="!isDisable" type="primary" @click="onContract">关联合同</a-button>
              </a-form-item>
            </a-col>
            <a-col :span="16">
              <a-form-item label="合同名称" name="kName" :label-col="{ span: 4 }" :wrapper-col="{ span: 24 }">
                <a-input v-model:value="formState.kName" placeholder="请输入合同名称" :disabled="isDisable"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="合同期限" name="kPeriod">
                <a-select v-model:value="formState.kPeriod" :disabled="isDisable" placeholder="请选择合同期限" @change="kPeriodChange" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.kPeriodList" :key="item.code" :value="item.code">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col> 
            <a-col :span="8">
              <a-form-item label="有效期开始" name="dateFrom">
                <a-date-picker v-model:value="formState.dateFrom" style="width: 100%" @change="dateChange(formState.dateFrom, 'dateFrom')" :disabled="isDisable" :disabled-date="disabledDateStart" placeholder="请选择开始日期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="有效期结束" name="dateTo">
                <a-date-picker v-model:value="formState.dateTo" style="width: 100%" @change="dateChange(formState.dateTo, 'dateTo')" :disabled="isDisable" :disabled-date="disabledDateEnd" placeholder="请选择结束日期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="合同签订日期" name="dateSign">
                <a-date-picker v-model:value="formState.dateSign" style="width: 100%" :disabled="isDisable" placeholder="请选择合同签订日期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="币种" name="curCode">
                <a-select v-model:value="formState.curCode" :disabled="isDisable" placeholder="请选择币种" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.curCodeList" :key="item.code" :value="item.code">
                    {{ item.fullName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="状态" name="approCode">
                <a-select v-model:value="formState.approCode" disabled style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.approCodeList" :key="item.code" :value="item.code">
                      {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="供应商" name="cpName">
                <a-input-search v-model:value="formState.cpName" :disabled="isDisable" placeholder="请选择供应商"  readonly @search="onSearchSupplier"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="业务人员" name="empName">
                <a-input-search v-model:value="formState.empName" :disabled="isDisable" placeholder="请选择业务联系人"  readonly @search="onSearchUser"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="业务部门" name="bDeptName">
                <a-input v-model:value="formState.bDeptName" disabled/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="合同主体" name="comName">
                <a-input v-model:value="formState.comName" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="备注" name="note" :label-col="{ span: 3 }" :wrapper-col="{ span: 24 }">
                <a-textarea  v-model:value="formState.note" :disabled="isDisable"  placeholder="请输入备注"  :auto-size="{ minRows: 2, maxRows: 5 }"/>
              </a-form-item>
            </a-col>
          </a-row>
        </Card>
        <Card title="业务信息" :bordered="false" >
           <div v-for="(item, idx) in dataListPrice" class="tbStyle">
            <div class="tb-box">
              <h4>上下载点</h4>
              <a-button type="primary" style="margin: 0 10px" @click="handleAdd" v-if="!isDisable">新增</a-button>
              <a-button type="primary" @click="handleDelete(idx)" v-if="!isDisable">删除</a-button>
            </div>
            <a-row>
              <a-col :span="8">
                <a-form-item name="pointUpName">
                  <template #label>
                    <span><span style="color:red">*</span>上载点</span>
                  </template>
                 <a-input-search v-model:value="item.pointUpName" :disabled="isDisable" placeholder="请选择上载点"  readonly @search="onSearchDownLoad('up', idx)"/>
                </a-form-item>
              </a-col>
               <a-col :span="8">
                <a-form-item name="pointDelyName">
                  <template #label>
                    <span><span style="color:red">*</span>下载点</span>
                  </template>
                  <a-input-search v-model:value="item.pointDelyName" :disabled="isDisable" placeholder="请选择下载点"  readonly @search="onSearchDownLoad('dely', idx)"/>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="备注" name="note" :label-col="{ span: 3 }" :wrapper-col="{ span: 24 }">
                  <a-textarea  v-model:value="item.note" :disabled="isDisable"  placeholder="请输入备注"  :auto-size="{ minRows: 2, maxRows: 5 }"/>
                </a-form-item>
              </a-col>
            </a-row>
            <div v-for="(k, idxk) in item.lngPriceTransPngList" class="tbStyle">
              <div class="tb-box">
                <h4>管输价格</h4>
                <a-button type="primary" style="margin: 0 10px" @click="addPrice(idx)" v-if="!isDisable">新增</a-button>
                <a-button type="primary" @click="deletePrice(idx, idxk)" v-if="!isDisable">删除</a-button>
              </div>
              
              <a-row>
                <a-col :span="8">
                  <a-form-item name="dateFromNew">
                    <template #label>
                      <span><span style="color:red">*</span>有效期开始</span>
                    </template>
                    <a-date-picker v-model:value="k.dateFromNew" format="YYYY-MM-DD" :value-format="'YYYY-MM-DD'"  @openChange="dateToYCheck(idx,idxk)" @change="dateFromNewChange" style="width: 100%" :disabled="isDisable" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item name="dateToCode">
                    <template #label>
                      <span><span style="color:red">*</span>结束日类型</span>
                    </template>
                    <a-select v-model:value="k.dateToCode" @change="dateToCodeChange(idx,idxk, k.dateToCode)" :disabled="isDisable" style="width: 100%" allow-clear>
                      <a-select-option v-for="item in optionSelect.dateToCodeList" :key="item.code" :value="item.code">
                          {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8" v-if="k.dateToCode=='F'">
                  <a-form-item name="dateToF">
                    <template #label>
                      <span><span style="color:red">*</span>固定结束日</span>
                    </template>
                    <a-date-picker v-model:value="k.dateToF" format="YYYY-MM-DD" :value-format="'YYYY-MM-DD'"  style="width: 100%" :disabled="isDisable" />
                  </a-form-item>
                </a-col>
                <a-col :span="8" v-if="k.dateToCode=='Y'">
                  <a-form-item name="dateToY">
                    <template #label>
                      <span><span style="color:red">*</span>每年结束日</span>
                    </template>
                    <a-date-picker v-model:value="k.dateToY" format="MM-DD" :value-format="'MM-DD'" style="width: 100%" :disabled="isDisable" @openChange="dateToYCheck(idx,idxk)"  :disabledDate="disabledCurrentYear"/>
                  </a-form-item>
                </a-col>
                <div style="width: 100%">
                  <a-button type="primary" style="margin-bottom: 10px" @click="addTable(idx, idxk)" v-if="!isDisable">新增行</a-button>
                  <a-table style="width: 100%" :columns="columnsPrice" :data-source="k.lngPriceTransPngDtlList" :pagination="false">
                    <template #headerCell="{ column }">
                      <template v-if="column.dataIndex == 'sortDesc'">
                        <span><span class="redStyle">*</span>约定</span>
                      </template>
                      <template v-if="column.dataIndex == 'priceTransM3'">
                        <span><span class="redStyle">*</span>管输单价(元/方)</span>
                      </template>
                      <template v-if="column.dataIndex == 'qtyM3'">
                        <span><span class="redStyle">*</span>阶梯内气量(方)</span>
                      </template>
                    </template>
                    <template #bodyCell="{ column, record, index }">
                      <template v-if="column.dataIndex === 'sortDesc'">
                        <a-input v-model:value="record.sortDesc" :disabled="isDisable" />
                      </template>
                      <template v-if="column.dataIndex === 'qtyM3'">
                        <input-number v-model:value="record.qtyM3" :disabled="isDisable" :min="0" :digits="3" @change="numCount(record)" style="width: 100%"/>
                      </template>
                      <template v-if="column.dataIndex === 'priceTransM3'">
                        <input-number v-model:value="record.priceTransM3" :disabled="isDisable" :min="0" :digits="4" @change="numCount(record)" style="width: 100%"/>
                      </template>
                      <template v-if="column.dataIndex === 'note'">
                        <a-input v-model:value="record.note" :disabled="isDisable" />
                      </template>
                      <template v-if="column.dataIndex === 'operation'">
                        <a v-if="!isDisable" @click="deleteTable(idx,idxk,index)">删除</a>
                      </template>
                    </template>
                  </a-table>
                </div>
              </a-row>
            </div>
          </div>
        </Card>
        <Card title="附件信息" :bordered="false" >
          <UploadList :disabled="isDisable" :list="dataFile" :value="formState.filePath" :tableName="tableName" :columnName="columnName" @change="uploadListChange"/>
        </Card>
        <Card title="关联合同信息" :bordered="false" >
          <correlationContractFactList :list="dataListContractFact" :disabled="isDisable" @change="getApproContractFactList"></correlationContractFactList>
        </Card>
        <Card title="签报列表" :bordered="false" >
          <correlationApproList :list="dataListAppro" :disabled="isDisable" @change="getApproList"></correlationApproList>
        </Card>
      </a-form>
    </div>
    <deptUserModal @register="register" @success="handleSuccess"/>
    <contractFactListModal @register="registerContractFact" @success="handleSuccessContractFact" />
    <downloadPointModal @register="registerDownLoad" @success="handleSuccessDownLoad"/>
    <supplierListModal @register="registerSupplier" @success="handleSuccessSupplier" selectType="radio" />
  </a-spin>
</template>

<script lang="ts" setup>
    import { Card } from 'ant-design-vue';
    import { useRouter } from 'vue-router';
    import { FromPageType, RecordType } from '/@/enums/workflowEnum';
    import { ref, computed, onMounted, onBeforeMount, nextTick, defineAsyncComponent, reactive, defineComponent, watch} from 'vue';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { useI18n } from '/@/hooks/web/useI18n';
    import { useMultipleTabStore } from '/@/store/modules/multipleTab';
    import useEventBus from '/@/hooks/event/useEventBus';
    import type { Rule } from 'ant-design-vue/es/form';
    import { getDictionary } from '/@/api/sales/Customer';
    import { useModal } from '/@/components/Modal';
    import { addLngContract,updateLngContract, getLngContract } from '/@/api/contract/ContractTransPng';
    import { getLngContractFact } from '/@/api/contract/ContractFact';
    import { getLngAppro,getCompDept } from '/@/api/approve/Appro';
    import dayjs from 'dayjs';
    import { h } from 'vue';
    import { SearchOutlined } from '@ant-design/icons-vue';
    import { getAppEnvConfig } from '/@/utils/env';
    import { message } from 'ant-design-vue';
    import UploadList from '/@/components/Form/src/components/UploadList.vue';
    import deptUserModal from '/@/components/common/deptUserModal.vue';
    import deptListModal from '/@/components/common/deptListModal.vue';
    import correlationApproList from '/@/components/common/correlationApproList.vue';
    import correlationContractFactList from '/@/components/common/correlationContractFactList.vue';
    import contractFactListModal from '/@/components/common/contractFactListModal.vue';
    import downloadPointModal from '/@/components/common/downloadPointModal.vue';
    import supplierListModal from '/@/components/common/supplierListModal.vue';
    import { getAllCurrency } from '/@/api/contract/ContractFact';
    import { useUserStore } from '/@/store/modules/user';
    import { getParameter } from '/@/api/contract/ContractProc';
    import { DataFormat, FormatOption, DATE_FORMAT, FormatType } from '/@/utils/dataFormat';

    const userStore = useUserStore();
    const userInfo = userStore.getUserInfo;

    const tableName = 'ContractTransPng';
    const columnName = 'ContractTransPng'

    const formType = ref('2'); // 0 新建 1 修改 2 查看
    const formRef = ref();
    const props = defineProps({
      disabled: false,
      id: ''
    
    });
    const { bus, FORM_LIST_MODIFIED } = useEventBus();

    const router = useRouter();
    const { currentRoute } = router;
    const isDisable = ref(false);
    const { formPath } = currentRoute.value.query;
    const pathArr = [];

    const tabStore = useMultipleTabStore();
    const formProps = ref(null);
    const formId = ref(currentRoute.value?.params?.id);
    const pageType = ref(currentRoute.value.query?.type);
    const pageId = ref(currentRoute.value.query?.id)
    const spinning = ref(false);
    const curIdx = ref(null)
    const curIdxk = ref(null)
    const rateCode = ref()
    const { notification } = useMessage();
    const { t } = useI18n();
    const formState = reactive({
      approCode: 'WTJ',
      typeCode: 'TP',
      onlineSign: 'N',
      cpTableName: 'lng_supplier',
      curCode: 'CNY',
    });
    const [register, { openModal:openModal}] = useModal();
    const [registerContractFact, { openModal:openModalContractFact}] = useModal();
    const [registerDownLoad, { openModal:openModalDownLoad}] = useModal();
    const [registerSupplier, { openModal:openModalSupplier}] = useModal();
    const rules= reactive({
      kNo: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      kName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      cpName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      uomCode: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      empName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      bDeptName: [{ required: false, message: "该项为必填项", trigger: 'change' }],
      dateTo:[{ required: true, message: "该项为必填项", trigger: 'change' }],
      dateFrom:[{ required: true, message: "该项为必填项", trigger: 'change' }]
    });
    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    }
    const dataFile = ref([]);
    const dataListAppro = ref([])
    const dataListContractFact = ref([])
    let optionSelect= reactive({
      approCodeList: [],
      kPeriodList: [],
      curCodeList: [],
      dateToCodeList: []
    });
    const dataListPrice = ref([
      {
        lngPriceTransPngList: [
          {
            dateToCode: '',
            dateFrom: null,
            lngPriceTransPngDtlList: []
          }
        ]  
      }
    ])
    const columnsPrice= ref([
      // { title: t('序号'), dataIndex: 'index', key: 'index',  customRender: (column) => `${column.index + 1}` ,width: 100},
      { title: t('阶梯'), dataIndex: 'sort',width:80},
      { title: t('约定'), dataIndex: 'sortDesc'},
      { title: t('阶梯内气量(方)'), dataIndex: 'qtyM3', width: 150},
      { title: t('管输单价(元/方)'), dataIndex: 'priceTransM3', width: 150},
      { title: t('备注'), dataIndex: 'note'},
      { title: t('操作'), dataIndex: 'operation', width: 80, fixed: 'right',align: 'center'},
    ]);
    watch(
      () => props.id,
      (val) => {
        if (val) {
          getInfo(val)
        }  
      },
      {
        immediate: true
      }
    );
    watch(
      () => props.disabled,
      (val) => {
        isDisable.value = val
        if (val) {
          let idx1 = columnsPrice.value.findIndex(v=>v.dataIndex == 'operation')
          idx1>-1&&columnsPrice.value.splice(idx1, 1)
        }
        
      },
      {
        immediate: true
      }
    );
    onMounted(async() => {
      getOption()
      if (pageId.value) {
        getInfo(pageId.value)
      } else {
        formState.empName = userInfo.name
        formState.empId = userInfo.id
        formState.tel = userInfo.mobile
        getOptionParams()
      }
      let a = await getParameter({code: 'RATE_TON_GJ'})||[]
      rateCode.value = a[0]?.valueNum1
    });
      const dateToCodeChange = (idx, idxk, val) => {
      if (val == 'F') {
        dataListPrice.value[idx].lngPriceTransPngList[idxk].dateToY = null
      } else {
        dataListPrice.value[idx].lngPriceTransPngList[idxk].dateToF = null
      }
    }
    const dateFromNewChange = (val) => {
      if (val) {
        dataListPrice.value[curIdx.value].lngPriceTransPngList[curIdxk.value].dateFrom = dayjs(val).format('YYYY-MM-DD')
        dataListPrice.value[curIdx.value].lngPriceTransPngList[curIdxk.value].dateToY = null
      }
    }
    const dateToYCheck = (idx, idxK) => {
      curIdx.value = idx
      curIdxk.value = idxK
    }
    const disabledCurrentYear = (current) => {
      let date = new Date().getFullYear()
      if (dataListPrice.value[curIdx.value].lngPriceTransPngList[curIdxk.value].dateFromNew) {
        date = new Date(dataListPrice.value[curIdx.value].lngPriceTransPngList[curIdxk.value].dateFromNew).getFullYear()
      }
      return current && new Date(current).getFullYear() !== date;
    };
    const kPeriodChange = (val) => {
      if (val !== 'Y') {
        formState.dateFrom = dayjs('2000-01-01')
        formState.dateTo = dayjs('2999-12-31')
      }
    }
    const uploadListChange = (val) => {
      dataFile.value = val
    }
    async function getInfo(id)  {
      spinning.value = true
      try {
      let data = await getLngContract(id)
      spinning.value = false
      Object.assign(formState, {...data})
      Object.assign(dataFile.value, formState.lngFileUploadList || [])
      Object.assign(dataListContractFact.value, formState.lngContractFactList || [])
      Object.assign(dataListAppro.value, formState.lngApproVoList || [])
      Object.assign(dataListPrice.value, formState.lngContractTransPngList || [])
      formState.dateSign = formState.dateSign ? dayjs(formState.dateSign) : null
      formState.dateFrom = formState.dateFrom ? dayjs(formState.dateFrom) : null
      formState.dateTo = formState.dateTo ? dayjs(formState.dateTo) : null
      getOptionParams()
      dataListPrice.value.forEach(v =>{
        v.lngPriceTransPngList.forEach(k => {
          k.dateFromNew = k.dateFrom ?  dayjs(k.dateFrom) : null
          k.dateToF = k.dateToF ?  dayjs(k.dateToF) : null
          k.dateToY = k.dateToY ?  dayjs(k.dateToY) : null
          k.lngPriceTransPngDtlList = k.lngPriceTransPngDtlList || []
          if (isDisable.value) {
            k.lngPriceTransPngDtlList =DataFormat.format(k.lngPriceTransPngDtlList, [
            FormatOption.createQty('qtyM3'),
            FormatOption.createQty('priceTransM3'),
          ]);
          }
        })
      })
      dataListAppro.value.forEach(v => {
        // v.approId = v.id
      })
      dataListContractFact.value.forEach(v => {
        v.kFactId = v.id
      })
      } catch (error) {
        spinning.value = false
      }
    }
    async function getOption() {
      optionSelect.kPeriodList = await getDictionary('LNG_K_PER')
      optionSelect.approCodeList = await getDictionary('LNG_APPRO')
      optionSelect.dateToCodeList = await getDictionary('LNG_D_TO')

      if (!pageId.value) {
        getCompDeptInfo(userInfo.id)
      }

    }
    async function getOptionParams() {
      optionSelect.curCodeList = await getAllCurrency({eid: formState.curCode})
    }
    const getCompDeptInfo = async (id, deptId)=> {
      const res = await getCompDept(id, deptId)
      formState.bDeptName = res?.dept?.name
      formState.bDeptId = res?.dept?.id

      if (!pageId.value) {
        formState.comName = res?.comp?.name
        formState.comId = res?.comp?.id
      }
    }
    const getApproList = (val) => {
      dataListAppro.value = val
    }
    const getApproContractFactList = (val) => {
      dataListContractFact.value = val
    }
    const dateChange = (val, k) => {
      if (!val) {
        if (k=='dateFrom') {
          formState.dateFrom = dayjs(new Date())
          setTimeout(() => {
            formState.dateFrom = null
          }, );
        }
        if (k=='dateTo') {
          formState.dateTo = dayjs(new Date())
          setTimeout(() => {
            formState.dateTo = null
          }, );
        }
      }
    }
    const disabledDateStart = (startValue) => {
      const endValue = formState?.dateTo;
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf();
    }
    const disabledDateEnd = (endValue) => {
      const startValue = formState?.dateFrom;
      if (!endValue || !startValue) {
        return false
      }
      return endValue.valueOf() <= startValue.valueOf();
    }

    const onSearchSupplier = () => {
      openModalSupplier(true,{isUpdate: false})
    }
    const onSearchUser = (val)=> {
      openModal(true,{isUpdate: false})
    }
    const onContract = (val)=> {
      openModalContractFact(true,{isUpdate: false})
    }
    const onSearchDownLoad = (val, index)=> {
      curIdx.value = index
      nextTick(() => {
        openModalDownLoad(true,{isUpdate: false, type: val})
      });
    }
    const addTable= (idx,idxk) => {
      dataListPrice.value[idx].lngPriceTransPngList[idxk].lngPriceTransPngDtlList.push({
        sortDesc:null,priceTransM3:null,
        sort:dataListPrice.value[idx].lngPriceTransPngList[idxk].lngPriceTransPngDtlList.length+1
      })
    }
    const deleteTable= (idx,idxk,index) => {
      dataListPrice.value[idx].lngPriceTransPngList[idxk].lngPriceTransPngDtlList.splice(index, 1)
    }
    const numCount = (record)=> {
      record.qtyGj = Number(record.qtyM3)*Number(rateCode.value)
      record.priceTransGj = Number(record.priceTransM3)*Number(rateCode.value)
      record.qtyGj = record.qtyGj ? record.qtyGj.toFixed(3): ''
      record.priceTransGj = record.priceTransGj ? record.priceTransGj.toFixed(4): ''
    }
    const addPrice = (idx) => {
      dataListPrice.value[idx].lngPriceTransPngList.push({
        lngPriceTransPngDtlList:[]
      })
    }
    const deletePrice= (idx, index) => {
      if (dataListPrice.value[idx].lngPriceTransPngList.length ==1)return
      dataListPrice.value[idx].lngPriceTransPngList.splice(index, 1)
    }
    const handleAdd = ()=> {
      dataListPrice.value.push({
        lngPriceTransPngList: [
          {lngPriceTransPngDtlList: []}
        ]  
      })
    }
    const handleDelete= (index) => {
      if (dataListPrice.value.length ==1)return
      dataListPrice.value.splice(index, 1)
       
    }
    
    const handleSuccess = (val, deptId) => {
      formState.empName = val[0].name
      formState.empId = val[0].id
      formState.tel = val[0].mobile
      getCompDeptInfo(formState.empId, deptId)
    }
    const handleSuccessSupplier = (val) => {
      formState.cpCode = val[0].suCode
      formState.cpName = val[0].suName
    }
    const handleSuccessContractFact = (val) => {
      val.forEach((v, idx) => {
        v.kFactId = v.id
        v.sort = idx
        v.id = null
      })
      if (!dataListContractFact.value.length) {
        dataListContractFact.value = val
        getContractFact()
        return
      }
      let arr = []
      val.forEach(v => {
        dataListContractFact.value.forEach(i => {
          if (v.kNo == i.kNo){
            message.warning(v.kNo + '已重复, 合同不需要重复选择')
          } else {
            arr.push(v)
          }
        })
      })
      dataListContractFact.value = unique([...dataListContractFact.value, ...arr], 'kNo')
      setTimeout(() => {
        getContractFact()
      });
    }
   const getContractFact = async () => {
      let a = []
      dataListContractFact.value.forEach(v=>{
        if (v.relTypeCode == 'M') {
          a.push(v)
        } 
      })
      if(a.length == 1) {
        spinning.value = true
        try {
        const res = await getLngContractFact(a[0].kFactId)
        spinning.value = false
        formState.kNo = formState.kNo ? formState.kNo : res?.kNo
        formState.kName = formState.kName ? formState.kName : res?.kName
        formState.kPeriod = formState.kPeriod ? formState.kPeriod : res?.periodTypeCode
        formState.curCode = formState.curCode ? formState.curCode : res?.curCode
        formState.dateFrom = formState.dateFrom ? formState.dateFrom : (res?.dateFrom ? dayjs(res?.dateFrom) : null)
        formState.dateTo = formState.dateTo ? formState.dateTo : (res?.dateTo ? dayjs(res?.dateTo) : null)
        let arr = res?.lngContractFactCpList || []
        let arrSales = []
        let arrSupplier = []
        arr.forEach(v=> {
          if (v.cpTableName == 'lng_customer') {
            arrSales.push(v)
          }
          if (v.cpTableName == 'lng_supplier') {
            arrSupplier.push(v)
          }
        })
        formState.cpName = formState.cpName ? formState.cpName : arrSupplier[0]?.cpName
        formState.cpCode = formState.cpCode ? formState.cpCode : arrSupplier[0]?.cpCode

        } catch (error) {
          spinning.value = false
        } 
      }
    }
    const handleSuccessDownLoad = (val, type) => {
      if (type == 'up') {
        dataListPrice.value[curIdx.value].pointUpCode = val[0].code
        dataListPrice.value[curIdx.value].pointUpName = val[0].fullName
      } else {
        dataListPrice.value[curIdx.value].pointDelyName = val[0].fullName
        dataListPrice.value[curIdx.value].pointDelyCode = val[0].code
      
      }
    }
    
    function unique(arr, u_key) {
      const map = new Map()
      arr.forEach((item, index) => {
        if (!map.has(item[u_key])) {
          map.set(item[u_key], item)
        }
      })
      return [...map.values()]
    }
    function close() {
      tabStore.closeTab(currentRoute.value, router);
    }
    async function getFormValue() {
      return formState
    }
    async function handleSubmit(type) {
      try {
        await formRef.value.validateFields();
        for(let i=0; i<dataListPrice.value.length; i++) {
          let isFlag = !dataListPrice.value[i].pointUpCode || !dataListPrice.value[i].pointDelyCode
          if (isFlag) {
            message.warn('请完善业务信息上下载点必选项')
            return
          }
          for(let k=0; k<dataListPrice.value[i].lngPriceTransPngList.length; k++) {
            let a = dataListPrice.value[i].lngPriceTransPngList[k]
            let flag = !a.dateFrom || !a.dateToCode || (a.dateToCode=='F'&&!a.dateToF) || (a.dateToCode=='Y'&&!a.dateToY)
            if (flag) {
              message.warn('请完善管输价格必选项')
              return
            }
            dataListPrice.value[i].lngPriceTransPngList[k].dateFrom = dataListPrice.value[i].lngPriceTransPngList[k].dateFrom ? dayjs(dataListPrice.value[i].lngPriceTransPngList[k].dateFrom).format('YYYY-MM-DD HH:mm:ss'):null
            dataListPrice.value[i].lngPriceTransPngList[k].dateFromNew = dataListPrice.value[i].lngPriceTransPngList[k].dateFromNew ? dayjs(dataListPrice.value[i].lngPriceTransPngList[k].dateFromNew).format('YYYY-MM-DD HH:mm:ss') : null
            dataListPrice.value[i].lngPriceTransPngList[k].dateToF = dataListPrice.value[i].lngPriceTransPngList[k].dateToF ? dayjs(dataListPrice.value[i].lngPriceTransPngList[k].dateToF).format('YYYY-MM-DD HH:mm:ss') : null
            dataListPrice.value[i].lngPriceTransPngList[k].dateToY = dataListPrice.value[i].lngPriceTransPngList[k].dateToY ? dayjs(dataListPrice.value[i].lngPriceTransPngList[k].dateToY).format('MM-DD') : null
            dataListPrice.value[i].lngPriceTransPngList[k].comId = formState.comId
            dataListPrice.value[i].lngPriceTransPngList[k].suCode = formState.cpCode
            dataListPrice.value[i].lngPriceTransPngList[k].pointDelyCode = dataListPrice.value[i].pointDelyCode
            dataListPrice.value[i].lngPriceTransPngList[k].pointUpCode = dataListPrice.value[i].pointUpCode
            let arr = dataListPrice.value[i].lngPriceTransPngList[k].lngPriceTransPngDtlList || []
            for(let i=0; i<arr.length; i++) {
              let isFlag = arr[i].sortDesc == null || arr[i].sortDesc === ''|| arr[i].priceTransM3 == null || arr[i].priceTransM3 === ''
              let isFlagNew = false
              if (arr[i].sort <arr.length && (arr[i].qtyM3 == '' || arr[i].qtyM3 == null)) {
                isFlagNew = true
              }
              if (isFlag || isFlagNew) {
                message.warn('请完善管输价格必选项')
                return
              }
              
            }
          }
        }
       

        let obj = {
          ...formState,
          lngContractTransPngList: dataListPrice.value,
          lngFileUploadList: dataFile.value,
          lngContractFactRelList: dataListContractFact.value,
          lngContractApproRelList: dataListAppro.value,
          approCode: pageType.value=='update' ? 'WTJ' : formState.approCode
          
        }
        spinning.value = true;
        let request = !formState.id ? addLngContract :updateLngContract

        try {
          const data = await request(obj);
          // 新增保存
          if (data?.id) {
            getInfo(data?.id)
          }
          // 同意保存不提示
          if (!type) {
            notification.success({
                message: '提示',
                description: data?.id ? t('新增成功！') : t('修改成功！')
            }); //提示消息
          }
          return data?.id ? data : obj
          
        } finally {
          spinning.value = false;
        }

      } catch (errorInfo) {
         spinning.value = false;
         errorInfo?.errorFields?.length && notification.warning({
          message: '提示',
          description: '请完善信息'
        });
        return false
      }
    }

      defineExpose({
        handleSubmit,
        getFormValue
    });
</script>

<style lang="less" scoped>
  :deep(.ant-form-item .ant-form-item-label) {
    width: 135px !important;
    max-width: 135px !important;
  }
    .page-bg-wrap {
        background-color: #fff;
    }

    .top-toolbar {
        min-height: 44px;
        margin-bottom: 12px;
        border-bottom: 1px solid #eee;
    } 
    .redStyle {
      color: red;
    }
    .tbStyle {
      border: 1px dashed #d9d9d9;
      padding: 10px;
      margin-bottom: 10px;
    }
    .tb-box {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
</style>
