<template>
  <a-spin :spinning="spinning" tip="加载中...">
    <div class="page-bg-wrap formViewStyle">
      <a-form ref="formRef" :model="formState" :rules="rules" v-bind="layout">
        <a-card title="" :bordered="false" >
          <a-row>
            <a-col :span="8">
              <a-form-item label="编号" name="code">
                <a-input v-model:value="formState.code" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="16">
              <a-form-item label="标题" name="title" :label-col="{ span: 4 }" :wrapper-col="{ span: 24 }">
                <a-input v-model:value="formState.title" :disabled="isDisable" placeholder="请输入标题"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="签报类型" name="typeCode">
                <a-select v-model:value="formState.typeCode" :disabled="isDisable" placeholder="请选择签报类型" 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="securityCode">
                <a-select v-model:value="formState.securityCode" :disabled="isDisable" placeholder="请选择密级" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.securityCodeList" :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="urgencyCode">
                <a-select v-model:value="formState.urgencyCode" :disabled="isDisable" placeholder="请选择缓急" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.urgencyCodeList" :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="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="isDisable" 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="dateAppro">
                <a-date-picker v-model:value="formState.dateAppro" :disabled="isDisable" style="width: 100%" placeholder="请选择评价日期" />
              </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="22">
              <a-form-item label="内容摘要" name="content" :label-col="{ span: 3 }" :wrapper-col="{ span: 24 }">
                <a-textarea  v-model:value="formState.content" :disabled="isDisable"  placeholder="请输入备注，最多1000字" :maxlength="1000"  :auto-size="{ minRows: 4, }"/>
              </a-form-item>
            </a-col>
            <a-col :span="22">
              <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>
        </a-card>
        <a-card title="附件信息" :bordered="false" >
          <UploadList :disabled="isDisable" :list="dataFile" :value="formState.filePath" :tableName="tableName" :columnName="columnName" @change="uploadListChange"/>
        </a-card>
      </a-form>
    </div>
    <deptUserModal @register="register" @success="handleSuccess"/>
    <deptListModal @register="registerDept" @success="handleSuccessDept" />
  </a-spin>
</template>

<script lang="ts" setup>
    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 { addLngAppro,updateLngAppro,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 { Modal } from 'ant-design-vue';
    import { useUserStore } from '/@/store/modules/user';
    const userStore = useUserStore();
    const userInfo = userStore.getUserInfo;

    const tableName = 'Appro';
    const columnName = 'Appro'

    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 { notification } = useMessage();
    const { t } = useI18n();
    const formState = reactive({
        approCode: 'WTJ',
        dateAppro: dayjs(new Date()),
    });
    const [register, { openModal:openModal}] = useModal();
    const [registerDept, { openModal:openModalDept}] = useModal();
    const rules: Record<string, Rule[]> = {
      title: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      typeCode: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      securityCode: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      urgencyCode: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      empName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      bDeptName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      comName: [{ required: false, message: "该项为必填项", trigger: 'change' }],
      dateAppro: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      content: [{ required: true, message: "该项为必填项", trigger: 'change' }],

    };
    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    }
    const dataFile = ref([]);
    let optionSelect= reactive({
      approCodeList: [],
      typeCodeList: [],
      securityCodeList: [],
      urgencyCodeList: []
    });
    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)
        if (currentRoute.value.query?.disabled) {
          isDisable.value = true 
        }
      } else {
        formState.empName = userInfo.name
        formState.empId = userInfo.id
      }
   
    });
    const uploadListChange = (val) => {
      dataFile.value = val
    }
    async function getInfo(id)  {
      spinning.value = true
      try {
      let data = await getLngAppro(id)
      spinning.value = false
      Object.assign(formState, {...data})
      Object.assign(dataFile.value, formState.lngFileUploadList || [])
      formState.dateAppro = formState.dateAppro ? dayjs(formState.dateAppro) : null
      } catch (error) {
        spinning.value = false
      }
    }
    async function getOption() {
      optionSelect.typeCodeList = await getDictionary('LNG_QB')
      optionSelect.securityCodeList = await getDictionary('LNG_SECRET')
      optionSelect.urgencyCodeList = await getDictionary('LNG_URGEN')
      optionSelect.approCodeList = await getDictionary('LNG_APPRO')

      if (!pageId.value) {
        const res = await getCompDept(userInfo.id)
        formState.bDeptName = res?.dept?.name
        formState.bDeptId = res?.dept?.id
  
        formState.comName = res?.comp?.name
        formState.comId = res?.comp?.id
      }

    }
    const onSearch = (val)=> {
      openModalDept(true,{isUpdate: false})
    }
    const onSearchUser = (val)=> {
      openModal(true,{isUpdate: false})
    }
    const handleSuccess = (val) => {
      formState.empName = val[0].name
      formState.empId = val[0].id
    }
    const handleSuccessDept = (val, info) => {
      formState.bDeptName = val[0].name
      formState.bDeptId = val[0].id

      formState.comName = info.name
      formState.comId = info.id
    }

    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 ? addLngAppro :updateLngAppro

        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) {
         spinning.value = false;
         errorInfo?.errorFields?.length && notification.warning({
          message: 'Tip',
          description: '请完善信息'
        });
        return false
      }
    }

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

<style lang="less" scoped>
    .page-bg-wrap {
        background-color: #fff;
    }

    .top-toolbar {
        min-height: 44px;
        margin-bottom: 12px;
        border-bottom: 1px solid #eee;
    } 
    
</style>
