<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="BgXiSpeakForm">
          <a-row :gutter="20">
            <a-col :span="24">
              <a-form-item label="习近平总书记重要讲话指示批示情况" v-bind="validateInfos.speakStatus">
                <a-input v-model:value="formData.speakStatus" placeholder="请输入重要指示批示情况" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="时间" v-bind="validateInfos.time">
                <a-date-picker placeholder="请选择时间" v-model:value="formData.time" value-format="YYYY-MM-DD" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="责任人" v-bind="validateInfos.responsiblePerson">
                <j-select-user v-model:value="formData.responsiblePerson" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="是否需要督办领导" v-bind="validateInfos.needSdwApproval">
                <a-radio-group v-model:value="formData.needSdwApproval" class="radio-group">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="24" v-if="formData.needSdwApproval === 1">
              <a-form-item label="督导领导列表" v-bind="validateInfos.sdwLeaderList">
                <j-select-user v-model:value="formData.sdwLeaderList" :multiple="true" allow-clear placeholder="请选择督导领导" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="企业负责同志批示情况" v-bind="validateInfos.elmComment">
                <a-input v-model:value="formData.elmComment" placeholder="请输入" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="学习传达研究部署情况" v-bind="validateInfos.status">
                <a-input v-model:value="formData.status" placeholder="请输入" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="牵头部门" v-bind="validateInfos.leadDepartment">
                <j-select-dept v-model:value="formData.leadDepartment" :multiple="true" checkStrictly allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="落实部门" v-bind="validateInfos.implDept">
                <j-select-dept v-model:value="formData.implDept" :multiple="true" checkStrictly allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="落实方案" v-bind="validateInfos.implPlan">
                <a-input v-model:value="formData.implPlan" placeholder="请输入" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="贯彻落实措施" v-bind="validateInfos.implMeasures">
                <a-input v-model:value="formData.implMeasures" placeholder="请输入" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="会议决策数" v-bind="validateInfos.numberOfResolutions">
                <a-input-number v-model:value="formData.numberOfResolutions" placeholder="请输入" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="落实条数" v-bind="validateInfos.implCount">
                <a-input-number v-model:value="formData.implCount" placeholder="请输入" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="已闭环数量" v-bind="validateInfos.closedCount">
                <a-input-number v-model:value="formData.closedCount" placeholder="请输入" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="落实情况" v-bind="validateInfos.implStatus">
                <a-input v-model:value="formData.implStatus" placeholder="请输入" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="报告反馈情况" v-bind="validateInfos.reportFeedbackStatus">
                <a-input v-model:value="formData.reportFeedbackStatus" placeholder="请输入" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="是否存在完成风险">
                <a-radio-group v-model:value="formData.isCompletionRisk" class="radio-group">
                  <a-radio :value="0">不存在</a-radio>
                  <a-radio :value="1">存在</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="完成状态">
                <a-radio-group v-model:value="formData.completionStatus" class="radio-group">
                  <a-radio :value="0">推进中</a-radio>
                  <a-radio :value="1">已完成</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="拖期风险应对措施" v-bind="validateInfos.delayRiskMitigation">
                <a-input v-model:value="formData.delayRiskMitigation" placeholder="请输入" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="督办次数" v-bind="validateInfos.supervisionCount">
                <a-input-number v-model:value="formData.supervisionCount" placeholder="请输入" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="父级节点" v-bind="validateInfos.pid">
                <j-tree-select
                  v-model:value="formData.pid"
                  dict="bg_xi_speak,impl_status,id"
                  pidField="pid"
                  pidValue="0"
                  hasChildField="has_child"
                  :disabled="disabled"
                />
              </a-form-item>
            </a-col>
            <a-col v-if="showFlowSubmitButton" :span="24" class="submit-area">
              <a-button preIcon="ant-design:check-outlined" style="width: 140px; height: 40px" type="primary" @click="submitForm">提 交</a-button>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, unref, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JSelectDept from '/@/components/Form/src/jeecg/components/JSelectDept.vue';
  import JSelectUser from '/@/components/Form/src/jeecg/components/JSelectUser.vue';
  import JTreeSelect from '/@/components/Form/src/jeecg/components/JTreeSelect.vue';
  import { getValueType } from '/@/utils';
  import { loadTreeData, saveOrUpdateDict } from '../BgXiSpeak.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { initBpmFormData } = usePermission();
  const useForm = Form.useForm;
  const formRef = ref();
  const expandedRowKeys = ref([]);
  const treeData = ref([]);
  const emit = defineEmits(['register', 'ok']);
  let model: Nullable<Recordable> = null;

  // 1. 初始化值修改：needSdwApproval 默认为 0
  const formData = reactive<Record<string, any>>({
    id: '',
    pid: '',
    speakStatus: '',
    time: '',
    elmComment: '',
    status: '',
    responsiblePerson: '',
    needSdwApproval: 0,
    sdwLeaderList: '',
    implPlan: '',
    leadDepartment: '',
    implMeasures: '',
    numberOfResolutions: undefined,
    implStatus: '',
    implCount: undefined,
    closedCount: undefined,
    reportFeedbackStatus: '',
    isCompletionRisk: undefined,
    delayRiskMitigation: '',
    completionStatus: undefined,
    implDept: '',
    treeDepth: undefined,
    sortOrder: undefined,
    delFlag: undefined,
    bpmStatus: undefined,
    supervisionCount: undefined,
  });

  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 6 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 18 } });
  const confirmLoading = ref<boolean>(false);

  // 2. 表单验证：明确 needSdwApproval 的验证
  const validatorRules = reactive({
    needSdwApproval: [{ required: true, message: '请选择是否需要督办领导' }],
    speakStatus: [{ required: true, message: '请输入指示批示情况' }],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true },
  });

  const disabled = computed(() => {
    if (props.formBpm === true) {
      return props.formData.disabled !== false;
    }
    return props.formDisabled;
  });

  onMounted(() => {
    initBpmFormData(props.formData);
    initFormData();
  });

  const queryByIdUrl = '/bg/xispeak/bgXiSpeak/queryById';
  async function initFormData() {
    if (props.formBpm === true && props.formData.dataId) {
      let params = { id: props.formData.dataId };
      const data = await defHttp.get({ url: queryByIdUrl, params });
      edit({ ...data });
    }
  }

  const showFlowSubmitButton = computed(() => {
    if (props.formBpm === true) {
      return props.formData.disabled === false;
    }
    return false;
  });

  function add(obj = {}) {
    edit(obj);
  }

  function edit(record) {
    nextTick(async () => {
      resetFields();
      expandedRowKeys.value = [];
      treeData.value = await loadTreeData({ async: false, pcode: '' });

      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        // 3. 赋值增强：处理后端返回 null 的情况
        if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key] === null ? (key === 'needSdwApproval' ? 0 : '') : record[key];
        }
      });

      Object.assign(formData, tmpData);
      model = { ...tmpData };
    });
  }

  function getExpandKeysByPid(pid, arr) {
    if (pid && arr && arr.length > 0) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].key == pid && unref(expandedRowKeys).indexOf(pid) < 0) {
          expandedRowKeys.value.push(arr[i].key);
          getExpandKeysByPid(arr[i]['parentId'], unref(treeData));
        } else if (arr[i].children) {
          getExpandKeysByPid(pid, arr[i].children);
        }
      }
    }
  }

  async function submitForm() {
    try {
      await validate();
    } catch ({ errorFields }) {
      if (errorFields && errorFields[0]) {
        formRef.value.scrollToField(errorFields[0].name, { behavior: 'smooth', block: 'center' });
      }
      return Promise.reject(errorFields);
    }

    // 4. 提交兜底：确保数值有效
    if (formData.needSdwApproval === undefined || formData.needSdwApproval === null) {
      formData.needSdwApproval = 0;
    }

    confirmLoading.value = true;
    const isUpdate = !!formData.id;

    // 拷贝一份数据进行转换，避免污染原始响应式对象
    const params = { ...formData };

    for (let key in params) {
      if (params[key] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, key);
        if (valueType === 'string') {
          params[key] = params[key].join(',');
        }
      }
    }

    await saveOrUpdateDict(params, isUpdate)
      .then(async (res) => {
        if (res.success) {
          await getExpandKeysByPid(params['pid'], unref(treeData));
          delete params['children'];
          emit('ok', {
            isUpdate: isUpdate,
            values: { ...params },
            expandedArr: unref(expandedRowKeys).reverse(),
            changeParent: model != null && model['pid'] != params['pid'],
          });
          createMessage.success(res.message);
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

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

<style lang="less" scoped>
  /* 保持原有样式不变 */
  .antd-modal-form {
    padding: 20px;
    .submit-area {
      text-align: center;
      padding-top: 16px;
      margin-top: 8px;
      border-top: 1px dashed #e8e8e8;
    }
    :deep(.ant-form-item-label > label) {
      font-weight: 500;
      color: #333;
    }
    :deep(.ant-radio-group.radio-group .ant-radio-wrapper) {
      margin-right: 16px;
      font-size: 14px;
    }
    :deep(.ant-input),
    :deep(.ant-input-number),
    :deep(.ant-select),
    :deep(.ant-picker) {
      border-radius: 6px;
      transition: all 0.3s ease;
      &:hover {
        border-color: #40a9ff;
      }
    }
    :deep(.ant-btn-primary) {
      height: 40px;
      padding: 0 32px;
      border-radius: 6px;
      background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
      border: none;
      font-size: 15px;
      &:hover {
        background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
      }
    }
  }
</style>
