<script setup lang="ts">
import { FormRules, ElForm } from "element-plus";
import { reactive, ref } from "vue";
import { httpAdd } from "/@/api/operate/batchCreatUser";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/useNav";
import { ElMessage } from "element-plus";
import { Company, Card } from "/@/components/RemoteSelect";
import dayjs from "dayjs";
enum FROM_TYPE {
  create = "create",
  edit = "edit",
  view = "view"
}
const { logout } = useNav();
const showModel = ref(false);
const TYPE = ref<FROM_TYPE>(FROM_TYPE.create);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const loading = ref(false);
const titleType = ref("");
const default_year = new Date().getFullYear() - 2000;
const year_options = ref([]);
const id = ref("");
const emit = defineEmits(["reload"]);
const initform = {
  company_id: "",
  card_id: "",
  username_prefix: "",
  username_year: default_year + "",
  time: []
};
const ruleForm = ref({ ...initform });
const rules = reactive<FormRules>({
  company_id: [{ required: true, trigger: "change", message: "请选择企业" }],
  card_id: [{ required: true, trigger: "change", message: "请选择卡类型" }],
  username_prefix: [
    { required: true, trigger: "bulr", message: "请输入字母端" }
  ],
  username_year: [
    { required: true, trigger: "change", message: "请选择年份段" }
  ],
  time: [
    {
      required: true,
      type: "array",
      trigger: "change",
      message: "请选择有效日期"
    }
  ]
});

async function show(node: any, did: string, isCreate: string) {
  id.value = did;
  const arr = [];
  for (let i = default_year + 1; i > 20; i--) {
    arr.push(i + "");
  }
  year_options.value = arr;
  Object.keys(ruleForm.value).forEach(key => {
    ruleForm.value[key] = initform[key];
  });
  TYPE.value = isCreate;
  switch (TYPE.value) {
    case "create":
      titleType.value = "新建批量创建账号";
      break;
    case "edit":
      titleType.value = "编辑批量创建账号";
      break;
    case "view":
      titleType.value = "批量创建账号详情";
      break;
    default:
      titleType.value = "新建批量创建账号";
  }
  showModel.value = true;
}

function handleCreate() {
  const data = {
    ...ruleForm.value
  };
  return {
    data,
    api: httpAdd
  };
}

function handleSave() {
  formRef.value.validate(async vaild => {
    if (vaild) {
      if (loading.value) return;
      loading.value = true;
      const { time } = ruleForm.value;
      if (time.length !== 2) {
        loading.value = false;
        ElMessage.warning("有效日期不完整！");
        return;
      }

      const handler = handleCreate;

      const { api, data } = handler();
      let model = JSON.parse(JSON.stringify(data));
      model.starttime = dayjs(model.time[0]).format("YYYY-MM-DD");
      model.expiretime = dayjs(model.time[1]).format("YYYY-MM-DD");
      delete model["time"];
      const { message, code } = await api(model);
      loading.value = false;
      responseHandle({
        code,
        message,
        logout,
        handler: () => {
          showModel.value = false;
          emit("reload");
        }
      });
    }
  });
}

defineExpose({
  show
});
</script>

<template>
  <el-dialog
    v-model="showModel"
    :close-on-press-escape="false"
    center
    append-to-body
    destroy-on-close
    :width="'650px'"
    :title="titleType"
    v-loading="loading"
  >
    <el-form
      ref="formRef"
      :model="ruleForm"
      :rules="rules"
      label-width="85px"
      style="margin-top: -10px"
      class="demo-ruleForm"
      status-icon
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="企业名称" prop="company_id">
            <Company
              v-model="ruleForm.company_id"
              :disabled="TYPE === 'view'"
              :show-disabled="true"
              placeholder="企业名称"
            /> </el-form-item
        ></el-col>
        <el-col :span="24">
          <el-form-item label="卡类型" prop="card_id">
            <Card
              v-model="ruleForm.card_id"
              :disabled="TYPE === 'view'"
              :show-disabled="true"
              placeholder="卡类型"
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="前缀" prop="headname">
            <span>CJ1745</span>
          </el-form-item></el-col
        >
        <el-col :span="12">
          <el-form-item label="字母段" prop="username_prefix">
            <ElInput
              placeholder="字母段"
              :disabled="TYPE === 'view'"
              maxlength="5"
              v-model="ruleForm.username_prefix"
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="年份段" prop="username_year">
            <el-select
              v-model="ruleForm.username_year"
              placeholder="年份段"
              style="width: 100%"
            >
              <el-option
                v-for="(item, sii) in year_options"
                :key="item + sii"
                :label="item"
                :value="item"
              />
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="数字段" prop="suffix">
            <span>0000~9999</span></el-form-item
          ></el-col
        >

        <el-col :span="24">
          <el-form-item label="有效日期" prop="time">
            <el-date-picker
              v-model="ruleForm.time"
              type="daterange"
              :disabled="TYPE === 'view'"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            /> </el-form-item
        ></el-col>
      </el-row>
      <div class="flex justify-end">
        <el-button
          v-if="TYPE !== 'view'"
          :loading="loading"
          :disabled="loading"
          type="primary"
          @click="handleSave"
          >保存</el-button
        >
        <el-button @click="showModel = false">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
