<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="8">
              <a-form-item label="合同名称" name="kName">
                <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="请选择合同期限" style="width: 100%" allow-clear @change="periodTypeCodeChange">
                  <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="dateCfmFrom">
                <a-date-picker v-model:value="formState.dateCfmFrom" @change="dateCfmChange" style="width: 100%" :disabled="isDisable" :disabled-date="disabledDateCfmStart" placeholder="请选择确认函开始日" />
              </a-form-item>
            </a-col>
             <a-col :span="8">
              <a-form-item label="确认函结束日" name="dateCfmTo">
                <a-date-picker v-model:value="formState.dateCfmTo" @change="dateCfmChange" style="width: 100%" :disabled="isDisable" :disabled-date="disabledDateCfmEnd" placeholder="请选择确认函结束日" />
              </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="onSearchCustomer"/>
              </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-search v-model:value="formState.bDeptName" disabled placeholder="请选择业务部门"  readonly @search="onSearch"/>
              </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="8">
              <a-form-item label="定价机制" name="prcTypeCode">
                <a-select v-model:value="formState.prcTypeCode" :disabled="isDisable" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.prcTypeCodeList" :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="periodTypeCode">
                <a-select v-model:value="formState.periodTypeCode" :disabled="isDisable" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.periodTypeCodeList" :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="onlineSign">
                <a-select v-model:value="formState.onlineSign" disabled style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.onlineSignList" :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="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-row>
        </Card>
        <Card title="业务信息" :bordered="false" >
          <div>
            <a-col :span="8">
              <a-form-item label="全部气源地可用" name="allStaSign">
                  <a-radio-group v-model:value="formState.allStaSign" :disabled="isDisable">
                     <template v-for="item in optionSelect.onlineSignList">
                       <a-radio :value="item.code" >{{item.name}}</a-radio>
                     </template>
                 </a-radio-group>
               </a-form-item>
             </a-col>
             <template v-if="formState.allStaSign=='N'">
               <h4>气源地列表</h4>
               <lngStationList :list="dataListStation" ref="lngStationRef" :disabled="isDisable" :isEdit="isDisable ||!formState.allStaSign|| formState.allStaSign=='Y'"></lngStationList>
             </template>
          </div>
          <div>
            <h4>合同约定</h4>
            <contractQtyLngList :list="dataListContractAgree" :disabled="isDisable" :optionSelect="optionSelect" ref="contractQty"></contractQtyLngList>
          </div>
          <div>
            <h4>返优惠列表</h4>
            <discountList :list="dataListDiscount" ref="discountRef" :optionSelect="optionSelect" :disabled="isDisable"></discountList>
          </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"/>
    <deptListModal @register="registerDept" @success="handleSuccessDept" />
    <contractFactListModal @register="registerContractFact" @success="handleSuccessContractFact" />
    <customerListModal @register="registerCustomer" @success="handleSuccessCustomer" 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, getTransList, getPurList } from '/@/api/contract/ContractSalesLng';
    import { getLngContractFact } from '/@/api/contract/ContractFact';
    import { getLngAppro,getCompDept } from '/@/api/approve/Appro';
    import dayjs from 'dayjs';
    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 lngStationList from '/@/components/common/lngStationList.vue';
    import customerListModal from '/@/components/common/customerListModal.vue';
    import contractQtyLngList from '/@/components/common/contractQtyLngList.vue';
    import discountList from '/@/components/common/discountList.vue';
    import { useUserStore } from '/@/store/modules/user';

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

    const tableName = 'ContractSalesLng';
    const columnName = 'ContractSalesLng'

    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 contractQty = ref()
    const lngStationRef = ref()
    const discountRef = ref()
    const spinning = ref(false);
    const curIdx = ref(null)
    const { notification } = useMessage();
    const { t } = useI18n();
    const hasDel = ref(false)
    const formState = reactive({
      approCode: 'WTJ',
      typeCode: 'SL',
      onlineSign: 'N',
      cpTableName: 'lng_customer',
      curCode: 'CNY',
      lngContractSalesLngList: [{}],
    });
    const [register, { openModal:openModal}] = useModal();
    const [registerDept, { openModal:openModalDept}] = useModal();
    const [registerContractFact, { openModal:openModalContractFact}] = useModal();
    const [registerDownLoad, { openModal:openModalDownLoad}] = useModal();
    const [registerCustomer, { openModal:openModalCustomer}] = useModal();
    const rules= reactive({
      kNo: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      kName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      cpName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      prcTypeCode: [{ 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' }],
      allStaSign:[{ required: true, message: "该项为必填项", trigger: 'change' }],
      periodTypeCode:[{ required: false, message: "该项为必填项", trigger: 'change' }],
    });
    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    }
    const dataListContractAgree = ref([])
    const dataListStation = ref([])
    const dataListDiscount = ref([])
    const dataFile = ref([]);
    const dataListAppro = ref([])
    const dataListContractFact = ref([])
    let optionSelect= reactive({
      approCodeList: [],
      kPeriodList: [],
      prcTypeCodeList: [],
      periodTypeCodeList: [],
      onlineSignList: [],
      discTypeCodeList: [],
      baseIncList: [],
      zfbyTypeCodeList: []
    });
    watch(
      () => props.id,
      (val) => {
        if (val) {
          getInfo(val)
        }  
      },
      {
        immediate: true
      }
    );
    watch(
      () => props.disabled,
      (val) => {
        isDisable.value = val
      },
      {
        immediate: true
      }
    );
    onMounted(() => {
      getOption()
      if (pageId.value) {
        getInfo(pageId.value)
      } else {
        formState.empName = userInfo.name
        formState.empId = userInfo.id
        formState.tel = userInfo.mobile
      }
   
    });
    const periodTypeCodeChange = (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(dataListContractAgree.value, formState.lngContractSalesLngQtyList || [])
      Object.assign(dataFile.value, formState.lngFileUploadList || [])
      Object.assign(dataListContractFact.value, formState.lngContractFactRelList || [])
      Object.assign(dataListAppro.value, formState.lngContractApproRelList || [])
      Object.assign(dataListStation.value, formState.lngContractSalesLngStaList || [])
      Object.assign(dataListDiscount.value, formState.lngContractSalesLngDiscList || [])
      formState.dateCfmFrom = formState.dateCfmFrom ? dayjs(formState.dateCfmFrom) : null
      formState.dateCfmTo = formState.dateCfmTo ? dayjs(formState.dateCfmTo) : null
      formState.dateSign = formState.dateSign ? dayjs(formState.dateSign) : null
      formState.dateFrom = formState.dateFrom ? dayjs(formState.dateFrom) : null
      formState.dateTo = formState.dateTo ? dayjs(formState.dateTo) : null
      formState.prcTypeCode = (formState?.lngContractSalesLngList[0] || {}).prcTypeCode
      formState.periodTypeCode = (formState?.lngContractSalesLngList[0] || {}).periodTypeCode
      formState.uomCode = (formState?.lngContractSalesLngList[0] || {}).uomCode
      formState.allStaSign = (formState?.lngContractSalesLngList[0] || {}).allStaSign
      
      dataListContractAgree.value.forEach(v => {
        v.dateFrom = v.dateFrom ? dayjs(v.dateFrom) : null
        v.dateTo = v.dateTo ? dayjs(v.dateTo) : null
      });

      } catch (error) {
        console.log(error, 'error')
        spinning.value = false
      }
    }
    async function getOption() {
      optionSelect.kPeriodList = await getDictionary('LNG_K_PER')
      optionSelect.prcTypeCodeList = await getDictionary('LNG_PRC')
      optionSelect.periodTypeCodeList = await getDictionary('LNG_PRC_P')
      optionSelect.approCodeList = await getDictionary('LNG_APPRO')
      optionSelect.onlineSignList = await getDictionary('LNG_YN')
      optionSelect.discTypeCodeList = await getDictionary('LNG_DISC')
      optionSelect.baseIncList = await getDictionary('LNG_BASE')
      optionSelect.zfbyTypeCodeList = await getDictionary('LNG_ZFBY')
      

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

    }
    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 dateCfmChange = (val) => {
      if (formState.dateCfmFrom || formState.dateCfmTo) {
        rules.periodTypeCode = [{ required: true, message: "该项为必填项", trigger: 'change' }]
      } else {
        rules.periodTypeCode = [{ required: false, message: "该项为必填项", trigger: 'change' }]
      }
    }

    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 disabledDateCfmStart = (startValue) => {
      const endValue = formState?.dateCfmTo;
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf();
    }
    const disabledDateCfmEnd = (endValue) => {
      const startValue = formState?.dateCfmFrom;
      if (!endValue || !startValue) {
        return false
      }
      return endValue.valueOf() <= startValue.valueOf();
    }
    const onSearch = (val)=> {
      openModalDept(true,{isUpdate: false})
    }
    const onSearchCustomer = () => {
      openModalCustomer(true,{isUpdate: false})
    }
    const onSearchUser = (val)=> {
      openModal(true,{isUpdate: false})
    }
    const onContract = (val)=> {
      openModalContractFact(true,{isUpdate: false})
    }


    
    const handleSuccess = (val, deptId) => {
      formState.empName = val[0].name
      formState.empId = val[0].id
      formState.tel = val[0].mobile
      getCompDeptInfo(formState.empId, deptId)
    }
    const handleSuccessDept = (val, info) => {
      formState.bDeptName = val[0].name
      formState.bDeptId = val[0].id

      formState.comName = info.name
      formState.comId = info.id
    }
    const handleSuccessCustomer = (val) => {
      formState.cpCode = val[0].cuCode
      formState.cpName = val[0].cuName
    }
    const handleSuccessContractFact = (val) => {
        val.forEach(v => {
          v.idNew = v.id
          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')
      getContractFact()
    }
    const getContractFact = async () => {
      let a = []
      dataListContractFact.value.forEach(v=>{
        if (v.relTypeCode == 'M') {
          a.push(v)
        } 
      })
      if(a.length == 1) {
        const res = await getLngContractFact(a[0].id || a[0].idNew)
        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.dateFrom = formState.dateFrom ? formState.dateFrom : (res?.dateFrom ? dayjs(res?.dateFrom) : null)
        formState.dateTo = formState.dateTo ? formState.dateTo : (res?.dateTo ? dayjs(res?.dateTo) : null)
        formState.cpName = formState.cpName ? formState.cpName : (res?.lngContractFactCpList || [])[0]?.cpName
        formState.cpCode = formState.cpCode ? formState.cpCode : (res?.lngContractFactCpList || [])[0]?.cpCode
      }
    }
    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();
        let arr =  contractQty.value.getQtyList()
        for(let i=0; i<arr.length; i++) {
          let isFlag = !arr[i].dateFrom || !arr[i].dateTo || !arr[i].baseInc || arr[i].qtyGjMonth == null || arr[i].qtyGjMonth === ''|| arr[i].qtyTonMonth == null || arr[i].qtyTonMonth === ''
          if (isFlag) {
            message.warn('请完善合同约定必选项')
            return
          }
          arr[i].dateFrom = dayjs(arr[i].dateFrom).format('YYYY-MM-DD HH:mm:ss')
          arr[i].dateTo = dayjs(arr[i].dateTo).format('YYYY-MM-DD HH:mm:ss')
        }
        dataListAppro.value.forEach((v,idx)=>{
          v.tableName = 'Ing_contract'
          v.sort = idx
        })
        dataListContractFact.value.forEach((v,idx)=> {
          v.sort = idx
        })
        let arrDic =  discountRef.value.getDataList()
        let arrSta = []
        if (formState.allStaSign=='N') {
          arrSta =  lngStationRef.value.getDataList()
        }
        for(let i=0; i<arrDic.length; i++) {
          if (!arrDic[i].discTypeCode || !arrDic[i].dateFrom || !arrDic[i].dateTo) {
            message.warn('请完善返优惠列表必选项')
            return
          }
        }
     
        let obj = {
          ...formState,
          lngContractSalesLngDiscList: arrDic,
          lngContractSalesLngStaList: arrSta,
          lngContractSalesLngQtyList: arr,
          lngFileUploadList: dataFile.value,
          lngContractFactRelList: dataListContractFact.value,
          lngContractApproRelList: dataListAppro.value,
          lngContractSalesLngList: [
            {
              ...formState.lngContractSalesLngList[0],
              "kId": formState.id,
              "prcTypeCode": formState.prcTypeCode,
              "periodTypeCode": formState.periodTypeCode,
              "uomCode": formState.uomCode,
              allStaSign: formState.allStaSign
            }
          ],
          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: 'Tip',
                description: data?.id ? t('新增成功！') : t('修改成功！')
            }); //提示消息
          }
          return data?.id ? data : obj
          
        } finally {
          spinning.value = false;
        }

      } catch (errorInfo) {
        console.log(errorInfo, 'errorInfo')
         spinning.value = false;
         errorInfo?.errorFields?.length && notification.warning({
          message: 'Tip',
          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;
    } 
    
    h4 {
      margin-top: 10px;
    }
</style>
