<script setup lang="ts">
import { FormRules, ElForm } from "element-plus";
import { reactive, ref } from "vue";
import {
  httpUpdate,
  httpAdd,
  httpDetail,
  httpRoleAll,
  httpCardAll
} from "/@/api/interest/account";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/useNav";
enum FROM_TYPE {
  create = "create",
  edit = "edit",
  view = "view"
}
const { logout } = useNav();
const showModel = ref(false);
const currentMenuId = ref("");
const TYPE = ref<FROM_TYPE>(FROM_TYPE.create);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const loading = ref(false);
const titleType = ref("");
const roleOptions = ref([]);
const cardOptions = ref([]);

const emit = defineEmits(["reload"]);
const initform = {
  username: "",
  role_id: "",
  card_id: [],
  id: ""
};
const ruleForm = ref({ ...initform });
const rules = reactive<FormRules>({
  username: [{ required: true, trigger: "blur", message: "请输入账号" }],
  role_id: [{ required: true, trigger: "change", message: "请选择角色" }],
  card_id: [
    {
      required: true,
      type: "array",
      trigger: "change",
      message: "请选择卡类型"
    }
  ]
});

async function show(node: any, id: string, isCreate: string) {
  Object.keys(ruleForm.value).forEach(key => {
    ruleForm.value[key] = initform[key];
  });
  console.log(ruleForm.value);
  TYPE.value = isCreate;
  switch (TYPE.value) {
    case "create":
      titleType.value = "新建运营账号";
      break;
    case "edit":
      titleType.value = "编辑运营账号";
      break;
    case "view":
      titleType.value = "运营账号详情";
      break;
    default:
      titleType.value = "新建运营账号";
  }
  if (TYPE.value !== "create") {
    await getDetail(id);
  }

  await getRole();
  await getCard();
  showModel.value = true;
}

function handleUpdate() {
  const data = {
    ...ruleForm.value
  };

  return {
    data,
    api: httpUpdate
  };
}
async function getDetail(id) {
  const { message, code, data } = await httpDetail({ id });
  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      console.log(data);
      Object.keys(ruleForm.value).forEach(key => {
        if (key === "card_id") {
          ruleForm.value[key] = data[key];
        } else {
          ruleForm.value[key] = data[key] + "";
        }
      });
    }
  });
}
async function getRole() {
  const { message, code, data } = await httpRoleAll({});
  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      roleOptions.value = data;
    }
  });
}
async function getCard() {
  const { message, code, data } = await httpCardAll({});
  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      cardOptions.value = data;
    }
  });
}

function handleCreate() {
  const data = {
    ...ruleForm.value
  };

  return {
    data,
    api: httpAdd
  };
}

function handleSave() {
  formRef.value.validate(async vaild => {
    if (vaild) {
      if (loading.value) return;
      const handler =
        TYPE.value === FROM_TYPE.create ? handleCreate : handleUpdate;

      loading.value = true;
      const { api, data } = handler();
      const { message, code } = await api(data);

      responseHandle({
        code,
        message,
        logout,
        handler: () => {
          showModel.value = false;
          loading.value = false;
          emit("reload");
        }
      });
    }
  });
}

defineExpose({
  show,
  changeCurrentMenuId: (id: string) => (currentMenuId.value = id)
});
</script>

<template>
  <div>
    <el-dialog
      v-model="showModel"
      :close-on-press-escape="false"
      center
      append-to-body
      destroy-on-close
      :width="'700px'"
      :title="titleType"
      v-loading="loading"
    >
      <el-form
        ref="formRef"
        :model="ruleForm"
        :rules="rules"
        label-width="90px"
        style="margin-top: -10px"
        class="demo-ruleForm"
        status-icon
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="账号名称" prop="username">
              <el-input
                v-model="ruleForm.username"
                :disabled="TYPE === 'view'"
                placeholder="账号名称"
              /> </el-form-item
          ></el-col>
          <el-col :span="24">
            <el-form-item label="角色" prop="role_id">
              <el-select
                v-model="ruleForm.role_id"
                style="width: 100%"
                :disabled="TYPE === 'view'"
                placeholder="角色"
              >
                <el-option
                  v-for="(si, sii) in roleOptions"
                  :key="'type' + si.id + sii"
                  :label="si.name"
                  :disabled="si.status + '' === '0'"
                  :value="si.id + ''"
                />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="24">
            <el-form-item label="卡类型" prop="card_id">
              <el-checkbox-group
                v-model="ruleForm.card_id"
                :disabled="TYPE === 'view'"
              >
                <el-checkbox
                  v-for="(si, sii) in cardOptions"
                  :key="'card_id' + si.id + sii"
                  :label="si.id + ''"
                  :disabled="si.status + '' === '0'"
                  >{{ si.title }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item></el-col
          >
        </el-row>
        <div class="flex justify-end">
          <el-button
            v-if="TYPE !== 'view'"
            :loading="loading"
            type="primary"
            @click="handleSave"
            >保存</el-button
          >
          <el-button @click="showModel = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
