<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form class="antd-modal-form" v-bind="formItemLayout" ref="formRef" name="FixedContact20260730FeedbackForm">
          <a-row>
            <a-col :span="12">
              <a-form-item label="计划完成时间" v-bind="validateInfos.planFinishTime" id="FixedContact20260730FeedbackForm-planFinishTime" name="planFinishTime">
                <a-date-picker v-model:value="formData.planFinishTime" value-format="YYYY-MM-DD" placeholder="请选择计划完成时间" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="计划完成情况" v-bind="validateInfos.planFinishStatus" id="FixedContact20260730FeedbackForm-planFinishStatus" name="planFinishStatus">
                <a-textarea v-model:value="formData.planFinishStatus" placeholder="请输入计划完成情况" :rows="3" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="处理意见、承办情况" v-bind="validateInfos.handleOpinion" id="FixedContact20260730FeedbackForm-handleOpinion" name="handleOpinion">
                <a-textarea v-model:value="formData.handleOpinion" placeholder="请输入处理意见、承办情况" :rows="3" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="办结情况" v-bind="validateInfos.finishStatus" id="FixedContact20260730FeedbackForm-finishStatus" name="finishStatus">
                <a-textarea v-model:value="formData.finishStatus" placeholder="请输入办结情况" :rows="3" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="实际完成时间" v-bind="validateInfos.actualFinishTime" id="FixedContact20260730FeedbackForm-actualFinishTime" name="actualFinishTime">
                <a-date-picker v-model:value="formData.actualFinishTime" value-format="YYYY-MM-DD" placeholder="请选择实际完成时间" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="实际完成情况" v-bind="validateInfos.actualFinishStatus" id="FixedContact20260730FeedbackForm-actualFinishStatus" name="actualFinishStatus">
                <a-input v-model:value="formData.actualFinishStatus" placeholder="请输入实际完成情况" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="反馈人" v-bind="validateInfos.feedbackUser" id="FixedContact20260730FeedbackForm-feedbackUser" name="feedbackUser">
                <SzSelectUser v-model:value="formData.feedbackUser" placeholder="请选择反馈人" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="反馈部门" v-bind="validateInfos.feedbackDept" id="FixedContact20260730FeedbackForm-feedbackDept" name="feedbackDept">
                <SzSelectDept v-model:value="formData.feedbackDept" placeholder="请选择反馈部门" allow-clear />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, inject, defineProps, unref, computed } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import SzSelectDept from '/@/components/Form/src/jeecg/components/SzSelectDept.vue';
  import SzSelectUser from '/@/components/semri/userComponent/SzUserSelect.vue';
  import { useUserStore } from '/@/store/modules/user';

  const mainId = inject('mainId');
  const formRef = ref();
  const useForm = Form.useForm;
  const userStore = useUserStore();
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    planFinishTime: '',
    planFinishStatus: '',
    handleOpinion: '',
    finishStatus: '',
    actualFinishTime: '',
    actualFinishStatus: '',
    feedbackUser: '',
    feedbackDept: '',
    fixedContact20260730Id: '',
  });
  const { createMessage } = useMessage();
  const confirmLoading = ref<boolean>(false);
  const validatorRules = {};
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const props = defineProps({
    disabled: { type: Boolean, default: false },
  });
  const disabled = computed(() => props.disabled);
  const formItemLayout = {
    labelCol: { xs: { span: 24 }, sm: { span: 6 } },
    wrapperCol: { xs: { span: 24 }, sm: { span: 18 } },
  };

  function add() {
    edit({});
    nextTick(() => {
      applyCurrentUserFeedbackInfo();
    });
  }

  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key];
        }
      });
      Object.assign(formData, tmpData);
    });
  }

  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;
  }

  function applyCurrentUserFeedbackInfo() {
    const userInfo = (userStore.getUserInfo || {}) as Record<string, any>;
    formData.feedbackUser = userInfo.id || userInfo.userId || '';
    const loginDepart = getCurrentLoginDepart();
    if (loginDepart) {
      formData.feedbackDept = loginDepart.id || '';
    }
  }

  async function submitForm() {
    try {
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    if (!isUpdate.value) {
      applyCurrentUserFeedbackInfo();
    }
    for (let data in model) {
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    if (unref(mainId)) {
      model['fixedContact20260730Id'] = unref(mainId);
    }
    // feedback save uses the same saveOrUpdate but differently
    const isUpdateVal = isUpdate.value;
    const saveUrl = isUpdateVal ? '/bg/fixcontact/fixedContact20260730/edit' : '/bg/fixcontact/fixedContact20260730/add';
    await defHttp.post({ url: saveUrl, params: model }, { isTransformResponse: false })
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
