<template>
  <JModal
    :title="isEdit ? '编辑反馈' : '新增反馈'"
    :width="820"
    :visible="visible"
    :confirmLoading="saving"
    okText="保存"
    cancelText="取消"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <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="反馈部门" name="responDeptid">
            <j-select-dept v-model:value="formData.responDeptid" :multiple="true" checkStrictly allow-clear @change="handleDeptChange" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="反馈人">
            <a-input :value="formData.responPersonname" disabled placeholder="自动填充当前用户" />
          </a-form-item>
        </a-col>
        <!--        <a-col :span="12">-->
        <!--          <a-form-item label="序号" name="num">-->
        <!--            <a-input-number v-model:value="formData.num" style="width: 100%" allow-clear />-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->

        <a-col :span="24">
          <a-form-item label="具体措施" name="method" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
            <a-textarea v-model:value="formData.method" :rows="3" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="完成期限" name="deadline">
            <a-date-picker v-model:value="formData.deadline" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="成果形式" name="outcomeForm">
            <a-input v-model:value="formData.outcomeForm" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="完成状态" name="completionStatus">
            <JDictSelectTag v-model:value="formData.completionStatus" dictCode="measure_complete_status" placeholder="请选择完成状态" type="select" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否有报送上级报告" name="isReportedToHigher">
            <JDictSelectTag v-model:value="formData.isReportedToHigher" dictCode="need_report_higher" placeholder="请选择" type="select" allow-clear />
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="进展情况" name="progress" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
            <a-textarea v-model:value="formData.progress" :rows="3" allow-clear />
          </a-form-item>
        </a-col>
        <!--        <a-col :span="24">-->
        <!--          <a-form-item label="落实情况" name="implStatus" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">-->
        <!--            <a-textarea v-model:value="formData.implStatus" :rows="3" allow-clear />-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->
<!--        <a-col :span="24">-->
<!--          <a-form-item label="落实计划" name="completionPlan" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">-->
<!--            <a-textarea v-model:value="formData.completionPlan" :rows="3" allow-clear />-->
<!--          </a-form-item>-->
<!--        </a-col>-->
        <a-col v-if="showJiJianFields" :span="12">
          <a-form-item label="检查情况(纪检)" name="checkStatus">
            <a-input v-model:value="formData.checkStatus" placeholder="填写监督检查情况，成果是否完整，符合，时间是否按时等" :disabled="jiJianFieldsReadonly" allow-clear />
          </a-form-item>
        </a-col>
        <a-col v-if="showJiJianFields" :span="24">
          <a-form-item label="监督意见(纪检)" name="inspectionAdvice" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
            <a-textarea v-model:value="formData.inspectionAdvice" placeholder="是否通过审核" :rows="3" :disabled="jiJianFieldsReadonly" allow-clear />
          </a-form-item>
        </a-col>
        <a-col v-if="showJiJianFields" :span="12">
          <a-form-item label="措施数量(纪检)" name="measureNum">
            <a-input-number v-model:value="formData.measureNum" placeholder="填写本条举措设计的措施数量" style="width: 100%" :disabled="jiJianFieldsReadonly" 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 { useMessage } from '/@/hooks/web/useMessage';
  import JModal from '/@/components/Modal/src/JModal/JModal.vue';
  import { bgXiSpeakFeedbackSaveOrUpdate } from '../BgXiSpeak.api';
  import { useUserStore } from '/@/store/modules/user';
  import { buildUUID } from '/@/utils/uuid';
  import SUploadFile from '/@/components/semri/fileComponent/SUploadFile.vue';
  import JSelectDept from '/@/components/Form/src/jeecg/components/JSelectDept.vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';

  const emit = defineEmits(['success']);
  const props = defineProps({
    showJiJianFields: { type: Boolean, default: false },
    jiJianFieldsReadonly: { type: Boolean, default: false },
  });
  const { createMessage } = useMessage();
  const userStore = useUserStore();

  const visible = ref(false);
  const saving = ref(false);
  const isEdit = ref(false);
  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: '',
    implStatus: '',
    completionStatus: '',
    isReportedToHigher: undefined,
    completionPlan: '',
    mainId: '',
    bpmProcessId: '',
    num: undefined,
    method: '',
    deadline: '',
    outcomeForm: '',
    progress: '',
    sumMethodNum: '',
    checkStatus: '',
    inspectionAdvice: '',
    measureNum: undefined,
    launchType: undefined,
    intervalType: undefined,
    startCount: undefined,
    startTime: '',
  });

  const formRules = {
    progress: [{ required: true, message: '请输入进展情况' }],
    completionStatus: [{ required: true, message: '请选择完成状态' }],
  };

  function resetForm(mainId = '', bpmProcessId = '') {
    Object.keys(formData).forEach((key) => {
      if (key === 'num' || key === 'measureNum' || key === 'launchType' || key === 'intervalType' || key === 'startCount') {
        formData[key] = undefined;
      } else {
        formData[key] = '';
      }
    });
    formData.mainId = mainId;
    formData.bpmProcessId = bpmProcessId;
    uploadKey.value += 1;
    nextTick(() => formRef.value?.clearValidate?.());
  }

  function open(mainId: string, secretLevel?: string | number, bpmProcessId = '', defaultDeptId = '', defaultDeptName = '') {
    resetForm(mainId, bpmProcessId);
    isEdit.value = false;
    uploadSecretLevel.value = normalizeSecretLevel(secretLevel);
    if (defaultDeptId) {
      void applyCurrentUserFeedbackInfo(defaultDeptId, defaultDeptName);
    } else {
      void applyCurrentUserFeedbackInfo();
    }
    visible.value = true;
  }

  function openEdit(record: Record<string, any>) {
    resetForm(record.mainId || '', record.bpmProcessId || '');
    isEdit.value = true;
    Object.keys(formData).forEach((key) => {
      if (record[key] !== undefined) {
        formData[key] = record[key];
      }
    });
    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 || '',
      };
    }
    return {
      id: userInfo.departIds || '',
      departName: userInfo.departIds_dictText || userInfo.orgCodeTxt || '',
    };
  }

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

  function handleDeptChange(value, row) {
    if (row) {
      formData.responDeptname = row.name || '';
    }
  }

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

  async function handleOk() {
    try {
      await formRef.value?.validate?.();
    } catch {
      return;
    }
    saving.value = true;
    try {
      if (!formData.id && uploadFileRef.value?.hasPendingFiles?.()) {
        formData.id = buildUUID();
      }
      const res = await bgXiSpeakFeedbackSaveOrUpdate({ ...formData }, isEdit.value);
      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,
    openEdit,
  });
</script>

<style lang="less" scoped>
  .bpm-feedback-modal-form {
    padding: 14px;

    :deep(.ant-form-item-label) {
      overflow: visible;
      white-space: normal;
      text-overflow: unset;
      text-align: left;

      > label {
        justify-content: flex-start;
        width: 100%;
      }
    }
  }
</style>
