<template>
  <JModal
    title="新增反馈"
    :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="责任部门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="12">
          <a-form-item label="完成状态" name="bpmStatus">
            <a-input v-model:value="formData.bpmStatus" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="实际完成时间" name="actualTime">
            <a-date-picker v-model:value="formData.actualTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" 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-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';

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

  const visible = ref(false);
  const saving = ref(false);
  const formRef = ref();
  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: '',
    actualExect: '',
    actualTime: '',
    bpmStatus: '',
    mainId: '',
  });

  const formRules = {
    actualExect: [{ required: true, message: '请输入实际执行情况' }],
  };

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

  function open(mainId: string) {
    resetForm(mainId);
    void applyCurrentUserFeedbackInfo();
    visible.value = true;
  }

  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 {
      await applyCurrentUserFeedbackInfo();
      const res = await bgPartymatterFeedbackSaveOrUpdate({ ...formData }, false);
      if (res.success) {
        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>
