<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { Close } from "@element-plus/icons-vue";
import { useColumns } from "./table/accountColumns";
import {
  getUserList,
  getDeptManageList,
  resetPW,
  deletePW,
  deleteDeptManage,
  queryRoleDateList,
  deleteRole,
  updateUserStatus
} from "@/api/system";
import { message } from "@/utils/message";
import accountDrawer from "./compontents/accountDrawer.vue";
import deptDrawer from "./compontents/deptDrawer.vue";
import roleDrawer from "./compontents/roleDrawer.vue";
import ruleSet from "./compontents/ruleSet.vue";
defineOptions({
  name: "AccountManagement"
});
const { accountColumns, deptColumns, roleColumns } = useColumns();
const seachForm = reactive({
  status: "1"
});
const accountForm = reactive({
  userName: "",
  roleId: "",
  deptId: ""
});
const updateFrom = ref({});
const updateDeptFrom = ref({});
const updateRoleFrom = ref({});
const passwordForm = reactive({
  id: "",
  account: "",
  password: "",
  confirmPassword: ""
});
const accountFromType = ref("");
const tabList = ref([
  {
    title: "账号管理",
    id: "1"
  },
  {
    title: "部门管理",
    id: "2"
  },
  {
    title: "角色权限",
    id: "3"
  }
]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  align: "center",
  layout: "total, prev, pager, next, jumper",
  background: true
});

const roleDataList = ref([]);
const accountDataList = ref([]);
// const deptDataList = ref([]);
/**
 * 部门列表查询
 */
const getDeptData = async () => {
  const res: any = await getDeptManageList({
    baseName: "",
    deptCode: "",
    pageNum: 1,
    pageSize: 20
  });
  if (res.code === 200) {
    deptOptions.value = res.data.records;
    if (seachForm.status === "2") {
      pagination.total = res.data.total;
    }
  }
};
/**
 * 用户列表查询
 */
const getUserTableData = async () => {
  const res: any = await getUserList({
    userName: accountForm.userName,
    deptId: accountForm.deptId,
    roleName: accountForm.roleId,
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize
  });
  if (res.code === 200) {
    accountDataList.value = res.data.records;
    pagination.total = res.data.total;
  }
  console.log(res);
  // dataList.value = res.data;
};
/**
 * 角色列表查询
 */
const getRoleTableData = async () => {
  const res: any = await queryRoleDateList({
    roleName: accountForm.userName,
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize
  });
  if (res.code === 200) {
    roleDataList.value = res.data.records;
    pagination.total = res.data.total;
  }
};
const search = () => {
  pagination.currentPage = 1;
  pagination.pageSize = 10;
  if (seachForm.status === "1") {
    getUserTableData();
  } else if (seachForm.status === "2") {
    getDeptData();
  } else {
    getRoleTableData();
  }
};

const reset = () => {
  accountForm.userName = "";
  accountForm.roleId = "";
  accountForm.deptId = "";
  search();
};
const createFlag = ref(false);
const createDeptFlag = ref(false);
const createRoleFlag = ref(false);
const dialogFormVisible = ref(false);
const deleteFormVisible = ref(false);
const roleSetVisible = ref(false);

const passwordFormRef = ref<FormInstance>();

const create = () => {
  if (seachForm.status === "1") {
    createFlag.value = true;
  } else if (seachForm.status === "2") {
    createDeptFlag.value = true;
  } else {
    createRoleFlag.value = true;
  }

  // search();
};
// const changeStatus = item => {
//   seachForm.status = item.id;
// };
const closeDrawer = () => {
  if (createFlag.value) {
    createFlag.value = false;
    accountFromType.value = "";
    search();
  } else if (createDeptFlag.value) {
    createDeptFlag.value = false;
    accountFromType.value = "";
    search();
  } else {
    createRoleFlag.value = false;
    accountFromType.value = "";
    search();
  }
  // if (updateFlag.value) {
  //   updateFlag.value = false;
  //   search();
  // }
};
const deptOptions = ref([]);

const changeStatus = item => {
  seachForm.status = item.id;
  search();
};
const handleView = async (value: any, type: string) => {
  console.log(value);
  createFlag.value = true;
  accountFromType.value = type;
  updateFrom.value = value;
};
const handleEdit = async (value: any, type: string) => {
  if (seachForm.status === "1") {
    createFlag.value = true;
    accountFromType.value = type;
    updateFrom.value = value;
  } else if (seachForm.status === "2") {
    createDeptFlag.value = true;
    accountFromType.value = type;
    updateDeptFrom.value = value;
  } else {
    createRoleFlag.value = true;
    accountFromType.value = type;
    updateRoleFrom.value = value;
  }
};

const handleReset = (value: any) => {
  dialogFormVisible.value = true;
  passwordForm.id = value.id;
  passwordForm.account = value.account;
  // updateId.value = value.id;
  // updateFlag.value = true;
};
const handleDelete = (value: any) => {
  deleteFormVisible.value = true;
  passwordForm.id = value.id;
};
function onCurrentChange(page: number) {
  // console.log("onCurrentChange", page);
  pagination.currentPage = page;
  pagination.pageSize = 10;
  getUserTableData();
}
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      // console.log(valid);
      resetPW({
        id: passwordForm.id
      }).then(res => {
        if (res.code === 200) {
          message("重置成功", { type: "success" });
          dialogFormVisible.value = false;
        }
      });
    } else {
      dialogFormVisible.value = false;
      console.log("error submit!");
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogFormVisible.value = false;
};
const deleteForm = () => {
  if (seachForm.status === "1") {
    deletePW({
      id: passwordForm.id
    }).then(res => {
      if (res.code === 200) {
        message("删除成功", { type: "success" });
        deleteFormVisible.value = false;
        search();
      }
    });
  } else if (seachForm.status === "2") {
    deleteDeptManage({
      id: passwordForm.id
    }).then(res => {
      if (res.code === 200) {
        message("删除成功", { type: "success" });
        deleteFormVisible.value = false;
        search();
      }
    });
  } else {
    deleteRole({
      id: passwordForm.id
    }).then(res => {
      if (res.code === 200) {
        message("删除成功", { type: "success" });
        deleteFormVisible.value = false;
        search();
      }
    });
  }
};
const newName = (type: any) => {
  if (type === "1") {
    return "新建账号";
  } else if (type === "2") {
    return "新建部门";
  } else {
    return "新建角色";
  }
};
const deleteName = (type: any) => {
  if (type === "1") {
    return "账号";
  } else if (type === "2") {
    return "部门";
  } else {
    return "角色";
  }
};
//角色权限
const handleRolePermission = row => {
  roleSetVisible.value = true;
};
//状态切换
const changeUserStatus = async row => {
  console.log(row);
  const res: any = await updateUserStatus({
    id: row.id,
    status: row.status ? 0 : 1
  });
  if (res.code === 200) {
    message("修改成功", { type: "success" });
    getUserTableData();
  }
};
onMounted(() => {
  getDeptData();
  // getUserTableData();
  // getRoleTableData();
  search();
});
</script>

<template>
  <div class="sublibrary_management app-main-content">
    <div class="main-table">
      <div class="main-table-header">
        <div class="tab-list">
          <div
            class="tab-list-item"
            :class="[seachForm.status === item.id ? 'actived' : '']"
            v-for="(item, index) in tabList"
            :key="index"
            @click="changeStatus(item)"
          >
            <span>{{ item.title }}</span>
          </div>
        </div>
        <div class="header-btn">
          <el-button @click="create" type="primary">{{
            newName(seachForm.status)
          }}</el-button>
        </div>
      </div>
      <div class="account_seach" v-if="seachForm.status === '1'">
        <el-form :model="accountForm">
          <el-row>
            <el-form-item label="用户名">
              <el-input v-model="accountForm.userName" placeholder="请输入" />
            </el-form-item>
            <el-form-item class="ml-4" label="角色">
              <el-input v-model="accountForm.roleId" placeholder="请输入" />
            </el-form-item>
            <el-form-item class="ml-4" label="所属部门">
              <el-select
                v-model="accountForm.deptId"
                clearable
                placeholder="请选择"
                style="width: 240px"
              >
                <el-option
                  v-for="item in deptOptions"
                  :key="item.id"
                  :label="item.deptName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-button @click="reset" class="ml-8">重置</el-button>
            <el-button @click="search" type="primary">搜索</el-button>
          </el-row>
        </el-form>
        <pure-table
          showOverflowTooltip
          alignWhole="center"
          :data="accountDataList"
          :columns="accountColumns"
          adaptive
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          :pagination="pagination"
          @page-current-change="onCurrentChange"
        >
          <template #index="{ index }">
            <span>{{ index + 1 }}</span>
          </template>
          <template #userRoleList="{ row }">
            <span v-for="(item, index) in row.userRoleList" :key="index"
              >{{ item.roleName
              }}<i v-if="index < row.userRoleList.length - 1">, </i></span
            >
          </template>
          <template #status="{ row }">
            <el-switch
              :model-value="row.status === 0 ? true : false"
              @click="changeUserStatus(row)"
            />
          </template>
          <template #operation="{ row }">
            <el-button link type="primary" @click="handleView(row, 'view')">
              查看
            </el-button>
            <span>|</span>
            <el-button link type="primary" @click="handleEdit(row, 'edit')">
              编辑
            </el-button>
            <span>|</span>
            <el-button link type="primary" @click="handleReset(row)">
              重置密码
            </el-button>
            <span>|</span>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template></pure-table
        >
      </div>
      <div class="account_seach" v-if="seachForm.status === '2'">
        <pure-table
          showOverflowTooltip
          alignWhole="center"
          :data="deptOptions"
          :columns="deptColumns"
          adaptive
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          :pagination="pagination"
          @page-current-change="onCurrentChange"
        >
          <template #index="{ index }">
            <span>{{ index + 1 }}</span>
          </template>
          <template #operation="{ row }">
            <el-button link type="primary" @click="handleEdit(row, 'edit')">
              编辑
            </el-button>
            <span>|</span>
            <el-button link type="primary"> 部门权限 </el-button>
            <span>|</span>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template></pure-table
        >
      </div>
      <div class="account_seach" v-if="seachForm.status === '3'">
        <pure-table
          showOverflowTooltip
          alignWhole="center"
          :data="roleDataList"
          :columns="roleColumns"
          adaptive
          :pagination="pagination"
          @page-current-change="onCurrentChange"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
        >
          <template #index="{ index }">
            <span>{{ index + 1 }}</span>
          </template>
          <template #operation="{ row }">
            <el-button link type="primary" @click="handleEdit(row, 'edit')">
              编辑
            </el-button>
            <span>|</span>
            <el-button link type="primary" @click="handleRolePermission(row)">
              角色权限
            </el-button>
            <span>|</span>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template></pure-table
        >
      </div>
      <!-- 账户抽屉 -->
      <accountDrawer
        :createFlag="createFlag"
        :updateFrom="updateFrom"
        :accountFromType="accountFromType"
        :closeDrawer="closeDrawer"
      />
      <!-- 部门 -->
      <deptDrawer
        :createFlag="createDeptFlag"
        :updateFrom="updateDeptFrom"
        :accountFromType="accountFromType"
        :closeDrawer="closeDrawer"
      />
      <!-- 角色 -->
      <roleDrawer
        :createFlag="createRoleFlag"
        :updateFrom="updateRoleFrom"
        :accountFromType="accountFromType"
        :closeDrawer="closeDrawer"
      />

      <!-- 账户弹框 -->
      <el-dialog
        v-model="dialogFormVisible"
        title="Shipping address"
        width="560"
        :show-close="false"
      >
        <template #header="{ close, titleId, titleClass }">
          <div class="my-header">
            <h4 :id="titleId" :class="titleClass"><span />重置密码</h4>
            <el-icon @click="close" class="cursor-pointer"><Close /></el-icon>
          </div>
        </template>
        <el-form
          :model="passwordForm"
          label-width="auto"
          ref="passwordFormRef"
          class="p-6"
        >
          <el-form-item label="用户名">
            <el-input
              v-model="passwordForm.account"
              autocomplete="off"
              disabled
            />
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
            :rules="[
              {
                required: true,
                message: '请输入',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="passwordForm.password"
              autocomplete="off"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="确认密码"
            prop="confirmPassword"
            :rules="[
              {
                required: true,
                message: '请输入',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="passwordForm.confirmPassword"
              autocomplete="off"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="resetForm(passwordFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(passwordFormRef)">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 账户删除弹框 -->
      <el-dialog
        v-model="deleteFormVisible"
        title="Shipping address"
        width="500"
        :show-close="false"
      >
        <template #header="{ titleId, titleClass }">
          <div class="my-header_delete">
            <h4 :id="titleId" :class="titleClass">
              <div class="my_delete_icon" />
              确认删除【{{ deleteName(seachForm.status) }}】？
            </h4>
          </div>
        </template>
        <div class="my_delete_body">
          删除后无法找回，此操作不可逆，请谨慎处理
        </div>
        <template #footer>
          <div class="dialog-footer_delete">
            <el-button @click="deleteFormVisible = false">取消</el-button>
            <el-button type="primary" @click="deleteForm"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 规则预设 -->
      <el-dialog
        v-model="roleSetVisible"
        title="Shipping address"
        width="1400"
        :show-close="false"
      >
        <template #header="{ close, titleId, titleClass }">
          <div class="my-header">
            <h4 :id="titleId" :class="titleClass"><span />规则预设</h4>
            <el-icon @click="close" class="cursor-pointer"><Close /></el-icon>
          </div>
        </template>
        <ruleSet />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="roleSetVisible = false">取消</el-button>
            <el-button type="primary" @click="roleSetVisible = false">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.sublibrary_management {
  .main-table {
    border-radius: 6px;

    .main-table-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 24px;
      border-bottom: 1px solid #dfe1e2;

      .tab-list {
        position: relative;
        top: 1px;
        display: flex;
        align-items: center;

        .tab-list-item {
          padding: 16px 34px;
          font-size: 18px;
          color: #333;
          cursor: pointer;
          background: #f5f7f9;
          border: 1px solid #dfe1e2;
          border-bottom: 0;
        }

        .actived {
          color: #0052d9;
          background: #fff;
          border: 0;
          border-top: 3px solid #0052d9;
        }
      }

      .header-btn {
        display: flex;
        align-items: center;
      }

      .main-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 142px;
        height: 32px;
        font-size: 14px;
        color: #fff;
        background: #0052d9;
        border-radius: 6px;
      }
    }
  }

  :deep(.el-dialog) {
    background: linear-gradient(180deg, #e1ecfe 0%, #fff 30%);
  }

  .my-header,
  .my-header_delete {
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    gap: 16px;
    justify-content: space-between;
    height: 74px;
    padding: 24px;
    border-bottom: 1px solid rgb(91 139 255 / 30%);

    h4 {
      display: flex;
      align-items: center;
      justify-content: center;

      span {
        display: inline-block;
        width: 6px;
        height: 20px;
        margin-right: 10px;
        background: #0052d9;
        border-radius: 3px;
      }
    }
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  .my-header_delete {
    padding: 24px 24px 0;
    border-bottom: none;

    h4 {
      display: flex;
      align-items: center;
      justify-content: center;

      .my_delete_icon {
        display: block;
        width: 28px;
        height: 28px;
        margin-right: 10px;
        background-image: url("@/assets/home/tishi@2x.png");
        background-size: 100% 100%;
      }
    }
  }

  .my_delete_body {
    text-align: center;
  }

  .dialog-footer_delete {
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>
