<template>
  <JModal
    :title="isEdit ? '编辑反馈' : '新增反馈'"
    :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="反馈部门" name="feedbackDeptId">
            <j-select-dept v-model:value="formData.feedbackDeptId" disabled checkStrictly @change="handleDeptChange" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="反馈人">
            <a-input :value="formData.feedbackPersonName" disabled placeholder="自动填充当前用户" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="实际完成时间" name="actualTime">
            <a-date-picker v-model:value="formData.actualTime" value-format="YYYY-MM-DD" style="width: 100%" :disabled="nonJiJianFieldsReadonly" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="进展状态" name="bpmStatus">
            <JDictSelectTag v-model:value="formData.bpmStatus" dictCode="super_status" placeholder="请选择进展状态" type="select" :disabled="nonJiJianFieldsReadonly" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="工作进展" name="workProgress" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
            <a-textarea v-model:value="formData.workProgress" :rows="3" :disabled="nonJiJianFieldsReadonly" allow-clear />
          </a-form-item>
        </a-col>
        <a-col v-if="showJiJianFields" :span="12">
          <a-form-item label="检查情况" name="inspectionStatus">
            <a-input v-model:value="formData.inspectionStatus" placeholder="填写监督检查情况" :disabled="jiJianFieldsReadonly" allow-clear />
          </a-form-item>
        </a-col>
        <a-col v-if="showJiJianFields" :span="24">
          <a-form-item label="监督意见" name="supervisoryOpinion" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
            <a-textarea v-model:value="formData.supervisoryOpinion" placeholder="是否通过审核" :rows="3" :disabled="jiJianFieldsReadonly" allow-clear />
          </a-form-item>
        </a-col>
        <a-col v-if="showJiJianFields" :span="12">
          <a-form-item label="措施数量" name="measureCount">
            <a-input-number v-model:value="formData.measureCount" 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"
              :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 { saveOrUpdate as progressSaveOrUpdate } from '../../inspectProgress/DqInspectProgress.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 },
    nonJiJianFieldsReadonly: { 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 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: '',
    feedbackDeptId: '',
    feedbackDeptName: '',
    feedbackPersonId: '',
    feedbackPersonName: '',
    actualTime: '',
    workProgress: '',
    bpmStatus: '',
    mainId: '',
    bpmProcessId: '',
    inspectionStatus: '',
    supervisoryOpinion: '',
    measureCount: undefined,
  });

  const formRules = {
    workProgress: [{ required: true, message: '请输入工作进展' }],
  };

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

  function open(mainId: string, bpmProcessId = '', defaultDeptId = '', defaultDeptName = '') {
    resetForm(mainId, bpmProcessId);
    isEdit.value = false;
    if (defaultDeptId) {
      applyCurrentUserFeedbackInfo(defaultDeptId, defaultDeptName);
    } else {
      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 fillCurrentDept() {
    const userInfo = (userStore.getUserInfo || {}) as Record<string, any>;
    let deptId = userInfo.departIds || userInfo.orgCode || '';
    let deptName = userInfo.departIds_dictText || userInfo.orgCodeTxt || '';
    // 如果 orgCodeTxt 仍为空（极少情况），从 loginInfo.departs 按 orgCode 补齐名称
    if (!deptName && deptId) {
      const loginInfo = (userStore.getLoginInfo || {}) as Record<string, any>;
      const departs = Array.isArray(loginInfo.departs) ? loginInfo.departs : [];
      console.log('【巡视整改-反馈】兜底查找, orgCode:', deptId, ', departs orgCodes:', departs.map((d: any) => d.orgCode), ', departs names:', departs.map((d: any) => d.departName));
      const matched = departs.find((d: any) => d.orgCode === deptId);
      if (matched) {
        deptId = matched.id || deptId;
        deptName = matched.departName || '';
        console.log('【巡视整改-反馈】兜底匹配成功, matched:', matched);
      }
    }
    formData.feedbackDeptId = deptId;
    formData.feedbackDeptName = deptName;
    console.log('【巡视整改-反馈】填充当前部门, deptId:', deptId, ', deptName:', deptName);
  }

  function applyCurrentUserFeedbackInfo(defaultDeptId = '', defaultDeptName = '') {
    const userInfo = (userStore.getUserInfo || {}) as Record<string, any>;
    formData.feedbackPersonId = userInfo.id || userInfo.userId || '';
    formData.feedbackPersonName = userInfo.realname || '';
    if (defaultDeptId) {
      formData.feedbackDeptId = defaultDeptId;
      formData.feedbackDeptName = defaultDeptName || '';
    } else {
      fillCurrentDept();
    }
  }

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

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

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