<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="cpCodeName">
                <a-input-search v-model:value="formState.cpCodeName" placeholder="请选择客户"  readonly @search="onSearch"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="客户分类" name="classCode">
                <a-input v-model:value="formState.classCode" disabled  />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="评价体系" name="gsId">
                <a-select v-model:value="formState.gsId" :disabled="isDisable" placeholder="请选择评价体系" @mouseenter="gsIdFocus(formState.gsId)" @change="gsIdChange" style="width: 100%" allow-clear>
                  <a-select-option v-for="item in optionSelect.gsIdList" :key="item.id" :value="item.id">
                    {{ item.gsName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="评价日期" name="dateGrade">
                <a-date-picker v-model:value="formState.dateGrade" disabled style="width: 100%" placeholder="请选择评价日期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="分类合计" name="score">
                <a-input v-model:value="formState.score" disabled/>
              </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>
        </a-card>
        <a-card title="填写评分表信息" :bordered="false" >
          <a-table :columns="columns" :data-source="dataList" >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'score'">
                <a-input-number v-model:value="record.score" @change="numChagne('score', record, index)"/>
              </template>
              <template v-if="column.dataIndex === 'scoreDesc'">
                <a-input v-model:value="record.scoreDesc" @change="numChagne('scoreDesc', record, index)"/> 
              </template>
            </template>
          </a-table>
        </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>
    <customerListModal @register="register" selectType="radio" @success="handleSuccess"/>
  </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 { getLngGradeSystemPageList, getLngGradeSystem} from '/@/api/sales/GradeSystem';
    import { useModal } from '/@/components/Modal';
    import { addLngScore,updateLngScore,getLngScore } from '/@/api/sales/ScoreCustomer';
    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 customerListModal from '/@/components/common/customerListModal.vue';
    import { getUserInfo } from '/@/api/system/login';
    import { Modal } from 'ant-design-vue';

    const tableName = 'ScoreCustomer';
    const columnName = 'ScoreCustomer'

    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',
        dateGrade: dayjs(new Date()),
    });
    const userInfo = reactive({})
    const [register, { openModal:openModal}] = useModal();
    const rules: Record<string, Rule[]> = {
      cpCodeName: [{ required: true, message: "该项为必填项", trigger: 'change' }],
      gsId: [{ required: true, message: "该项为必填项", trigger: 'change' }],
    };
    const layout = {
      labelCol: { span: 9 },
      wrapperCol: { span: 15 },
    }
    const gsIdOld = ref()
    const columns = ref([
      { title: t('序号'), dataIndex: 'index', key: 'index', sorter: true, customRender: (column) => `${column.index + 1}` ,width: 80},
      { title: t('评价事项'), dataIndex: 'itemName', sorter: true},
      { title: t('评价标准'), dataIndex: 'itemDesc', sorter: true},
      { title: t('评价部门'), dataIndex: 'eDeptCode', sorter: true},
      { title: t('评分'), dataIndex: 'score', sorter: true},
      { title: t('分数说明'), dataIndex: 'scoreDesc', sorter: true},
      { title: t('评价人'), dataIndex: 'aEmpCode', sorter: true},
      { title: t('评价时间'), dataIndex: 'aTime', sorter: true},
      { title: t('实际评价部门'), dataIndex: 'aDeptCode', sorter: true},
    ]);
    const dataList= ref([]);
    const dataFile = ref([]);
    let optionSelect= reactive({
      gsIdList: [],
      approCodeList: [],
    });
    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)
      }
   
    });
    const uploadListChange = (val) => {
      dataFile.value = val
    }
    async function getInfo(id)  {
      spinning.value = true
      try {
      let data = await getLngScore(id)
      spinning.value = false
      Object.assign(formState, {...data})
      Object.assign(dataList.value, formState.lngScoreDtlList || [])
      Object.assign(dataFile.value, formState.lngFileUploadList || [])
      formState.dateGrade = formState.dateGrade ? dayjs(formState.dateGrade) : null
      } catch (error) {
        spinning.value = false
      }
    }
    async function getOption() {
      optionSelect.gsIdList = await getLngGradeSystemPageList({'valid': 'Y', 'typeCode': 'CU'})
      optionSelect.approCodeList = await getDictionary('LNG_APPRO')
      let res = await getUserInfo()
      Object.assign(userInfo, {...res})
    }
    const onSearch = (val)=> {
      openModal(true,{isUpdate: false})
    }
    const handleSuccess = (val) => {
      formState.cpCode = val[0].cuCode
      formState.classCode = val[0].classCode
      formState.cpCodeName = val[0].cuName
    }
    const gsIdFocus = (val) => {
      gsIdOld.value = val
    }
    async function gsIdChange (val) {
      if (!val) {
        dataList.value = []
        return
      }
      const res = await getLngGradeSystem(val)
      let arr = res.lngGradeSystemItemList || []
      if (!gsIdOld.value) {
        dataList.value = res.lngGradeSystemItemList || []
        dataList.value.forEach(v => {
          v.aTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
          v.aEmpCode = userInfo.name
          v.gsiId = v.id
        })
        return
      }
      if (arr.length && gsIdOld.value) {
          Modal.confirm({
            title: t('提示'),
            content: t('变更将重新设置评分表，是否继续'),
            okText: t('确定'),
            cancelText: t('取消'),
            onOk() {
              dataList.value = res.lngGradeSystemItemList || []
              dataList.value.forEach(v => {
                v.aTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
                v.aEmpCode = userInfo.name
                v.gsiId = v.id
              })
            },
            onCancel() {
              formState.gsId = gsIdOld.value
            }
        });
      } else {
        if (!arr.length) {
          dataList.value = res.lngGradeSystemItemList || []
          dataList.value.forEach(v => {
            v.aTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
            v.aEmpCode = userInfo.name
            v.gsiId = v.id
          })
        }
      }
    }
    const numChagne = (type, record, index) => {
      record.aTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
      if (type == 'score') {
        let num = 0
        dataList.value.forEach(v => {
          num+=Number(v.score || 0)
        })
        formState.score = num
      }
    }
    function close() {
      tabStore.closeTab(currentRoute.value, router);
    }
    async function getFormValue() {
      return formState
    }
    async function handleSubmit(type) {
      try {
        await formRef.value.validateFields();
        let obj = {
          ...formState,
          lngScoreDtlList: dataList.value,
          lngFileUploadList: dataFile.value
          
        }
        spinning.value = true;
        let request = !formState.id ? addLngScore :updateLngScore

        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>
