<template>
  <main class="safety-platform-container__main">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #attachment>
        <UploadFiles label="上传附件" ref="uploadFilesRef" @uploadSuccess="handleUploadSuccess" />
      </template>
      <template #isPush>
        <el-radio-group v-model="ruleFormData.isPush">
          <el-radio :value="IS_PUSH.PUSH">是</el-radio>
          <el-radio :value="IS_PUSH.NOT_PUSH">否</el-radio>
        </el-radio-group>
        <SelectGroup
          v-if="ruleFormData.isPush === IS_PUSH.PUSH"
          ref="selectGroupRef"
          :userGroupList="ruleFormData.userGroupList as number[] || []"
          @userGroupListChange="handleUserGroupListChange"
        />
      </template>
    </BasicForm>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">取消</el-button>
    <el-button type="primary" @click="handleSubmit">提交</el-button>
  </footer>
  <UploadLoading :form-loading="formLoading" v-if="formLoading" />
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BasicForm from '@/components/BasicForm.vue';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import SelectGroup from '@/components/PersonGroup/SelectGroup.vue';
  import UploadLoading from '@/components/UploadLoading.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import { IS_PUSH } from '../constants';
  import { createRegulation } from '@/api/security-confidentiality-regulation-notice/confidentiality-regulation-notice';
  import { REGULATION_FORM_CONFIG, REGULATION_FORM_DATA, REGULATION_FORM_RULES } from '../configs/form';
  import type { CreateRegulationRuleForm, CreateRegulationQuery } from '../types';
  import type { FileItem } from '@/components/UploadFiles/types.ts';
  import { formatAttachmentList } from '@/components/UploadFiles/utils';

  const { realname } = useUserInfoHook();

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<CreateRegulationRuleForm>(REGULATION_FORM_CONFIG, REGULATION_FORM_DATA, REGULATION_FORM_RULES);

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const selectGroupRef = ref<InstanceType<typeof SelectGroup>>();

  const handleUserGroupListChange = (userGroupList: number[]) => {
    ruleFormData.userGroupList = userGroupList;
  };

  const handleUploadSuccess = (fileList: FileItem[]) => {
    ruleFormData.attachment = fileList;
  };

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const parentValidateResult = await basicFormRef.value.validateForm();
    let childValidateResult = true;
    if (selectGroupRef.value) {
      childValidateResult = (await selectGroupRef.value.validateForm()) as boolean;
    }
    return parentValidateResult && childValidateResult;
  };

  const getFormData = async () => {
    if (!ruleFormData.isPush) {
      ruleFormData.userGroupList = [];
    }
    cloneRuleFormData();
    const res: CreateRegulationQuery = {
      managementType: 1,
      name: ruleFormData.name,
      attachment: JSON.stringify(await formatAttachmentList(ruleFormData.attachment)),
      isPush: ruleFormData.isPush,
      userGroupList: ruleFormData.userGroupList?.join(','),
      remark: ruleFormData.remark,
      effectState: 0,
    };
    return res;
  };

  const formLoading = ref(false);
  const router = useRouter();
  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      formLoading.value = true;
      const params = await getFormData();
      await createRegulation(params);
      ElMessage.success('创建成功');
      router.back();
    } catch (e) {
      console.log(e);
    } finally {
      formLoading.value = false;
    }
  };

  onMounted(() => {
    ruleFormData.realname = realname;
    cloneRuleFormData();
    beforeRouteLeave();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
</style>
