<template>
  <div class="custom-page">
    <avue-crud
      ref="crudRef"
      v-model:search="state.query"
      v-model:page="state.pageData"
      :table-loading="state.loading"
      :data="state.data"
      :option="state.options"
      @refresh-change="refreshChange"
      @search-reset="searchChange"
      @search-change="searchChange"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
    >
      <template #menu-left>
        <el-button type="primary" icon="plus" @click="rowAdd">选择用户</el-button>
        <el-button type="danger" icon="close" @click="rowAuthAll(state.selection)">批量取消授权</el-button>
      </template>

      <template #status="{ row }">
        <el-tag v-if="row.status == 0" type="success">启用</el-tag>
        <el-tag v-if="row.status == 1" type="danger">禁用</el-tag>
      </template>

      <template #menu="scope">
        <custom-table-operate :actions="state.options.actions" :data="scope" />
      </template>
    </avue-crud>

    <select-user ref="userRef" :role-id="state.roleId" @on-confirm="rowSave" />
  </div>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import { AuthUserList, AuthUserCancel, AuthUserCancelAll, AuthUserSelectAll } from '@/apis/system/auth';
import SelectUser from './selectUser.vue';

const app = useApp();
const route = useRoute();
const crudRef = ref(null);
const userRef = ref(null);
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtn: false,
    selection: true,
    rowKey: 'userId',
    column: [
      {
        label: '登录名',
        prop: 'userName',
        search: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '用户名称',
        prop: 'nickName',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '状态',
        prop: 'status',
        type: 'select',
        dicData: [
          {
            label: '启用',
            value: '0',
          },
          {
            label: '禁用',
            value: '1',
          },
        ],
        value: '0',
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      {
        label: '手机号',
        prop: 'phonenumber',
        search: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '邮箱',
        prop: 'email',
        hide: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
    ],
    actions: [
      {
        type: 'danger',
        name: '取消授权',
        icon: 'close',
        event: ({ row }) => rowAuth(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  roleId: '',
});

// 加载
const loadData = () => {
  state.loading = true;
  state.query.roleId = route.query.id;
  AuthUserList(state.query)
    .then((res) => {
      if (res.code === 200) {
        const { current, size, total, records } = res.data;
        state.data = records;
        state.pageData = {
          currentPage: current || 1,
          pageSize: size || 10,
          total: total,
        };
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
      state.data = [];
    })
    .finally(() => {
      state.loading = false;
    });
};

loadData();

// 页数
const currentChange = (current) => {
  state.query.current = current;
  loadData();
};

// 条数
const sizeChange = (size) => {
  state.query.size = size;
  loadData();
};

// 搜索
const searchChange = (params, done) => {
  if (done) done();
  state.query = params;
  state.query.current = 1;
  loadData();
};

// 刷新
const refreshChange = () => {
  loadData();
  app.$message.success('刷新成功');
};

// 选择
const selectionChange = (rows) => {
  state.selection = rows;
};

// 取消授权
const rowAuth = (row) => {
  const roleId = route.query.id;
  app
    .$confirm(`确认要取消该用户 ${row.userName} 角色吗？`, '确定取消', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      AuthUserCancel({ roleId: roleId, userId: row.userId })
        .then((res) => {
          if (res.code === 200) {
            app.$message.success('取消授权成功！');
            loadData();
          }
        })
        .catch((err) => {
          app.$message.error(err.msg);
        });
    })
    .catch(() => {});
};

// 批量取消授权
const rowAuthAll = () => {
  const roleId = route.query.id;
  const userIds = state.selection.map((item) => item.userId);
  app
    .$confirm(`是否取消选中用户授权数据项？`, '确定取消', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      AuthUserCancelAll({ roleId: roleId, userIds: userIds.join(',') })
        .then((res) => {
          if (res.code === 200) {
            app.$message.success('取消授权成功！');
            loadData();
          }
        })
        .catch((err) => {
          app.$message.error(err.msg);
        });
    })
    .catch(() => {});
};

// 添加
const rowAdd = () => {
  state.roleId = route.query.id;
  userRef?.value && userRef.value.show();
};

// 授权用户
const rowSave = (data) => {
  AuthUserSelectAll(data)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('授权用户成功!');
        loadData();
        userRef.value.hide();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    });
};
</script>
