<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="comId">
                 <a-select v-model:value="formState.comId" :disabled="isDisable || pageType" 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="staName">
                <a-input-search v-model:value="formState.staName" :disabled="isDisable || pageType" placeholder="请选择接收站"  readonly @search="onSearchStation"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="入库类型" name="typeCode">
                <a-select v-model:value="formState.typeCode" :disabled="isDisable||pageType" placeholder="请选择" @change="typeCodeChange" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.typeCodeList" :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="dateOut">
                <a-date-picker :inputReadOnly="true" v-model:value="formState.dateOut" style="width: 100%" :disabled="isDisable" placeholder="请选择日期" />
              </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||formState.typeCode=='CQ'||pageType" placeholder="请选择合同"  readonly @search="onContract"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="客户" name="cuName">
                <a-input-search v-model:value="formState.cuName" disabled/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="主计量单位" name="uomCode">
                <a-select v-model:value="formState.uomCode" :disabled="isDisable" placeholder="请选择" @change="uomCodeChage" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.uomCodeList" :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="rateTonGj">
                <input-number v-model:value="formState.rateTonGj" :disabled="isDisable"  :min="0" @blur="numCount" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="比值(方/吉焦)" name="rateM3Gj">
                <input-number v-model:value="formState.rateM3Gj" :disabled="isDisable"  :min="0" @blur="numCount" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="出库量(吉焦)" name="qtyGj">
                <input-number v-model:value="formState.qtyGj" :disabled="isDisable" :digits="3" :min="0" @blur="numCount" style="width: 100%" />
              </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" @blur="numCount" style="width: 100%" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-item label="出库价格(元/吉焦)" name="priceGj">
                <input-number v-model:value="formState.priceGj" :disabled="isDisable" :min="0" @blur="numCount" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="出库价格(元/吨)" name="priceTon">
                <input-number v-model:value="formState.priceTon" :disabled="isDisable" :min="0" @blur="numCount" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="出库金额(元)" name="amount">
                <input-number v-model:value="formState.amount" :disabled="isDisable" :digits="2" :min="0" @blur="amountCount" style="width: 100%" />
              </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" :maxLength="200" placeholder="请输入内容，最多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" @blur="uploadListChange"/>
        </Card>
      </a-form>
    </div>
    <contractSalesLngListModal @register="registerContractSalesLng" @success="handleSuccessContractSalesLng"/>
    <lngStationModal @register="registerStation" @success="handleSuccessStation"/>
  </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 { addLngInventoryOut,updateLngInventoryOut, getLngInventoryOut,} from '/@/api/inventory/lngInventoryOut';
    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 contractSalesLngListModal from '/@/components/common/contractSalesLngListModal.vue';
    import lngStationModal from '/@/components/common/lngStationModal.vue';
    import { getAllCom} from '/@/api/contract/ContractPurInt';
    import { getParameter } from '/@/api/contract/ContractProc';

    const tableName = 'LngInventoryOut';
    const columnName = 'LngInventoryOut'

    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 pageSource = ref(currentRoute.value.query?.pageSource)
    const spinning = ref(false);
    const { notification } = useMessage();
    const { t } = useI18n()

    const formState = reactive({
      approCode: 'WTJ',
      typeCode: 'ZN',
      catCode: 'LNG'
    });
    const [register, { openModal:openModal}] = useModal();
    const [registerContractSalesLng, { openModal:openModalContractSalesLng}] = useModal();
    const [registerStation, { openModal:openModalStation}] = useModal();
    
    const rules= reactive({
      comId: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      ssTypeCode: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      typeCode: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      kName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      staName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      dateOut: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      uomCode: [{ required: true, message: "该项为必填项", trigger: 'change' }]
    });
    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    }
    const dataFile = ref([]);
    let optionSelect= reactive({
      comIdList: [],
      typeCodeList: [],
      uomCodeList: [],
    });
    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 {
        getSysRate()
      }
    });
    async function getSysRate () {
      let a = await getParameter({code: 'RATE_TON_GJ'})||[]
      let b = await getParameter({code: 'RATE_M3_GJ'})||[]
      formState.rateTonGj = a[0]?.valueNum1
      formState.rateM3Gj = b[0]?.valueNum1
    }
    const uploadListChange = (val) => {
      dataFile.value = val
    }
    async function getInfo(id)  {
      spinning.value = true
      try {
      let data = await getLngInventoryOut(id)
      spinning.value = false
      Object.assign(formState, {...data})
      Object.assign(dataFile.value, formState.lngFileUploadList || [])
      formState.dateOut = formState.dateOut ? dayjs(formState.dateOut) : null
  

      } catch (error) {
        spinning.value = false
      }
    }
    async function getOption() {
      optionSelect.uomCodeList = await getDictionary('LNG_UOM')
      optionSelect.typeCodeList = await getDictionary('LNG_INV_I')
      let res = await getAllCom() || []
      optionSelect.comIdList = res.map(v=> {
        return {
          label: v.shortName,
          value: v.id
        }
      })
     
    }
    const typeCodeChange = (val) => {
      if (val !== 'ZN') {
        formState.kId = ''
        formState.kName = ''
        formState.cuCode = ''
        formState.cuName = ''
        rules.kName = [{ required: false, message: "该项为必填项", trigger: 'change' }]
      } else {
        rules.kName = [{ required: true, message: "该项为必填项", trigger: 'change' }]
      }
     
    }
    const uomCodeChage = () => {
      numCount()
    }
    const numCount = () => {

      if (formState.uomCode == 'GJ') {
        if (!formState.qtyTon) {
          formState.qtyTon = Number(formState.rateTonGj) ? Number(formState.qtyGj || 0)/Number(formState.rateTonGj) : 0
          amountCount()
        }
        if (!formState.amount) {
          formState.amount = Number(formState.qtyGj || 0)*Number(formState.priceGj || 0)
          amountCount()
          
        }
      }
      
      if (formState.uomCode == 'TON') {
        if (!formState.qtyGj) {
          formState.qtyGj = Number(formState.qtyTon || 0)*Number(formState.rateTonGj || 0)
          amountCount()
        }
        if (!formState.amount) {
          formState.amount = Number(formState.qtyTon || 0)*Number(formState.priceTon || 0)
          amountCount()
        }
      }
    }
    const amountCount = () => {
      if (!formState.priceTon) {
        formState.priceTon = Number(formState.qtyTon) ? Number(formState.amount || 0)/Number(formState.qtyTon) : null
      }
      if (!formState.priceGj) {
        formState.priceGj = Number(formState.qtyGj) ? Number(formState.amount || 0)/Number(formState.qtyGj) : null
      }
    }
    const onSearchStation = (val)=> {
      openModalStation(true,{isUpdate: false})
    }

    const onContract = (val)=> {
      openModalContractSalesLng(true,{isUpdate: false})
    }
    
    const handleSuccessStation = (val) => {
      formState.staCode = val[0].code
      formState.staName = val[0].fullName
    }
    const handleSuccessContractSalesLng = (val) => {
      formState.kId = val[0].id
      formState.kName = val[0].kName
      formState.comId = val[0].comId
      formState.cuCode = val[0].cpCode
      formState.cuName = val[0].cpName
    }
    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 ? addLngInventoryOut :updateLngInventoryOut

        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>
