<template>
  <div class="container">
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="table-container">
      <TableCustom :columns="columns" :tableData="tableData" :paging="paging" :refresh="getData" :changePage="changePage">
        <template #toolbarBtn>
          <el-button type="primary" @click="typeVisible = true">类型编辑</el-button>
          <el-button type="primary" @click="handelRow('add')">新增用户</el-button>
          <el-button @click="handleImp">批量创建用户</el-button>
          <!-- <el-button>导出</el-button> -->
          <!-- <el-button type="danger">删除</el-button> -->
        </template>

        <template #status="{ rows }">
          <el-switch v-model="rows.status" :active-value="1" :inactive-value="0" />
        </template>

        <template #roleId="{ rows }">
          {{ roleEnum[rows.roleId] }}
        </template>
        <!-- 
        <template #password="{ rows }">
          <div v-if="rows.flag" @click="rows.flag = false">
            {{ rows.password }}
            <el-icon style="cursor: pointer"><View /></el-icon>
          </div>
          <div v-else @click="rows.flag = true">
            ******
            <el-icon style="cursor: pointer"><Hide /></el-icon>
          </div>
        </template> -->

        <template #operator="{ rows }">
          <el-button link type="primary" size="small" @click="handelRow('pwd', rows)"> 重置密码 </el-button>
          <el-button link type="primary" size="small" @click="handelRow('edit', rows)"> 修改 </el-button>
          <el-button link type="danger" size="small" @click="handelDel(rows)"> 删除 </el-button>
        </template>
      </TableCustom>
    </div>
    <el-dialog :title="dialogTitle" v-model="visible" width="700px" destroy-on-close :close-on-click-modal="false" @close="closeDialog">
      <AddUser :orgAllData="orgAllData" :form-data="rowData" :api="updateData" @close="closeDialog" />
    </el-dialog>
    <el-dialog title="重置密码" v-model="visible1" width="700px" destroy-on-close :close-on-click-modal="false" @close="visible1 = false">
      <ResetPwd :api="handleResetPwd" @close="visible1 = false" />
    </el-dialog>
    <el-dialog title="编辑类型" v-model="typeVisible" width="800px" destroy-on-close :close-on-click-modal="false" @close="closeDialog">
      <UserType :typeHeadList="typeHeadList" :roleListData="roleListData" @complete="saveType" @addType="addType" />
    </el-dialog>
    <BatchImp ref="batchImpRef" @success="handleSearch" />
  </div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { accountAdd, accountModify, accountList, accountDeletet, passwordReset, roleList, roleMenuList, roleModify, roleAdd, orgAllList } from "@/api/index";
import TableCustom from "@/components/table-custom.vue";
import TableSearch from "@/components/table-search.vue";
import TableEdit from "@/components/table-edit.vue";
import BatchImp from "@/components/batch-imp.vue";
import AddUser from "./addUser.vue";
import { useCommonStore } from "@/store/common";
import UserType from "./userType.vue";
import ResetPwd from "./resetPwd.vue";
import { TableItem } from "@/types/table";
import { FormOption, FormOptionList } from "@/types/form-option";
import { TAccount, TOrg, TRoleList, TRoleMenuList, TRoleModify } from "@/api/index.d";
// import { Hide, View } from "@element-plus/icons-vue";

enum roleEnum {
  "管理员" = -1,
  "警察" = 1,
  "辅警" = 2,
  "协警" = 3,
}

const comm = useCommonStore();
const visible = ref(false);
const visible1 = ref(false);
const typeVisible = ref(false);
const isEdit = ref(false);
const dialogTitle = ref("");
const rowData = ref<TAccount.IListRes | undefined>();
// 类型列表头列表
let typeHeadList = ref<TRoleMenuList.TRes[]>([]);
const orgAllData = ref<TOrg.IOrgRecordRes[]>([]);
// 查询相关
const query = reactive({
  name: "",
});
const batchImpRef = ref();
const paging = reactive({
  page: 1,
  size: 10,
  total: 0,
});
const tableData = ref<TAccount.IListRes[]>([]);
const roleListData = ref<TRoleList[]>([]);

const searchOpt = ref<FormOptionList[]>([
  { type: "input", label: "用户名：", prop: "name" },
  { type: "input", label: "警员号：", prop: "username" },
  {
    type: "select",
    label: "用户类型：",
    prop: "roleId",
    opts: comm.roleList.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    }),
  },
  {
    type: "select",
    label: "状态：",
    prop: "status",
    opts: [
      { label: "禁用", value: "0" },
      { label: "启用", value: "1" },
    ],
  },
]);

// 表格相关
let columns = ref([
  // { type: "selection" },
  { type: "index", label: "序号", width: 55, align: "center" },
  { prop: "name", label: "用户名称" },
  { prop: "username", label: "警员号" },
  { prop: "phone", label: "手机号" },
  // { prop: "password", label: "密码", width: 120 },
  { prop: "roleId", label: "类型" },
  { prop: "orgName", label: "辖区" },
  { prop: "createTime", label: "创建时间" },
  { prop: "status", label: "状态" },
  { prop: "operator", label: "操作", width: 250 },
]);

const handleImp = () => {
  batchImpRef.value.dialogVisible = true;
};
const handleSearch = () => {
  paging.page = 1;
  getData();
};

const changePage = (val: number) => {
  paging.page = val;
  getData();
};

const getData = async () => {
  const res = await accountList({ ...paging, ...query });
  tableData.value = res.records?.map((item) => {
    item.flag = false;
    return item;
  });
  paging.total = res.total;
};

const getOrgAllList = () => {
  orgAllList().then((res) => {
    orgAllData.value = res;
  });
};
// 删除相关
const handelDel = (row: TableItem) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  }).then(async () => {
    accountDeletet({ id: row.id }).then((res) => {
      ElMessage.success("删除成功");
      getData();
    });
  });
};

const updateData = (res) => {
  let api, msg, p;
  if (dialogTitle.value == "重置密码") {
    api = passwordReset;
    p = { ...res, id: rowData.value.id };
    msg = "重置成功";
  } else {
    p = { ...res };
    api = isEdit.value ? accountModify : accountAdd;
    msg = isEdit.value ? "修改成功" : "新增成功";
  }

  api(p).then((res) => {
    ElMessage.success(msg);
    closeDialog();
    getData();
  });
};
const handleResetPwd = (res) => {
  passwordReset({ ...res, id: rowData.value.id }).then((res) => {
    ElMessage.success("密码重置成功");
    visible1.value = true;
  });
};
const saveType = (row: TRoleModify.Ireq) => {
  const api = row.id ? roleModify : roleAdd;
  api(row).then(() => {
    ElMessage.success("保存成功");
    comm.getRoleList();
  });
};
const addType = () => {
  roleListData.value.push({ name: "", roleMenu: [] });
};
const roleListFn = () => {
  roleList().then((res) => {
    roleListData.value = res;
  });
};
const closeDialog = () => {
  visible.value = false;
};

const handelRow = (name: string, row?: TAccount.IListRes) => {
  if (name == "add") {
    dialogTitle.value = "新增用户";
    rowData.value = undefined;
    visible.value = true;
  } else if (name == "pwd") {
    rowData.value = { ...row };
    visible1.value = true;
  } else if (name == "edit") {
    dialogTitle.value = "编辑";
    rowData.value = { ...row };
    visible.value = true;
  }
};
const getRoleMenuList = () => {
  roleMenuList().then((res) => {
    typeHeadList.value = res;
  });
};
onMounted(() => {
  getData();
  getRoleMenuList();
  getOrgAllList();
  roleListFn();
});
</script>

<style scoped>
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
