<template>
  <a-spin :spinning="spinning" tip="加载中...">
    
    <div class="page-bg-wrap formViewStyle pdcss">
      <div class="top-toolbar" >
        <a-button style="margin-right: 10px" @click="close">
          <slot name="icon"><close-outlined /></slot>关闭
        </a-button>
        <template v-if="pageType!=='view'">
          <a-button style="margin-right: 10px" type="primary" @click="handleSubmit">
            <slot name="icon"><save-outlined /></slot>保存
          </a-button>
        </template>
      </div>
      <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="ssNo">
                <a-input v-model:value="formState.ssNo" disabled/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="是否自采" name="ownSign">
                <a-select v-model:value="formState.ownSign" :disabled="isDisable" placeholder="请选择是否自采" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.ownSignList" :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="comId">
                <a-select v-model:value="formState.comId" :disabled="isDisable" placeholder="请选择" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.comIdList" :key="item.value" :value="item.value">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="长协/现货" name="longSpotCode">
                <a-select v-model:value="formState.longSpotCode" :disabled="isDisable" placeholder="请选择" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.longSpotCodeList" :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="kName">
                <a-input-search v-model:value="formState.kName" :disabled="isDisable" placeholder="请选择合同"  readonly @search="onContract"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="供应商" name="suName">
                <a-input-search v-model:value="formState.suName" :disabled="isDisable" placeholder="请选择供应商"  readonly @search="onSearchSupplier"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="价格条款" name="prcTermCode">
                <a-select v-model:value="formState.prcTermCode" :disabled="isDisable" placeholder="请选择" style="width: 100%" allow-clear @change="periodTypeCodeChange">
                  <a-select-option v-for="item in optionSelect.prcTermCodeList" :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="ssTypeCode">
                <a-select v-model:value="formState.ssTypeCode" :disabled="isDisable" placeholder="请选择" style="width: 100%" allow-clear @change="periodTypeCodeChange">
                  <a-select-option v-for="item in optionSelect.ssTypeCodeList" :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="cuName">
                <a-input-search v-model:value="formState.cuName" :disabled="isDisable" placeholder="请选择客户"  readonly @search="onSearchCustomer"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="接收站" name="staName">
                <a-input-search v-model:value="formState.staName" :disabled="isDisable" placeholder="请选择接收站"  readonly @search="onSearchStation"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="卸港港口" name="portUnloading1Name">
                <a-input-search v-model:value="formState.portUnloading1Name" :disabled="isDisable" placeholder="请选择卸港港口"  readonly @search="onSearchPort"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="是否接卸" name="unloadSign">
                <a-select v-model:value="formState.unloadSign" :disabled="isDisable" placeholder="请选择" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.ownSignList" :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="shipName">
                <a-input v-model:value="formState.shipName" :disabled="isDisable"  placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="船只IMO" name="shipCode">
                <a-input v-model:value="formState.shipCode" :disabled="isDisable" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="国际气源地" name="sourceName">
                <a-input v-model:value="formState.sourceName" :disabled="isDisable" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="NOR" name="dateNor">
                <a-date-picker v-model:value="formState.dateNor" style="width: 100%" :disabled="isDisable" placeholder="请选择日期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="最迟交货日" name="dateEnd">
                <a-date-picker v-model:value="formState.dateEnd" style="width: 100%" :disabled="isDisable" placeholder="请选择日期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="卸港ETA" name="dateEta">
                <a-date-picker v-model:value="formState.dateEta" style="width: 100%" :disabled="isDisable" placeholder="请选择日期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="卸港ETB" name="dateEtb">
                <a-date-picker v-model:value="formState.dateEtb" style="width: 100%" :disabled="isDisable" placeholder="请选择日期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="卸港ETC" name="dateEtc">
                <a-date-picker v-model:value="formState.dateEtc" style="width: 100%" :disabled="isDisable" placeholder="请选择日期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="卸港ETD" name="dateEtd">
                <a-date-picker v-model:value="formState.dateEtd" style="width: 100%" :disabled="isDisable" placeholder="请选择日期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="热值(MMBtu)" name="qtyMmbtu">
                <input-number v-model:value="formState.qtyMmbtu" :disabled="isDisable" :digits="3" :min="0" style="width: 100%" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="热值(GJ)" name="qtyGj">
                <input-number v-model:value="formState.qtyGj" :disabled="isDisable" :digits="3" :min="0" style="width: 100%" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="重量(吨)" name="qtyTon">
                <input-number v-model:value="formState.qtyTon" :disabled="isDisable" :digits="3" :min="0" style="width: 100%" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="体积(标方)" name="qtyM3">
                <input-number v-model:value="formState.qtyM3" :disabled="isDisable" :digits="3" :min="0" style="width: 100%" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="币种" name="currCode">
                <a-select v-model:value="formState.currCode" :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="rateEx">
                <input-number v-model:value="formState.rateEx" :disabled="isDisable" :digits="6" :min="0" style="width: 100%" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="采购价格" name="priceMmbtuPur">
                <input-number v-model:value="formState.priceMmbtuPur" :disabled="isDisable" :digits="4" :min="0" style="width: 100%" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="采购金额" name="amountPur">
                <input-number v-model:value="formState.amountPur" :disabled="isDisable" :digits="2" :min="0" style="width: 100%" placeholder="请输入"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <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="empTel">
                <a-input-search v-model:value="formState.empTel" :disabled="isDisable" placeholder="请输入"  readonly @search="onSearchUser"/>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="对在港烧气有特别要求" class="formItemWarp" name="request" :label-col="{ span: 3 }" :wrapper-col="{ span: 24 }">
                <a-textarea  v-model:value="formState.request" :disabled="isDisable" :maxLength="100" placeholder="请输入内容，最多100字"  :auto-size="{ minRows: 2, maxRows: 5 }"/>
              </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="请输入内容，最多200字"  :maxLength="200"  :auto-size="{ minRows: 2, maxRows: 5 }"/>
              </a-form-item>
            </a-col>
          </a-row>
        </Card>
        <Card title="附件信息" :bordered="false" >
          <UploadList :disabled="isDisable" :list="dataFile" :value="formState.filePath" :tableName="tableName" :columnName="columnName" @change="uploadListChange"/>
        </Card>
      </a-form>
    </div>
    <deptUserModal @register="register" @success="handleSuccess"/>
    <ContractPurIntListModal @register="registerContractPurInt" @success="handleSuccessContractPurInt" selectType="radio" />
    <supplierListModal @register="registerSupplier" @success="handleSuccessSupplier" selectType="radio" />
    <customerListModal @register="registerCustomer" @success="handleSuccessCustomer" selectType="radio" />
    <lngStationModal @register="registerStation" @success="handleSuccessStation"/>
    <portListModal @register="registerPort" @success="handleSuccessPort"/>
  </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 { SendOutlined, SaveOutlined, CloseOutlined, } from '@ant-design/icons-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 { getAllPriceTerm} from '/@/api/contract/ContractPurInt';
    import { addLngShipSchedule,updateLngShipSchedule, getLngShipSchedule} from '/@/api/ship/ShipSchedule';
    import { getAllCurrency } from '/@/api/contract/ContractFact';
    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 ContractPurIntListModal from '/@/components/common/ContractPurIntListModal.vue';
    import supplierListModal from '/@/components/common/supplierListModal.vue';
    import lngStationModal from '/@/components/common/lngStationModal.vue';
    import customerListModal from '/@/components/common/customerListModal.vue';
    import portListModal from '/@/components/common/portListModal.vue';
    import { useUserStore } from '/@/store/modules/user';
    import { getAllCom} from '/@/api/contract/ContractPurInt';
    const userStore = useUserStore();
    const userInfo = userStore.getUserInfo;

    const tableName = 'ShipSchedule';
    const columnName = 'ShipSchedule'

    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 { notification } = useMessage();
    const { t } = useI18n()

    const formState = reactive({
      
    });
    const [register, { openModal:openModal}] = useModal();
    const [registerContractPurInt, { openModal:openModalContractPurInt}] = useModal();
    const [registerSupplier, { openModal:openModalSupplier}] = useModal();
    const [registerStation, { openModal:openModalStation}] = useModal();
    const [registerCustomer, { openModal:openModalCustomer}] = useModal();
    const [registerPort, { openModal:openModalPort}] = useModal();
    const rules= reactive({
      ownSign: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      comId: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      ssTypeCode: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      currCode: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      dateEta: [{ required: true, message: "该项为必填项", trigger: 'change' }],
    });
    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    }
    const dataFile = ref([]);
    let optionSelect= reactive({
      ownSignList: [],
      comIdList: [],
      ssTypeCodeList: [],
      longSpotCodeList: [],
      curCodeList: [],
      prcTermCodeList: [],
    });
    watch(
      () => props.id,
      (val) => {
        if (val) {
          getInfo(val)
        }  
      },
      {
        immediate: true
      }
    );
    watch(
      () => props.disabled,
      (val) => {
        isDisable.value = val
      },
      {
        immediate: true
      }
    );
    onMounted(() => {
      isDisable.value = pageType.value == 'view'
      getOption()
      if (pageId.value) {
        getInfo(pageId.value)
      } else {
        formState.empName = userInfo.name
        formState.empId = userInfo.id
        formState.empTel = userInfo.mobile
        getOptionParams()
      }
   
    });

    const uploadListChange = (val) => {
      dataFile.value = val
    }
    async function getInfo(id)  {
      spinning.value = true
      try {
      let data = await getLngShipSchedule(id)
      spinning.value = false
      Object.assign(formState, {...data})
      Object.assign(dataFile.value, formState.lngFileUploadList || [])
      formState.dateNor = formState.dateNor ? dayjs(formState.dateNor) : null
      formState.dateEnd = formState.dateEnd ? dayjs(formState.dateEnd) : null
      formState.dateEta = formState.dateEta ? dayjs(formState.dateEta) : null
      formState.dateEtb = formState.dateEtb ? dayjs(formState.dateEtb) : null
      formState.dateEtc = formState.dateEtc ? dayjs(formState.dateEtc) : null
      formState.dateEtd = formState.dateEtd ? dayjs(formState.dateEtd) : null
      getOptionParams()

      } catch (error) {
        spinning.value = false
      }
    }
    async function getOption() {
      optionSelect.ownSignList = await getDictionary('LNG_YN')
      optionSelect.ssTypeCodeList = await getDictionary('LNG_SHP_S')
      optionSelect.approCodeList = await getDictionary('LNG_APPRO')
      optionSelect.longSpotCodeList = await getDictionary('LNG_LONG')
      let res = await getAllCom() || []
      optionSelect.comIdList = res.map(v=> {
        return {
          label: v.shortName,
          value: v.id
        }
      })
    }
    async function getOptionParams() {
      optionSelect.curCodeList = await getAllCurrency({eid: formState.curCode})
      optionSelect.prcTermCodeList = await getAllPriceTerm({eid: formState.prcTermCode})
    }
    const onSearchPort= () => {
      openModalPort(true,{isUpdate: false})
    }
    const onSearchCustomer = () => {
      openModalCustomer(true,{isUpdate: false})
    }
    const onSearchStation = (val)=> {
      openModalStation(true,{isUpdate: false})
    }
    const onSearchSupplier = () => {
      openModalSupplier(true,{isUpdate: false})
    }
    const onSearchUser = (val)=> {
      openModal(true,{isUpdate: false})
    }
    const onContract = (val)=> {
      openModalContractPurInt(true,{isUpdate: false})
    }
    const handleSuccess = (val, deptId) => {
      formState.empName = val[0].name
      formState.empId = val[0].id
      formState.empTel = val[0].mobile
    }
     const handleSuccessPort = (val) => {
      formState.portUnloading1Code = val[0].code
      formState.portUnloading1Name = val[0].fullName
    }
    const handleSuccessStation = (val) => {
      formState.staCode = val[0].code
      formState.staName = val[0].fullName
    }
    const handleSuccessCustomer = (val) => {
      formState.cuCode = val[0].cuCode
      formState.cuName = val[0].cuName
    }
    const handleSuccessSupplier = (val) => {
      formState.suCode = val[0].suCode
      formState.suName = val[0].suName
    }
    const handleSuccessContractPurInt = (val) => {
      formState.kId = val[0].id
      formState.kName = val[0].kName
      formState.comId = val[0].comId
      formState.suCode = val[0].suCode
      formState.suName = val[0].suName
      formState.longSpotCode = val[0].longSpotCode
      formState.prcTermCode = val[0].prcTermCode
      formState.sourceName = val[0].sourceName
    }
    function close() {
      tabStore.closeTab(currentRoute.value, router);
    }
    async function getFormValue() {
      return formState
    }
    async function handleSubmit(type) {
      try {
        await formRef.value.validateFields();
        let obj = {
          ...formState,
          lngFileUploadList: dataFile.value,
        }
        spinning.value = true;
        let request = !formState.id ? addLngShipSchedule :updateLngShipSchedule

        try {
          const data = await request(obj);
          notification.success({
              message: '提示',
              description: data?.id ? t('新增成功！') : t('修改成功！')
          }); //提示消息
          
          setTimeout(() => {
            bus.emit(FORM_LIST_MODIFIED, {});
            close();
          }, 500);
          
        } 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;
    } 
    .pdcss {
      padding:0px 12px 6px 12px !important;
    }
    :deep(.formItemWarp .ant-form-item-label > label) {
      white-space: normal !important;
      word-break: break-word !important;
    }
    
</style>
