<template>
  <div class="user h-full">
    <div v-if="perm.BUTTON_Add" class="page-action page-header">
      <t-button theme="primary" @click="handleAdd">
        <template #icon><svg-icon name="add-circle" color="#fff" /></template>
        新增用户
      </t-button>
    </div>
    <div class="flex-1 page-wrap">
      <t-table
        size="small"
        row-key="id"
        :columns="columns"
        :data="tableData"
        bordered
        :pagination="{
          defaultCurrent: 1,
          defaultPageSize: 10,
          onChange,
          showJumper: true,
          showPageSize: false,
          total: pagination.total,
          current: pagination.pageNumber,
        }"
        v-loading="tableLoading"
      >
        <template #roles="{ row }">
          {{ row.roles.map((item) => item.name).join('、') }}
        </template>
        <template #enable="{ col, row }">
          <status-tag :value="row[col.colKey]" type="enable"></status-tag>
        </template>
        <template #operate="{ row }">
          <div class="table-operations">
            <t-link
              v-if="perm.LINK_InitPwd"
              theme="primary"
              hover="color"
              @click="handleModifyPwd(row)"
            >
              初始化密码
            </t-link>

            <t-link
              v-if="perm.LINK_Update"
              theme="primary"
              hover="color"
              @click="handleEdit(row)"
            >
              修改
            </t-link>
            <t-link
              :disabled="!row.bandSupplier"
              theme="primary"
              hover="color"
              @click="handleBindSupplier(row)"
            >
              绑定供应商
            </t-link>
            <t-link
              v-if="perm.LINK_Enable"
              theme="primary"
              hover="color"
              @click="handleEnable(row)"
            >
              {{ row.enable ? '禁用' : '启用' }}
            </t-link>
          </div>
        </template>
      </t-table>
    </div>

    <AddUserDialog
      v-if="perm.BUTTON_Add || perm.LINK_Update"
      v-model:visible="showAddUserDialog"
      :curRow="curRow"
      @success="addSuccess"
    ></AddUserDialog>

    <UpdateUserPwdDialog
      v-model:visible="showUpdateUserPwdDialog"
      :curRow="curRow"
      @success="updatePwdSuccess"
    >
    </UpdateUserPwdDialog>

    <BindSupplierDialog
      v-model:visible="showBindSupplierDialog"
      :curRow="curRow"
      @success="bindSupplierSuccess"
      :options="canBindSupplierList"
    >
    </BindSupplierDialog>
  </div>
</template>

<script setup name="User">
import { ref } from 'vue';
import { getUserList, initUserPassword, getSupplierByUser } from '@/api/user';
import useFetchTable from '@/hooks/useFetchTable';
import AddUserDialog from './add-user-dialog.vue';
import UpdateUserPwdDialog from './update-user-pwd-dialog.vue';
import { toggleUserStatus } from '@/api/user';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import usePermission from '@/hooks/usePermission';
import BindSupplierDialog from './bind-supplier-dialog.vue';
const { perm } = usePermission();

const showAddUserDialog = ref(false);
const showUpdateUserPwdDialog = ref(false);
const curRow = ref(null);
const canBindSupplierList = ref([]);
const columns = [
  { colKey: 'loginName', title: '登录名', width: 140 },
  { colKey: 'realName', title: '姓名', minWidth: 90 },
  { colKey: 'genderStr', title: '性别', width: 70 },
  { colKey: 'mobileNumber', title: '手机', width: 130 },
  { colKey: 'orgName', title: '所属节点', width: 160 },
  { colKey: 'roles', title: '角色', minWidth: 130 },
  { colKey: 'enable', title: '状态', width: 90 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 280,
  },
];

const {
  loading: tableLoading,
  pagination,
  tableData,
  fetchData,
  onChange,
} = useFetchTable(getUserList);

const handleAdd = () => {
  curRow.value = null;
  showAddUserDialog.value = true;
};

const handleEdit = (row) => {
  curRow.value = row;
  showAddUserDialog.value = true;
};
const showBindSupplierDialog = ref(false);
const handleBindSupplier = (row) => {
  curRow.value = row;
  getSupplierByUser({ userRoleEnum: row.userRoleEnum })
    .then((res) => {
      canBindSupplierList.value = res;
    })
    .catch((err) => {
      canBindSupplierList.value = [];
    });
  showBindSupplierDialog.value = true;
};
const handleEnable = (row) => {
  const name = !row.enable ? '启用' : '禁用';

  const confirmDia = DialogPlugin({
    header: `${name}提示`,
    body: `是否${name}该用户？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await toggleUserStatus({
        id: row.id,
        enable: !row.enable,
      }).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      row.enable = !row.enable;
    },
  });
};

const handleModifyPwd = (row) => {
  curRow.value = row;
  const confirmDia = DialogPlugin({
    header: `提示`,
    body: `初始密码为手机后6位，是否初始化用户 [ ${row.realName} ] 的密码？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await initUserPassword({
        id: row.id,
      }).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
    },
  });
  // showUpdateUserPwdDialog.value = true;
};

const addSuccess = () => {
  showAddUserDialog.value = false;
  MessagePlugin.success('操作成功');
  fetchData();
};
const updatePwdSuccess = () => {
  // showUpdateUserPwdDialog.value = false;
  MessagePlugin.success('操作成功');
};

const bindSupplierSuccess = () => {
  showBindSupplierDialog.value = false;
  MessagePlugin.success('绑定成功');
};
</script>
