<template>
  <div class="step4">
    <div class="w-3/4 mx-auto">
      <BasicForm @register="register" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, inject, computed } from "vue";
import { BasicForm, FormSchema, useForm } from "/@/components/Form/index";

import { debounce } from "lodash-es";
import { GeneratorConfig } from "/@/model/generator/generatorConfig";
import { useMessage } from "/@/hooks/web/useMessage";

import { getAuthList } from "/@/api/system/authorize";
import { useI18n } from "/@/hooks/web/useI18n";
const props = defineProps({
  //是否是编辑状态
  isUpdate: {
    type: Boolean,
    default: false,
  },
});
const { t } = useI18n();
const { notification } = useMessage();

const dataAuthPlaceholder = computed(() => {
  return generatorConfig!.outputConfig!.isDataAuth
    ? t("请选择已有通用数据权限")
    : t("请先启用数据权限");
});
const dataAuthHelpMessage = `
      1.启用数据权限会判断主表是否包含RuleUserlD字段如果存在，则不进行表结构修改，如果不存在，则会对主表进行字段添加。
      2.RuleUserlD主要用来控制每一条记录的权限所属人新增时，默认将当前登录认作为权限所属人。
      3.在表单设计中会添加“批量设置权限所属人”功能启用后，拥有该按钮权限的人员可以设置每一条记录的权限所属人。
        `;

const formSchemaData: FormSchema[] = [
  {
    field: "formName",
    label: t("表单名称"),

    component: "Input",
    colProps: {
      span: 12,
    },
    componentProps: {
      placeholder: t("请输入表单名称"),
      onChange: (val: ChangeEvent) => {
        generatorConfig!.outputConfig!.formName = val.target.value;
      },
    },
    dynamicRules: () => {
      return [{ required: generatorConfig!.outputConfig!.isSystemForm ? false : true }];
    },
    dynamicDisabled: () => {
      return generatorConfig!.outputConfig!.isSystemForm ? true : false;
    },
  },
  {
    field: "formCategory",
    label: t("表单分类"),
    component: "DicSelect",
    dynamicRules: () => {
      return [{ required: generatorConfig!.outputConfig!.isSystemForm ? false : true }];
    },
    dynamicDisabled: () => {
      return generatorConfig!.outputConfig!.isSystemForm ? true : false;
    },
    componentProps: {
      placeholder: t("请选择表单分类"),
      itemId: "1419276800524424444",
      isShowAdd: false,
      onChange: (id) => {
        generatorConfig!.outputConfig!.formCategory = id;
        clearValidate();
      },
    },
    colProps: { span: 12 },
  },
  {
    field: "isSystemForm",
    label: "转为系统表单",
    component: "Switch",
    required: false,
    colProps: { span: 12 },
    helpComponentProps: { maxWidth: "400px" },
    componentProps: {
      checkedValue: true,
      unCheckedValue: false,
      onChange: (val) => {
        generatorConfig!.outputConfig!.isSystemForm = val;
      },
    },
    dynamicDisabled: () => {
      return props.isUpdate ? true : false;
    },
  },
  {
    field: "className",
    label: t("功能名称"),
    required: true,
    component: "Input",
    colProps: { span: 12 },
    componentProps: {
      placeholder: t("请填写功能名称"),
      onChange: (val: ChangeEvent) => {
        generatorConfig!.outputConfig!.className = val.target.value;
      },
    },
    ifShow: () => {
      return generatorConfig!.outputConfig!.isSystemForm;
    },
  },
  {
    field: "comment",
    label: t("功能描述"),
    required: true,
    component: "Input",
    colProps: { span: 12 },
    componentProps: {
      placeholder: t("请填写功能描述"),
      onChange: (val: ChangeEvent) => {
        generatorConfig!.outputConfig!.comment = val.target.value;
      },
    },
    ifShow: () => {
      return generatorConfig!.outputConfig!.isSystemForm;
    },
  },
  {
    field: "outputArea",
    label: t("功能模块"),
    component: "DicSelect",
    required: true,
    componentProps: {
      placeholder: t("请选择功能模块"),
      itemId: "1419276800524423333",
      onChange: debounce((_, obj) => {
        if (obj) {
          generatorConfig!.outputConfig!.outputArea = obj.id;
          generatorConfig!.outputConfig!.outputValue = obj.value;
        }
      }, 200),
      getPopupContainer: () => document.body,
    },
    colProps: { span: 12 },
    ifShow: () => {
      return generatorConfig!.outputConfig!.isSystemForm;
    },
  },
  {
    field: "remarks",
    label: t("备注"),
    component: "Input",
    required: false,
    colProps: { span: 12 },
    componentProps: {
      placeholder: t("请填写备注"),
      onChange: (val) => {
        generatorConfig!.outputConfig!.remarks = val.target.value;
      },
    },
  },
  {
    field: "isDataAuth",
    label: t("数据权限"),
    component: "Switch",
    required: false,
    colProps: { span: 12 },
    helpMessage: dataAuthHelpMessage,
    helpComponentProps: { maxWidth: "400px" },
    componentProps: {
      checkedValue: true,
      unCheckedValue: false,
      onChange: (val) => {
        if (!val) {
          setFieldsValue({ dataAuthList: [] });
          generatorConfig!.outputConfig!.dataAuthList = [];
          if (generatorConfig?.tableStructureConfigs?.length) {
            generatorConfig.tableStructureConfigs[0].tableFieldConfigs = generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.filter(
              (x) => x.key !== "rule_user_id"
            );
          }
        } else {
          const hasRuleUserField =
            generatorConfig?.tableStructureConfigs?.length &&
            generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.find(
              (x) => x.key === "rule_user_id"
            );
          if (hasRuleUserField) return;
          generatorConfig?.tableStructureConfigs?.length &&
            generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.push({
              key: "rule_user_id",
              fieldName: "rule_user_id",
              fieldLength: 500,
              fieldType: 7,
              fieldComment: t("数据权限所属人ID"),
            });
        }
        generatorConfig!.outputConfig!.isDataAuth = val;
      },
    },
  },
  {
    field: "dataAuthList",
    label: t("权限选择"),
    component: "ApiSelect",
    required: false,
    colProps: { span: 12 },
    componentProps: {
      mode: "multiple",
      placeholder: dataAuthPlaceholder,
      api: getAuthList,
      labelField: "name",
      valueField: "id",
      getPopupContainer: () => document.body,
      onChange: (val) => {
        generatorConfig!.outputConfig!.dataAuthList = val;
      },
    },
    dynamicDisabled: ({ values }) => {
      return !values.isDataAuth;
    },
  },
];

const generatorConfig = inject<GeneratorConfig>("generatorConfig");

const [register, { validate, setFieldsValue, clearValidate }] = useForm({
  schemas: formSchemaData,
  showActionButtonGroup: false,
  layout: "vertical",
  rowProps: { gutter: 32 },
});
onMounted(() => {
  const { outputConfig } = generatorConfig!;

  setFieldsValue({
    formName: outputConfig?.formName,
    formCategory: outputConfig?.formCategory,
    isSystemForm: outputConfig?.isSystemForm,
    className: outputConfig?.className,
    comment: outputConfig?.comment,
    outputArea: outputConfig?.outputArea,
    isDataAuth: outputConfig?.isDataAuth,
    dataAuthList: outputConfig?.dataAuthList || [],
    remarks: outputConfig?.remarks,
  });
  clearValidate();
});

//验证当前步骤的数据
const validateStep = async (): Promise<boolean> => {
  try {
    const { outputConfig } = generatorConfig!;

    await validate();

    if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(outputConfig!.className!)) {
      notification.error({
        message: t("提示"),
        description: t("功能名称只能是数字和字母组成，必须以英文字母开头"),
      });
      return false;
    }
  } catch (error) {
    return false;
  }

  return true;
};

defineExpose({ validateStep });
</script>
<style lang="less" scoped>
.step4 {
  padding-top: 30px;
}
</style>
