<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="16">
              <a-form-item label="申请说明" name="appName" :label-col="{ span: 4 }" :wrapper-col="{ span: 24 }">
                <a-input v-model:value="formState.appName" placeholder="请输入" :disabled="isDisable"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="定价类型" name="priceTypeCode">
                <a-select v-model:value="formState.priceTypeCode" :disabled="isDisable" placeholder="请选择" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.priceTypeCodeList" :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 || dataListPrice.length" placeholder="请选择" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.comIdList" :key="item.id" :value="item.id">
                    {{ item.shortName }}
                  </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="24">
              <a-form-item label="说明" name="priceDesc" :label-col="{ span: 3 }" :wrapper-col="{ span: 24 }">
                <a-textarea  v-model:value="formState.priceDesc" :disabled="isDisable"  placeholder="请输入备注"  :auto-size="{ minRows: 2, maxRows: 5 }"/>
              </a-form-item>
            </a-col>
          </a-row>
        </Card>
        <priceInfoList :list="dataListPrice" :formState="formState" :optionSelect="optionSelect" ref="priceRef" pageType="pur" :isDisable="isDisable" :rateCode="rateCode" @change="priceChange"/>
        <Card title="附件信息" :bordered="false" >
          <UploadList :disabled="isDisable" :list="dataFile" :value="formState.filePath" :tableName="tableName" :columnName="columnName" @change="uploadListChange"/>
        </Card>
      </a-form>
    </div>
    
  </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 { addLngPricePurPngApp,updateLngPricePurPngApp, getLngPricePurPngApp } from '/@/api/price/PricePurPngApp';
    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 priceInfoList from '/@/components/common/priceInfoList.vue';
    import { useUserStore } from '/@/store/modules/user';
    import { getParameter } from '/@/api/contract/ContractProc';
    import { DataFormat, FormatOption, DATE_FORMAT, FormatType } from '/@/utils/dataFormat';
    import { getAllCom} from '/@/api/contract/ContractPurInt';
    

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

    const tableName = 'PricePurPngApp';
    const columnName = 'PricePurPngApp'

    const formType = ref('2'); // 0 新建 1 修改 2 查看
    const formRef = ref();
    const priceRef = 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 rateCode = ref()
    const { notification } = useMessage();
    const { t } = useI18n();
    const formState = reactive({
      approCode: 'WTJ',
    });
    const [registerPur, { openModal:openModalPur}] = useModal();
    const rules= reactive({
      appName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      priceTypeCode: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      comId: [{ required: true, message: "该项为必填项", trigger: 'change' }],
    });
    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    }
    const dataFile = ref([]);
    let optionSelect= reactive({
      approCodeList: [],
      priceTypeCodeList: [],
      comIdList: [],
      baseIncList: []
    });
    const dataListPrice = ref([
      // {
      //   lngPricePurPngAppSuDtlList: []  
      // }
    ])
    
    watch(
      () => props.id,
      (val) => {
        if (val) {
          getInfo(val)
        }  
      },
      {
        immediate: true
      }
    );
    watch(
      () => props.disabled,
      (val) => {
        isDisable.value = val
        
      },
      {
        immediate: true
      }
    );
    onMounted(async() => {
      getOption()
      if (pageId.value) {
        getInfo(pageId.value)
      }
      let a = await getParameter({code: 'RATE_M3_GJ'})||[]
      rateCode.value = a[0]?.valueNum1
    });
  
    
    const priceChange = (val) => {
      dataListPrice.value = val
    }
    const uploadListChange = (val) => {
      dataFile.value = val
    }
    async function getInfo(id)  {
      spinning.value = true
      try {
      let data = await getLngPricePurPngApp(id)
      spinning.value = false
      Object.assign(formState, {...data})
      Object.assign(dataFile.value, formState.lngFileUploadList || [])
      Object.assign(dataListPrice.value, formState.lngPricePurPngAppSuList || [])
      dataListPrice.value.forEach(v=> {
        v.dateFrom = v.dateFrom ? dayjs(v.dateFrom) : null
      })
      } catch (error) {
        spinning.value = false
      }
    }
    async function getOption() {
      optionSelect.priceTypeCodeList = await getDictionary('LNG_PRC_T')
      optionSelect.approCodeList = await getDictionary('LNG_APPRO')
      optionSelect.baseIncList = await getDictionary('LNG_BASE')
      optionSelect.comIdList = await getAllCom() || []

    }
      
    async function getFormValue() {
      return formState
    }
    async function handleSubmit(type) {
      try {
        await formRef.value.validateFields();
        let priceList = priceRef.value.getList()
        for(let i=0; i<priceList.length; i++) {
          let isFlag = !priceList[i].kName || !priceList[i].dateFrom
          if (isFlag) {
            message.warn('请完善供应商价格信息必选项')
            return
          }
          let arr = priceList[i].lngPricePurPngAppSuDtlList || []
          for(let i=0; i<arr.length; i++) {
            if (!arr[i].priceCode) {
              message.warn('请完善供应商价格信息必选项')
              return
            }
          }
        }

        let obj = {
          ...formState,
          lngPricePurPngAppSuList: priceList,
          lngFileUploadList: dataFile.value,
          approCode: pageType.value=='update' ? 'WTJ' : formState.approCode
          
        }
        spinning.value = true;
        let request = !formState.id ? addLngPricePurPngApp :updateLngPricePurPngApp

        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;
    }

</style>
