<script lang="ts" setup>
import BasePageableTable from "@/components/base/base-pageable-table/BasePageableTable.vue";
import DefaultToolButton from "@/components/base/default-tool-button/DefaultToolButton.vue";
import DefaultOperateButtonColumn from "@/components/base/default-column/DefaultOperateButtonColumn.vue";
import { usePage } from "@/composables/use-page";
import BaseForm from "@/components/base/base-form/BaseForm.vue";
import { $t } from "@/common/languages";
import type { FormInstance, FormRules } from "element-plus";
import { formatDate } from "@/common/utils/format-utils";
import DefaultStatusSwitchColumn from "@/components/base/default-column/DefaultStatusSwitchColumn.vue";
import StatusSwitch from "@/components/base/base-switch/StatusSwitch.vue";
import BaseMultiSelect from "@/components/base/base-multi-select/BaseMultiSelect.vue";

/**
 * 必须要的变量
 */
const getPageUrl = "/sys/sysuser/getSysUserPage";
const addUrl = "/sys/sysuser/addSysUser";
const editUrl = "/sys/sysuser/updateSysUser";
const removeUrl = "/sys/sysuser/deleteSysUser";
const statusUrl = "/sys/sysuser/setStatus";
const roleSelectUrl = "/sys/sysrole/getSysRoleSelectList";

const searchers = [
  { name: "loginName", type: "text" as const, placeholder: $t("_prop.systemset.sysuser.loginName") },
  { name: "userName", type: "text" as const, placeholder: $t("_prop.systemset.sysuser.userName") },
];

const rules = reactive<FormRules>({
  loginName: [{ required: true, message: $t("_message.systemset.sysuser.input_loginName"), trigger: "blur" }],
  userName: [{ required: true, message: $t("_message.systemset.sysuser.input_userName"), trigger: "blur" }],
  passWord: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        // 编辑模式下密码为空表示不修改，允许通过
        if (formType.value && !value) {
          callback();
          return;
        }
        // 新建模式下密码必填
        if (!formType.value && !value) {
          callback(new Error($t("_message.systemset.sysuser.input_password")));
          return;
        }
        // 密码长度校验
        if (value && value.length < 6) {
          callback(new Error($t("_message.systemset.sysuser.password_min_length")));
          return;
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  confirmPassword: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        // 编辑模式下如果密码为空，确认密码也为空时允许通过
        if (formType.value && !form.value.passWord && !value) {
          callback();
          return;
        }
        // 新建模式下确认密码必填
        if (!formType.value && !value) {
          callback(new Error($t("_message.systemset.sysuser.input_confirmPassword")));
          return;
        }
        // 密码一致性校验
        if (value !== form.value.passWord) {
          callback(new Error($t("_message.systemset.sysuser.password_not_match")));
          return;
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  userType: [{ required: true, message: $t("_message.systemset.sysuser.select_userType"), trigger: "change" }],
  roleIds: [
    { required: true, message: $t("_message.systemset.sysuser.select_role"), trigger: "change", type: "array" },
  ],
});

const userTypeOptions = [
  { code: 0, description: $t("_enum.userType.normal") },
  { code: 5, description: $t("_enum.userType.admin") },
];

/**
 * 基本不变通用变量
 */
const tableRef = ref<InstanceType<typeof BasePageableTable> | null>(null);
const { useAdd, useEdit, useRemove, useGeneralPageRef } = usePage(tableRef);
const { title, visible, formType, form } = useGeneralPageRef();
const baseFormRef = ref<InstanceType<typeof BaseForm>>();

/**
 * 可以自定义的变量
 */
const add = () => {
  form.value = {
    userType: 0,
    roleIds: [],
    status: 1,
  };
  title.value = "_title.systemset.sysuser.add";
  visible.value = true;
  formType.value = false;
};

const edit = (row: any) => {
  title.value = "_title.systemset.sysuser.edit";
  form.value = {
    ...row,
    passWord: "",
    confirmPassword: "",
    roleIds: row.roleIds || [],
  };
  visible.value = true;
  formType.value = true;
};

const remove = (row: any) => {
  useRemove(removeUrl, row.id, "_message.systemset.sysuser.delete_message");
};

const submit = (formData: any, formRef: FormInstance | undefined) => {
  if (formRef !== undefined) {
    formRef.validate(valid => {
      if (valid) {
        const submitData = { ...formData };
        // 编辑模式下，如果密码为空，则不提交密码字段
        if (formType.value && !submitData.passWord) {
          delete submitData.passWord;
          delete submitData.confirmPassword;
        }

        if (formType.value) {
          // 编辑模式：使用新的 DTO 格式 { id, dto }
          const updateData = {
            id: submitData.id,
            dto: submitData,
          };
          useEdit(editUrl, updateData, visible);
        } else {
          useAdd(addUrl, submitData, visible);
        }
      }
    });
  }
};

const topButtonClick = (eventName: string) => {
  switch (eventName) {
    case "add":
      add();
      break;
  }
};

const operateButtonClick = (eventName: string, row: any) => {
  switch (eventName) {
    case "edit":
      edit(row);
      break;
    case "remove":
      remove(row);
      break;
  }
};

const getUserTypeLabel = (type: number) => {
  const option = userTypeOptions.find(item => item.code === type);
  return option?.description || "-";
};

// 通用状态标签类型映射（启用/禁用）
const getCommonStatusTagType = (code: number | null): string => {
  const tagTypeMap: Record<number, string> = {
    0: "success", // 启用
    1: "info", // 禁用
  };
  return tagTypeMap[code ?? -1] || "info";
};
</script>
<template>
  <BasePageableTable :url="getPageUrl" :searchers="searchers" ref="tableRef">
    <template #tool-button>
      <DefaultToolButton @top-button-click="topButtonClick" />
    </template>
    <template #columns>
      <el-table-column :label="$t('_prop.systemset.sysuser.loginName')" prop="loginName" />
      <el-table-column :label="$t('_prop.systemset.sysuser.userName')" prop="userName" />
      <el-table-column :label="$t('_prop.systemset.sysuser.roleNames')" prop="roleNames" show-overflow-tooltip />
      <el-table-column
        :label="$t('_prop.systemset.sysuser.userType')"
        prop="userType"
        :formatter="(row: any) => getUserTypeLabel(row.userType)"
      />
      <el-table-column :label="$t('_prop.common.createDate')" prop="createDate" :formatter="formatDate" />
      <DefaultStatusSwitchColumn :url="statusUrl" :tag-type-mapping="getCommonStatusTagType" />
      <DefaultOperateButtonColumn @operate-button-click="operateButtonClick" />
    </template>
  </BasePageableTable>

  <BaseForm
    ref="baseFormRef"
    v-model:visible="visible"
    @submit="submit"
    v-model:form="form"
    :title="$t(title)"
    :rules="rules"
  >
    <template #form-items>
      <el-form-item prop="id" v-if="false"><el-input v-model="form.id" /></el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.sysuser.loginName')" prop="loginName">
            <el-input v-model="form.loginName" :placeholder="$t('_message.systemset.sysuser.input_loginName')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.sysuser.userName')" prop="userName">
            <el-input v-model="form.userName" :placeholder="$t('_message.systemset.sysuser.input_userName')" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.sysuser.password')" prop="passWord">
            <el-input
              v-model="form.passWord"
              type="password"
              show-password
              :placeholder="
                formType
                  ? $t('_message.systemset.sysuser.input_password_edit')
                  : $t('_message.systemset.sysuser.input_password')
              "
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.sysuser.confirmPassword')" prop="confirmPassword">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              show-password
              :placeholder="$t('_message.systemset.sysuser.input_confirmPassword')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.sysuser.userType')" prop="userType">
            <el-select
              v-model="form.userType"
              :placeholder="$t('_message.systemset.sysuser.select_userType')"
              style="width: 100%"
            >
              <el-option
                v-for="item in userTypeOptions"
                :key="item.code"
                :label="item.description"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.sysuser.role')" prop="roleIds">
            <BaseMultiSelect
              v-model="form.roleIds"
              :url="roleSelectUrl"
              name="roleId"
              label="roleName"
              :placeholder="$t('_message.systemset.sysuser.select_role')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.common.status')" prop="status">
            <StatusSwitch v-model="form.status" />
          </el-form-item>
        </el-col>
      </el-row>
    </template>
  </BaseForm>
</template>
