<template>
  <JModal
    :title="modalTitle"
    :width="820"
    :visible="visible"
    :confirmLoading="saving"
    okText="保存"
    cancelText="取消"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-alert v-if="!isEdit" message="可以多次添加反馈信息" type="info" showIcon style="margin-bottom: 12px" />
    <a-form
      ref="formRef"
      class="bpm-feedback-modal-form"
      :model="formData"
      :rules="formRules"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
    >
      <a-row :gutter="16">
<!--        <a-col :span="12">-->
<!--          <a-form-item label="责任部门ID" name="responDeptid">-->
<!--            <a-input v-model:value="formData.responDeptid" allow-clear />-->
<!--          </a-form-item>-->
<!--        </a-col>-->
<!--        <a-col :span="12">-->
<!--          <a-form-item label="责任部门名称" name="responDeptname">-->
<!--            <a-input v-model:value="formData.responDeptname" allow-clear />-->
<!--          </a-form-item>-->
<!--        </a-col>-->
<!--        <a-col :span="12">-->
<!--          <a-form-item label="反馈人ID" name="responPersonid">-->
<!--            <a-input v-model:value="formData.responPersonid" allow-clear />-->
<!--          </a-form-item>-->
<!--        </a-col>-->
<!--        <a-col :span="12">-->
<!--          <a-form-item label="反馈人姓名" name="responPersonname">-->
<!--            <a-input v-model:value="formData.responPersonname" allow-clear />-->
<!--          </a-form-item>-->
<!--        </a-col>-->
        <a-col :span="24">
          <a-tooltip :title="isEdit ? '' : '该信息后续不可编辑，请谨慎填写'">
            <a-form-item label="计划完成目标" name="planExect" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
              <a-textarea v-model:value="formData.planExect" :rows="3" :disabled="isEdit" allow-clear />
            </a-form-item>
          </a-tooltip>
        </a-col>
        <a-col :span="24">
          <a-tooltip :title="isEdit ? '' : '该信息后续不可编辑，请谨慎填写'">
            <a-form-item label="计划完成日期" name="planTime" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
              <a-date-picker v-model:value="formData.planTime" value-format="YYYY-MM-DD" style="width: 100%" :disabled="isEdit" allow-clear />
            </a-form-item>
          </a-tooltip>
        </a-col>
        <a-col :span="24">
          <a-form-item label="完成状态" name="bpmStatus" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
            <JDictSelectTag v-model:value="formData.bpmStatus" dictCode="feedback_status" placeholder="请选择完成状态" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="实际完成日期" name="actualTime" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
            <a-date-picker v-model:value="formData.actualTime" value-format="YYYY-MM-DD" placeholder="请选择实际完成日期" style="width: 100%" :disabled="isEdit" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="实际执行情况" name="actualExect" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
            <a-textarea v-model:value="formData.actualExect" :rows="4" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="附件" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
            <SUploadFile
              :key="uploadKey"
              ref="uploadFileRef"
              :bussiness-id="formData.id"
              :bussiness-secret-level="uploadSecretLevel"
              :multiple="true"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </JModal>
</template>

<script lang="ts" setup>
  import { nextTick, reactive, ref } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JModal from '/@/components/Modal/src/JModal/JModal.vue';
  import { bgPartymatterFeedbackSaveOrUpdate } from '../BgPartymatter.api';
  import { useUserStore } from '/@/store/modules/user';
  import { buildUUID } from '/@/utils/uuid';
  import SUploadFile from '/@/components/semri/fileComponent/SUploadFile.vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';

  const emit = defineEmits(['success']);
  const { createMessage } = useMessage();
  const userStore = useUserStore();
  const DEFAULT_COMPLETED_STATUS = '2';

  const visible = ref(false);
  const saving = ref(false);
  const isEdit = ref(false);
  const modalTitle = ref('新增反馈');
  const formRef = ref();
  const uploadFileRef = ref<InstanceType<typeof SUploadFile> | null>(null);
  const uploadSecretLevel = ref(1);
  const uploadKey = ref(0);
  const labelCol = { xs: { span: 24 }, sm: { span: 7 } };
  const wrapperCol = { xs: { span: 24 }, sm: { span: 17 } };
  const wideLabelCol = { xs: { span: 24 }, sm: { span: 3 } };
  const wideWrapperCol = { xs: { span: 24 }, sm: { span: 21 } };

  const formData = reactive<Record<string, any>>({
    id: '',
    responDeptid: '',
    responDeptname: '',
    responPersonid: '',
    responPersonname: '',
    planExect: '',
    planTime: '',
    actualExect: '',
    actualTime: '',
    bpmStatus: '',
    bpmProcessId: '',
    mainId: '',
  });

  const formRules = {
    planExect: [{ required: true, message: '请输入计划完成目标' }],
    planTime: [{ required: true, message: '请选择计划完成日期' }],
  };

  function resetForm(mainId = '', bpmProcessId = '') {
    Object.keys(formData).forEach((key) => {
      formData[key] = '';
    });
    formData.mainId = mainId;
    formData.bpmProcessId = bpmProcessId;
    uploadKey.value += 1;
    nextTick(() => formRef.value?.clearValidate?.());
  }

  function open(mainId: string, secretLevel?: string | number, bpmProcessId = '', record?: Record<string, any>) {
    resetForm(mainId, bpmProcessId);
    uploadSecretLevel.value = normalizeSecretLevel(secretLevel);
    if (record?.id) {
      isEdit.value = true;
      modalTitle.value = '编辑反馈';
      Object.keys(formData).forEach((key) => {
        if (Object.prototype.hasOwnProperty.call(record, key)) {
          formData[key] = record[key] ?? '';
        }
      });
      formData.mainId = formData.mainId || mainId;
      formData.bpmProcessId = formData.bpmProcessId || bpmProcessId;
    } else {
      isEdit.value = false;
      modalTitle.value = '新增反馈';
      // 新增反馈默认按“已完成”处理，时间取打开弹窗时刻，编辑已有记录不覆盖。
      formData.bpmStatus = DEFAULT_COMPLETED_STATUS;
      void applyCurrentUserFeedbackInfo();
    }
    visible.value = true;
  }

  function normalizeSecretLevel(value?: string | number) {
    const level = Number(value);
    return [1, 2, 3, 4].includes(level) ? level : 1;
  }

  function getCurrentLoginDepart() {
    const userInfo = (userStore.getUserInfo || {}) as Record<string, any>;
    const loginInfo = (userStore.getLoginInfo || {}) as Record<string, any>;
    const departs = Array.isArray(loginInfo.departs) ? loginInfo.departs : [];
    if (userInfo.orgCode) {
      return departs.find((item) => item.orgCode === userInfo.orgCode);
    }
    return departs.length === 1 ? departs[0] : undefined;
  }

  async function getCurrentDepartInfo() {
    const userInfo = (userStore.getUserInfo || {}) as Record<string, any>;
    const loginDepart = getCurrentLoginDepart();
    if (loginDepart) {
      return {
        id: loginDepart.id || '',
        departName: loginDepart.departName || '',
      };
    }
    if (userInfo.orgCode) {
      const depart = await defHttp.get({ url: '/sys/sysDepart/getDepartName', params: { orgCode: userInfo.orgCode } });
      return {
        id: depart?.id || '',
        departName: depart?.departName || '',
      };
    }
    return {
      id: userInfo.departIds || '',
      departName: userInfo.departIds_dictText || userInfo.orgCodeTxt || '',
    };
  }

  async function applyCurrentUserFeedbackInfo() {
    const userInfo = (userStore.getUserInfo || {}) as Record<string, any>;
    formData.responPersonid = userInfo.id || userInfo.userId || '';
    formData.responPersonname = userInfo.realname || '';
    const departInfo = await getCurrentDepartInfo();
    formData.responDeptid = departInfo.id;
    formData.responDeptname = departInfo.departName;
  }

  function handleCancel() {
    visible.value = false;
  }

  async function handleOk() {
    try {
      await formRef.value?.validate?.();
    } catch {
      return;
    }
    saving.value = true;
    try {
      const isUpdate = !!formData.id;
      if (!isUpdate) {
        await applyCurrentUserFeedbackInfo();
      }
      if (!isUpdate && uploadFileRef.value?.hasPendingFiles?.()) {
        formData.id = buildUUID();
      }
      const res = await bgPartymatterFeedbackSaveOrUpdate({ ...formData }, isUpdate);
      if (res.success) {
        if (formData.id && uploadFileRef.value?.hasPendingFiles?.()) {
          await uploadFileRef.value.bindBussinessId(formData.id);
        }
        createMessage.success(res.message || '保存成功');
        visible.value = false;
        emit('success');
      } else {
        createMessage.warning(res.message || '保存失败');
      }
    } finally {
      saving.value = false;
    }
  }

  defineExpose({
    open,
  });
</script>

<style lang="less" scoped>
  .bpm-feedback-modal-form {
    padding: 12px 8px 0;
  }
</style>
