/**
 * 通用表单配置hook
 * @param config 表单配置
 * @param data 表单数据
 * @param rules 表单规则
 * @returns initRuleFormData 初始化表单数据
 * @returns ruleFormData 表单数据
 * @returns formRules 表单规则
 * @returns cloneRuleFormData 克隆表单数据
 * @returns validateFormData 验证表单数据
 * @returns beforeRouteLeave 离开页面前的确认
 * @description 用于RuleForm的配置
 * @author Chauncey
 */
import { ref, reactive } from 'vue';
import type { FormRules } from 'element-plus';
import { cloneDeep, isEqual } from 'lodash-es';
import { onBeforeRouteLeave } from 'vue-router';
import { ElMessageBox } from 'element-plus';
import type { FormConfig } from '@/types/basic-form';
export const useFormConfigHook = <T extends Record<string, any> = Record<string, any>>(
  config: FormConfig[],
  data: T,
  rules: FormRules<T>,
) => {
  const ruleFormConfig = reactive<FormConfig[]>(config);
  const ruleFormData = reactive<T>(cloneDeep(data));
  const initRuleFormData = ref<T>();
  const formRules = reactive<FormRules<T>>(rules);
  const cloneRuleFormData = () => {
    initRuleFormData.value = cloneDeep(ruleFormData as T);
  };
  const hasFormChanged = () => {
    return isEqual(initRuleFormData.value, ruleFormData);
  };
  const beforeRouteLeave = () => {
    onBeforeRouteLeave((to, from, next) => {
      const hasChange = hasFormChanged();
      if (hasChange) {
        next();
        return;
      }
      setTimeout(() => {
        ElMessageBox.confirm('当前页面存在修改，是否确认离开当前页面？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
        })
          .then(() => {
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    });
  };
  return {
    ruleFormConfig,
    ruleFormData,
    formRules,
    cloneRuleFormData,
    beforeRouteLeave,
  };
};
