<script setup lang="ts">
import { httpAdd, httpUpdate, httpRoleAll } from "/@/api/interest/account";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { reactive, ref, watch, nextTick } from "vue";
import menuType from "./types";
import { useNav } from "/@/layout/hooks/nav";
import { isMobile } from "/@/utils/validate";
const { logout } = useNav();
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();

const props = defineProps({
  itemId: {
    type: String,
    default: ""
  },
  showModel: {
    type: Boolean,
    default: false
  },
  isDetails: {
    type: String,
    default: "add"
  },
  sitem: {
    type: Object as PropType<menuType>
  }
});
const showModelThis = ref(false);
const emit = defineEmits<{
  (e: "cancel"): void;
  (e: "refresh"): void;
}>();
const id = ref("");
const editType = ref("add");
const roleList = ref([]);
const formModel = {
  id: "", //账户id
  nickname: "", //真实姓名
  mobile: "", //手机号
  email: "", //邮箱
  role: "" //角色
};
const ruleForm = reactive<menuType>({ ...formModel });
const rules = reactive<FormRules>({
  nickname: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, max: 12, message: "长度在 2 到 12 个字符", trigger: "blur" }
  ],
  mobile: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("手机号不能为空！"));
        } else if (!isMobile(value)) {
          callback(new Error("手机号格式不正确！"));
        } else {
          callback();
        }
      },

      trigger: "blur"
    }
  ],

  role: [
    {
      required: true,
      message: "请选择角色",
      trigger: "change"
    }
  ],
  email: [
    {
      required: false,
      message: "请输入邮箱",
      trigger: "change"
    }
  ]
});
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (loading.value === true) return;
      loading.value = true;
      const model = Object.assign({}, ruleForm);
      const { code, message } =
        editType.value === "add"
          ? await httpAdd(model)
          : await httpUpdate(model);
      loading.value = false;
      if (code === 0) {
        ElMessage.success(titleType.value + "成功！");
        showModelThis.value = false;
        emit("refresh");
      } else if (code > 100 && code < 140) {
        showModelThis.value = false;
        logout();
      } else {
        ElMessage.error(message);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = async (formEl: FormInstance | undefined, item) => {
  if (!formEl) return;
  formEl.clearValidate();
  formEl.resetFields();
  await nextTick(async () => {
    for (let key in ruleForm) {
      if (key === "role") {
        ruleForm[key] = item["roleid"] || "";
      } else {
        ruleForm[key] = item[key];
      }
    }
  });
};
const closeDialog = () => {
  showModelThis.value = false;
  emit("cancel");
};

const loading = ref(true);
const titleType = ref("");
async function initForm(item: Object) {
  loading.value = true;
  switch (editType.value) {
    case "add":
      titleType.value = "新建账号";
      break;
    case "edit":
      titleType.value = "编辑账号";
      break;
    case "view":
      titleType.value = "账号详情";
      break;
    default:
      titleType.value = "新建账号";
  }
  const { code, data, message } = await httpRoleAll({});
  if (code === 0) {
    roleList.value = data ?? [];
  } else if (code > 100 && code < 140) {
    logout();
  } else {
    ElMessage.error(message);
  }
  await resetForm(ruleFormRef.value, item);
  console.log(ruleForm);
  loading.value = false;
}
watch(
  () => {
    return props.showModel;
  },
  () => {
    const { showModel, itemId, isDetails, sitem } = props;
    showModelThis.value = showModel;
    if (showModelThis.value) {
      id.value = itemId;
      editType.value = isDetails;
      if (isDetails !== "add") {
        initForm(sitem);
      } else {
        initForm(formModel);
      }
    }
  }
);
</script>

<template>
  <el-dialog
    :close-on-press-escape="false"
    v-model="showModelThis"
    append-to-body
    :width="'900px'"
    center
    :title="titleType"
    v-loading="loading"
    @close="closeDialog"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="90px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="真实姓名" prop="nickname">
            <el-input
              v-model="ruleForm.nickname"
              :disabled="editType === 'view'"
              placeholder="真实姓名"
            /> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="ruleForm.mobile"
              :disabled="editType === 'view'"
              :maxlength="11"
              placeholder="手机号"
            /> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="ruleForm.email"
              :disabled="editType === 'view'"
              placeholder="邮箱"
            /> </el-form-item
        ></el-col>
        <el-col :span="24">
          <el-form-item label="角色" prop="role">
            <el-radio-group
              v-model="ruleForm.role"
              :disabled="editType === 'view'"
            >
              <el-radio
                v-for="(si, sii) in roleList"
                :key="si.id + sii"
                :label="si.id"
                :disabled="si.status !== '1'"
                >{{ si.role_name }}</el-radio
              >
            </el-radio-group>
          </el-form-item></el-col
        >
      </el-row>
      <el-col :span="24" class="clear">
        <el-button
          v-if="editType === 'add' || editType === 'edit'"
          type="primary"
          class="fr"
          style="margin: 0 0 0 16px"
          @click="submitForm(ruleFormRef)"
          >保存</el-button
        >
        <el-button class="fr" style="margin: 0 0 0 16px" @click="closeDialog"
          >关闭</el-button
        >
      </el-col>
    </el-form>
  </el-dialog>
</template>
