<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" labelAlign="left" :labelCol="labelCol" :wrapperCol="wrapperCol" name="BgXiSpeakForm">
          <!-- 基本信息 -->
          <a-divider orientation="left" plain>基本信息</a-divider>
          <a-row :gutter="[16, 0]">
            <a-col :span="24">
              <a-form-item
                label="重要讲话指示批示"
                v-bind="validateInfos.speakStatus"
                id="BgXiSpeakForm-speakStatus"
                name="speakStatus"
                :labelCol="{ xs: { span: 24 }, sm: { span: 3 } }"
                :wrapperCol="{ xs: { span: 24 }, sm: { span: 21 } }"
              >
                <a-textarea v-model:value="formData.speakStatus" :rows="3" placeholder="请输入习近平总书记重要讲话指示批示情况" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="时间" v-bind="validateInfos.time" id="BgXiSpeakForm-time" name="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="12">
              <a-form-item label="企业负责同志批示情况" v-bind="validateInfos.elmComment" id="BgXiSpeakForm-elmComment" name="elmComment">
                <a-input v-model:value="formData.elmComment" placeholder="请输入企业负责同志批示情况" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="学习传达研究部署" v-bind="validateInfos.status" id="BgXiSpeakForm-status" name="status">
                <a-input v-model:value="formData.status" placeholder="请输入学习传达研究部署情况" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="密级" v-bind="validateInfos.secretLevel" id="BgXiSpeakForm-secretLevel" name="secretLevel">
                <j-dict-select-tag v-model:value="formData.secretLevel" dictCode="secret_level" placeholder="请选择密级" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="责任人" v-bind="validateInfos.responsiblePerson" id="BgXiSpeakForm-responsiblePerson" name="responsiblePerson">
                <j-select-user v-model:value="formData.responsiblePerson" placeholder="请从所党委选择责任人" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="牵头部门" v-bind="validateInfos.implDept" id="BgXiSpeakForm-implDept" name="implDept">
                <j-select-dept v-model:value="formData.implDept" :multiple="true" placeholder="请选择牵头部门" checkStrictly allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="贯彻落实措施" v-bind="validateInfos.implMeasures" id="BgXiSpeakForm-implMeasures" name="implMeasures">
                <a-input v-model:value="formData.implMeasures" placeholder="来源于党委会抄告" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="会议决策数" v-bind="validateInfos.numberOfResolutions" id="BgXiSpeakForm-numberOfResolutions" name="numberOfResolutions">
                <a-input-number v-model:value="formData.numberOfResolutions" placeholder="请输入会议决策数" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否需要督办领导" v-bind="validateInfos.needSdwApproval" id="BgXiSpeakForm-needSdwApproval" name="needSdwApproval">
                <a-radio-group v-model:value="formData.needSdwApproval">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col v-if="formData.needSdwApproval === 1" :span="12">
              <a-form-item label="督办领导列表" v-bind="validateInfos.sdwLeaderList" id="BgXiSpeakForm-sdwLeaderList" name="sdwLeaderList">
                <j-select-user v-model:value="formData.sdwLeaderList" :multiple="true" allow-clear placeholder="请选择督办领导" />
              </a-form-item>
            </a-col>
          </a-row>

          <!-- 状态与统计 -->
          <a-divider orientation="left" plain>状态与统计</a-divider>
          <a-row :gutter="[16, 0]">
            <a-col :span="12">
              <a-form-item label="指定落实措施条数" v-bind="validateInfos.implCount" id="BgXiSpeakForm-implCount" name="implCount">
                <a-input-number v-model:value="formData.implCount" placeholder="每增加一条反馈数量加1" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="措施已闭环数量" v-bind="validateInfos.closedCount" id="BgXiSpeakForm-closedCount" name="closedCount">
                <a-input-number v-model:value="formData.closedCount" placeholder="完成反馈全流程后增加" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="报告反馈情况" v-bind="validateInfos.reportFeedbackStatus" id="BgXiSpeakForm-reportFeedbackStatus" name="reportFeedbackStatus">
                <a-input v-model:value="formData.reportFeedbackStatus" placeholder="请输入" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="完成状态" v-bind="validateInfos.completionStatus" id="BgXiSpeakForm-completionStatus" name="completionStatus">
                <JDictSelectTag v-model:value="formData.completionStatus" dictCode="db_status" placeholder="请选择完成状态" type="radio" :stringToNumber="true" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="截止日期" v-bind="validateInfos.deadline" id="BgXiSpeakForm-deadline" name="deadline">
                <a-date-picker placeholder="请选择截止日期" v-model:value="formData.deadline" value-format="YYYY-MM-DD" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="督办次数" v-bind="validateInfos.supervisionCount" id="BgXiSpeakForm-supervisionCount" name="supervisionCount">
                <a-input-number v-model:value="formData.supervisionCount" placeholder="每次发起督办流程自动加1" style="width: 100%" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-col v-if="showFlowSubmitButton" :span="24" style="width: 100%; text-align: center; margin-top: 16px;">
            <a-button preIcon="ant-design:check-outlined" style="width: 126px" type="primary" @click="submitForm">提 交</a-button>
          </a-col>
        </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 JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.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;

  const formData = reactive<Record<string, any>>({
    id: '',
    pid: '',
    speakStatus: '',
    time: '',
    elmComment: '经单位主要负责同时签批同意，由xx部做好贯彻落实',
    status: 'x月x日召开xxxx年第x次党委会议',
    secretLevel: '',
    responsiblePerson: '',
    needSdwApproval: 0,
    sdwLeaderList: '',
    implPlan: '',
    implMeasures: '',
    numberOfResolutions: undefined,
    implStatus: '',
    implCount: undefined,
    closedCount: undefined,
    reportFeedbackStatus: '',
    isCompletionRisk: undefined,
    delayRiskMitigation: '',
    completionStatus: undefined,
    deadline: '',
    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);

  const validatorRules = reactive({
    speakStatus: [{ required: true, message: '请输入重要讲话指示批示情况' }],
    time: [{ required: true, message: '请选择时间' }],
    elmComment: [{ required: true, message: '请输入企业负责同志批示情况' }],
    status: [{ required: true, message: '请输入学习传达研究部署情况' }],
    secretLevel: [{ required: true, message: '请选择密级' }],
    responsiblePerson: [{ required: true, message: '请选择责任人' }],
    needSdwApproval: [{ required: true, message: '请选择是否需要督办领导' }],
    implMeasures: [{ required: true, message: '请输入贯彻落实措施' }],
    numberOfResolutions: [{ required: true, message: '请输入会议决策数' }],
    reportFeedbackStatus: [{ required: true, message: '请输入报告反馈情况' }],
    completionStatus: [{ required: true, message: '请选择完成状态' }],
    deadline: [{ required: true, message: '请选择截止日期' }],
    implDept: [{ 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;
  });

  async function add(obj = {}) {
    treeData.value = await loadTreeData({ async: false, pcode: '' });
    edit(obj);
  }

  function edit(record) {
    nextTick(async () => {
      resetFields();
      expandedRowKeys.value = [];

      // 非BPM模式且有ID时，从API查询完整数据，避免列表行数据不完整导致字段不显示
      let data = record;
      if (record.id && !props.formBpm) {
        try {
          const res = await defHttp.get({ url: queryByIdUrl, params: { id: record.id } });
          data = res || record;
        } catch {
          data = record;
        }
      }

      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (data.hasOwnProperty(key)) {
          tmpData[key] = data[key] === null ? (key === 'needSdwApproval' ? 0 : '') : data[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);
    }

    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: 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>
