<template>
  <div>
    <p class="text-2xl font-bold mb-5">用户管理</p>
    <div>
      <!-- 级联选择 -->
      <!-- <a-cascader
        :disabled="search.length == 0 ? false : true"
        v-model="value"
        @change="handleChange"
        placeholder="通过选择搜索"
        style="width: 40%; margin-right: 15px"
      /> -->
      <header-select
        ref="headerSelect"
        :setFooList="setFooList"
        :fooList="fooList"
        :level="level"
        :role="role"
      />
      <!-- 搜索框 -->
      <!-- <a-input
        :disabled="value.length == 0 ? false : true"
        placeholder="通过输入详细地址搜索"
        v-model="search"
        style="width: 20%; margin-right: 15px"
      /> -->
      <!-- level -->
      所属层级：
      <a-select class="mr-5" style="width: 120px" v-model="type">
        <a-select-option
          v-for="item in options1"
          :key="item.value"
          :value="item.value"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
      <!-- role -->
      <a-select class="mr-5" style="width: 120px" v-model="search">
        <a-select-option
          v-for="item in option"
          :key="item.value"
          :value="item.value"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
      <!-- 操作 -->
      <a-button type="primary" style="margin-right: 10px" @click="query"
        >查询</a-button
      >
      <a-button type="primary" style="margin-right: 10px" @click="reset"
        >重置</a-button
      >
      <a-button
        type="primary"
        v-if="isBackAdmin"
        style="margin-right: 10px"
        @click="importExcel"
        :loading="loading"
        >导入</a-button
      >
      <input
        type="file"
        accept=".xlsx"
        @input="handleFileChange"
        ref="importExcel"
        v-show="false"
      />
    </div>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import { Cascader, Icon } from "ant-design-vue";
import { options } from "@/mock/index";
import { message } from "ant-design-vue";
import StaffService from "@/service/StaffService";
import { getUserMsg } from "@/utils/userMsg/userMsg";
import { eLevel } from "@/types/level";
import { bank } from "@/types/staff";
import { fooList } from "@/views/Root/OutletManagement/components/HeaderSelect/const";
import { PAGE_SIZE } from "@/const/config/page";
import HeaderSelect from "@/views/Root/OutletManagement/components/HeaderSelect/index.vue";
import { eNewRoleRelatedToBackEnd, eRole } from "@/types/role";
import { mapMutations } from "vuex";
import { getOldRoleFromUserMsg } from "@/utils/user";
import { menuList } from "@/views/Root/getMenuList";
import { handle建设银行excelFileChange } from "@/utils/StaffUtils";
import { iStaffItem } from "@/service/StaffService/types";
Vue.use(Cascader);
Vue.prototype.$message = message;

export default Vue.extend({
  components: {
    HeaderSelect,
    Icon,
  },
  computed: {
    options() {
      return options;
    },
    level(): number | undefined {
      return getUserMsg()?.level;
    },
    role() {
      return getUserMsg()?.newRole;
    },
    isBackAdmin(){
      return getUserMsg()?.newRole === eNewRoleRelatedToBackEnd.BackAdmin;
    },
  },
  data() {
    return {
      loading: false,
      search: eNewRoleRelatedToBackEnd.ACM,
      type: bank["二级支行"],
      value: [],
      fooList,
      options1: [
        {
          label: "一级分行",
          value: bank["一级分行"],
        },
        {
          label: "二级分行",
          value: bank["二级分行"],
        },
        {
          label: "一级支行",
          value: bank["一级支行"],
        },
        {
          label: "二级支行",
          value: bank["二级支行"],
        },
      ],
      option: [
        {
          label: eNewRoleRelatedToBackEnd.Management,
          value: eNewRoleRelatedToBackEnd.Management,
        },
        {
          label: eNewRoleRelatedToBackEnd.ACM,
          value: eNewRoleRelatedToBackEnd.ACM,
        },
      ],
    };
  },
  mounted() {
    console.log("foolish", this.fooList);
    this.clearPostion();
    // this.getBranchList()
    // this.setLevel(this.fooList)
  },
  methods: {
    ...mapMutations("platformUserManagement", {
      platformSave: "save",
    }),
    importExcel() {
      (this.$refs.importExcel as HTMLInputElement).click();
    },
    async handleFileChange(e: Event) {
      this.loading = true;
      try {
        const ret = await handle建设银行excelFileChange(e);
        const ret2 = await StaffService.getInstance().import({
          staffs: ret as iStaffItem[],
        });
        if(ret2.code === 200){
          message.success("导入成功");
          (this.$refs.headerSelect as any).init();
        }
      } catch (err: any) {
        message.error(err);
      }
      this.loading = false;
    },
    clearPostion() {
      this.platformSave({
        location: "",
        firstBranch: undefined,
        firstSubBranch: undefined,
        secondBranch: undefined,
        secondSubBranch: undefined,
        page: 1,
      });
    },
    // 设置级别 level
    setLevel(v: any[]) {
      for (let i = 0; i < v.length; i++) {
        if (!v[i].value) {
          this.type = i - 1 < 0 ? 0 : i - 1;
          break;
        } else if (i === v.length - 1 && v[i].value) {
          this.type = i;
        }
      }
    },
    setFooList(v: any[]) {
      this.fooList = [...v];
      // this.setLevel(v)
    },
    async getBranchList() {
      const userLevel = getUserMsg()?.level;
      console.log("level", userLevel);

      const ret = StaffService.getInstance().getBranch({
        level: userLevel as eLevel,
        page: 5,
        page_size: PAGE_SIZE,
      });

      console.log(ret);
    },
    query() {
      const levelList = [];
      for (let item of this.fooList) {
        if (item.value) {
          let name = "";
          for (let i of item.options) {
            if (i.ID === item.value) {
              name = i.Name;
            }
          }
          levelList.push({ value: item.value, name });
        } else {
          break;
        }
      }
      if (levelList.length == 0) {
        this.$message.info({
          content: "请先选择相应分区",
          icon: () => {
            return this.$createElement("Icon", {
              style: { color: "#3E4FAF" },
              props: { type: "exclamation-circle" },
            });
          },
        });
        // this.$message.info({content:"请通过选择或者输入详细地址搜索",icon:()=>{return this.$createElement('Icon',{style:{color:'#3E4FAF'},props:{type:'exclamation-circle'}})}})
      } else {
        this.selectTables(levelList);
      }
    },
    getRoles(path: string) {
      const _path = "/backend/user" + path;
      let roles = [] as any;
      menuList.forEach((item: any) => {
        if (item.path === _path) {
          roles = item.roles;
        }
      });
      return roles;
    },
    checkPermission(path: string) {
      // 获取跳转路由的权限列表
      const roles = this.getRoles(path);

      const usermsg = getUserMsg() as any;
      const oldRole = getOldRoleFromUserMsg(usermsg);
      const userHasRoleInCurPage =
        oldRole !== undefined && roles !== undefined && roles.includes(oldRole);
      if (userHasRoleInCurPage) {
        return true;
      } else {
        return false;
      }
    },
    goPages(
      _path: string,
      query: { rankVal: string; role: string; level: string }
    ) {
      const basePath = "/backend/user";
      // 判断账户权限
      if (!this.checkPermission(_path)) {
        message.error("当前账号无此权限");
        return;
      }
      this.$router.push({ path: basePath + _path, query });
    },
    selectTables(arr: Array<{ value: number; name: string }>) {
      const query = {
        rankVal: JSON.stringify(arr),
        role: this.search,
        level: this.type + 1 + "",
        // ... permission
      };
      const lv = +query.level;
      /**
       * @ 判断选择角色类型 -> 判断跳转路由层级
       * @search 角色类型, 管理/经理
       * @lv select 的 level 值 + 1, 路由层级
       */
      if (this.search === eNewRoleRelatedToBackEnd.ACM) {
        if (lv >= 3) {
          if (lv === 3) {
            const _path = "/firstSubClientManager";
            this.goPages(_path, query);
          } else {
            const _path = "/secondarySubClientManager";
            this.goPages(_path, query);
          }
        } else {
          message.error("所选分行不存在客户经理");
        }
      } else {
        if (lv === 1) {
          const _path = "/firstLevel";
          this.goPages(_path, query);
        } else if (lv === 2) {
          const _path = "/secondary";
          this.goPages(_path, query);
        } else if (lv === 3) {
          const _path = "/firstSub";
          this.goPages(_path, query);
        } else {
          const _path = "/secondarySub";
          this.goPages(_path, query);
        }
      }
    },
    reset() {
      (this.$refs.headerSelect as any).init();
      this.search = eNewRoleRelatedToBackEnd.Management;
      this.type = bank["一级分行"];
    },
  },
});

function _path(_path: any) {
  throw new Error("Function not implemented.");
}
</script>