<template>
  <main class="safety-platform-container__main">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #attachment>
        <UploadFiles
          label="上传附件"
          ref="uploadFilesRef"
          :fileList="ruleFormData.attachment"
          @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 || []"
          @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 BasicForm from '@/components/BasicForm.vue';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import SelectGroup from '@/components/PersonGroup/SelectGroup.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { IS_PUSH } from '../constants';
  import { ElMessage } from 'element-plus';
  import { NOTICE_FORM_CONFIG, NOTICE_FORM_DATA, NOTICE_FORM_RULES } from '../configs/form';
  import type { CreateNoticeRuleForm, CreateNoticeQuery, UpdateNoticeQuery } from '../types';
  import type { FileItem } from '@/components/UploadFiles/types.ts';
  import { onMounted, ref } from 'vue';
  import UploadLoading from '@/components/UploadLoading.vue';
  import { useRouter } from 'vue-router';
  import { stringToArray, unformatAttachment, formatAttachmentList } from '@/components/UploadFiles/utils';
  import {
    getNoticeDetail,
    updateNotice,
  } from '@/api/security-confidentiality-regulation-notice/security-regulation-notice';

  const props = defineProps<{
    id: number;
  }>();

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<CreateNoticeRuleForm>(NOTICE_FORM_CONFIG, NOTICE_FORM_DATA, NOTICE_FORM_RULES);

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

  const getDetail = async () => {
    const res = await getNoticeDetail(props.id);
    ruleFormData.name = res.name;
    ruleFormData.content = res.content;
    ruleFormData.attachment = unformatAttachment(res.attachment)!;
    ruleFormData.remark = res.remark;
    ruleFormData.realname = res.creatName;
    ruleFormData.isPush = res.isPush;
    ruleFormData.userGroupList = stringToArray(res.userGroupList);
    cloneRuleFormData();
  };

  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: UpdateNoticeQuery = {
      id: props.id,
      managementType: 2,
      name: ruleFormData.name,
      content: ruleFormData.content,
      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 updateNotice(params);
      ElMessage.success('编辑成功');
      router.back();
    } catch (e) {
      console.log(e);
    } finally {
      formLoading.value = false;
    }
  };

  onMounted(() => {
    beforeRouteLeave();
    getDetail();
  });
</script>

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