<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="" prop="params.code">
              <CustomInput
                v-model:params="queryParams.params.code"
                placeholder="编码"
                clearable
                @keyUpEvent="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="" prop="params.name">
              <CustomInput
                v-model:params="queryParams.params.name"
                placeholder="名称"
                clearable
                @keyUpEvent="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleQuery" v-has-perm="['sys:user-group:search']">搜索</el-button>
        <el-button @click="resetQuery" v-has-perm="['sys:user-group:reset']">重置</el-button>
      </div>
    </el-row>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <span>更新时间：{{currentTime}}</span>
        <div class="page-table-operateBtns">
          <el-button type="primary" @click="openAddUserDialog" v-has-perm="['sys:user-group:designUser']">
            分配用户
          </el-button>
          <el-button type="primary" @click="openAddRoleDialog" v-has-perm="['sys:user-group:designRole']">
            分配角色
          </el-button>
          <el-button type="primary" @click="handleAdd" v-has-perm="['sys:user-group:add']">
            <el-icon><Plus /></el-icon>
            创建
          </el-button>
          <el-popover :persistent="false" placement="right" popper-class="config-table-wrap" trigger="click">
            <template #reference>
              <el-button class="operateBtns-setting">
                <svg-icon icon-class="table_title" width="16px" height="16px"/>
              </el-button>
            </template>
            <ConfigTable :list="column" @updateList="updateList"/>
          </el-popover>

        </div>
      </div>
      <el-table
        border
        :data="userGroup"
        highlight-current-row
        row-key="id"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" align="center"/>
        <template
          v-for="(col,index) in column"
          :key="index"
        >
          <el-table-column
            v-if="!col.hide"
            :label="col.header"
            show-overflow-tooltip
          >
            <template #default="scope">
              <span v-if="col.field === 'status'">
                <span v-if="scope.row[col.field]" class="table-status-active">启用</span>
                <span v-else class="table-status-inActive">禁用</span>
              </span>
              <span v-else>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>

        <el-table-column
          width="250"
          label="操作"
          align="center"
          class-name="table-operation"
          fixed="right"
        >
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleUpdate(scope.row)" v-if="!scope.row.status" v-has-perm="['sys:user-group:update']">
              编辑
            </el-button>
            <div class="splitLine" v-if="!scope.row.status" v-has-perm="['sys:user-group:enable','sys:user-group:disable']"></div>
            <el-button type="primary" link v-if="!scope.row.status" @click="enable(scope.row)" v-has-perm="['sys:user-group:enable']">
              启用
            </el-button>
            <el-button type="primary" link v-if="!!scope.row.status" @click="disable(scope.row)" v-has-perm="['sys:user-group:disable']">
              禁用
            </el-button>
            <div class="splitLine" v-has-perm="['sys:user-group:userlist']"></div>
            <el-button type="primary" link @click.stop="openUserListDrawer(scope.row)" v-has-perm="['sys:user-group:userlist']">
              用户清单
            </el-button>
            <div class="splitLine" v-has-perm="['sys:user-group:rolelist']"></div>
            <el-button type="primary" link @click.stop="openRoleListDrawer(scope.row)" v-has-perm="['sys:user-group:rolelist']">
              角色清单
            </el-button>
          </template>
        </el-table-column>
        <template v-slot:empty>
          <svg-icon icon-class="noData" width="160px" height="160px"/>
        </template>
      </el-table>
      <pagination
        v-if="total>0"
        :total="total"
        v-model:pageNumTo="queryParams.pageNum"
        v-model:pageSizeTo="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </div>
    <!--  新增或编辑  -->
    <el-drawer
      :title="dialog.title"
      v-model="dialog.visible"
      @close="cancel"
      @opened="dialogOpend"
    >
      <el-form
        ref="formDataRef"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-drawer>
    <!-- 用户清单的抽屉 -->
    <UserListDrawer
      v-if="userListDrawer.visible"
      :selectItem="selectItem"
      :userListDrawer="userListDrawer"
    ></UserListDrawer>
    <!-- 分配用户的弹窗 -->
    <AddUserDialog
      v-if="addUserDialog.visible"
      :selectGroup="multiSelection"
      :selectedUsers="[]"
      :addUserDialog="addUserDialog"
      @updateVisible="updateUserVisible"
    ></AddUserDialog>
    <!-- 角色清单的抽屉 -->
    <RoleListDrawer
      v-if="roleListDrawer.visible"
      :selectItem="selectItem"
      :roleListDrawer="roleListDrawer"
    ></RoleListDrawer>
    <!-- 分配角色的弹窗 -->
    <AddRoleDialog
      v-if="addRoleDialog.visible"
      :selectGroup="multiSelection"
      :selectedRoles="[]"
      :addRoleDialog="addRoleDialog"
      @updateVisible="updateRoleVisible"
    ></AddRoleDialog>
  </div>
</template>

<script lang="ts">
export default {
  name: 'userGroup'
};
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from 'vue';
import { ElForm, ElMessageBox  } from 'element-plus';
import {
  getGroupList,
  addGroup,
  updateGroup,
  enableGroup,
  disableGroup
} from '@/api/userGroup';
import UserListDrawer from './userListDrawer.vue';
import AddUserDialog from './addUserDialog.vue'
import RoleListDrawer from './roleListDrawer.vue';
import AddRoleDialog from './addRoleDialog.vue'

const queryFormRef = ref(ElForm);
const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();

const state = reactive({
  queryParams: {
    params: {
      code:'',
      name:'',
    },
    pageNum: 1,
    pageSize: 10
  },
  total: 0,
  userGroup: [] as any,
  dialog: {
    title: '新增',
    visible: false
  },
  formData: {
    code: '',
    name: '',
    remark: ''
  } as any,
  rules: {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  },
  column: [] as any,
  selectItem: undefined as any,
  currentTime: '',
  multiSelection: [] as any,
  userListDrawer: {// 用户清单
    title: '用户清单',
    visible: false
  },
  addUserDialog:{// 分配用户
    title: '分配用户',
    visible: false
  },
  roleListDrawer: {// 角色清单
    title: '角色清单',
    visible: false
  },
  addRoleDialog:{// 分配角色
    title: '分配角色',
    visible: false
  }
})
const {
  queryParams,
  total,
  userGroup,
  dialog,
  formData,
  rules,
  column,
  selectItem,
  currentTime,
  multiSelection,
  userListDrawer,
  addUserDialog,
  roleListDrawer,
  addRoleDialog
} = toRefs(state);

onMounted(() => {
  state.column = [
    { header: '编码',field:'code',hide: false },
    { header: '名称',field:'name',hide: false },
    { header: '备注',field:'remark',hide: false },
    { header: '状态',field:'status',hide: false },
    { header: '创建人',field:'createUserName',hide: false },
    { header: '创建时间',field:'createTime',hide: false },
    { header: '更新人',field:'lastUpdateUserName',hide: false },
    { header: '更新时间',field:'lastUpdateTime',hide: false },
  ]
  //handleQuery();
});
// 更新列
function updateList(col: any) {
  state.column = col;
}
function handleQuery() {
  getGroupList(state.queryParams)
    .then((res:any)=>{
      console.log(res.data);
      state.userGroup = res.data.list;
      state.total = res.data.total;
      showCurrentTime();
    })
    .catch(() => {});
}
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}
function showCurrentTime() {
  let date = new Date()
  state.currentTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ":" +
    (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
}
const handleSelectionChange = (val: any) => {
  state.multiSelection = val;
}
/**
 *  启用
 */
function enable(row:any) {
  state.selectItem = row;
  ElMessageBox.confirm(
    '确认启用?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      enableGroup({
        data:{
          dataId: row.dataId
        }
      }).then(() => {
        proxy.$ElMessage.success('启用成功');
        cancel();
        handleQuery();
      });
    })
    .catch(() => {

    })
}
/**
 *  禁用
 */
function disable(row:any) {
  state.selectItem = row;
  ElMessageBox.confirm(
    '确认禁用?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      disableGroup({
        data:{
          dataId: row.dataId
        }
      }).then(() => {
        proxy.$ElMessage.success('禁用成功');
        cancel();
        handleQuery();
      });
    })
    .catch(() => {

    })
}

/**
 * 新增用户 dialog
 */
function handleAdd() {
  selectItem.value = undefined;
  dialog.value = {
    title: '新增',
    visible: true
  };
}
/**
 * 编辑用户 dialog
 */
function handleUpdate(row: any) {
  state.dialog = {
    title: '编辑',
    visible: true
  };
  state.selectItem = row;
}

function dialogOpend() {
  formDataRef.value.resetFields();
  if(state.selectItem) {
    state.formData = {
      code: state.selectItem.code,
      name: state.selectItem.name,
      remark: state.selectItem.remark
    }
  }
}

/**
 * 取消关闭弹窗
 */
function cancel() {
  state.dialog.visible = false;
}
/**
 * 保存
 */
function submitForm() {
  formDataRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (state.selectItem) {// 编辑
        state.formData.dataId = state.selectItem.dataId;
        updateGroup({data:state.formData}).then(() => {
          proxy.$ElMessage.success('修改成功');
          cancel();
          handleQuery();
        });
      } else {
        addGroup({data:state.formData}).then(() => {
          proxy.$ElMessage.success('新增成功');
          cancel();
          handleQuery();
        });
      }
    }
  });
}
/******************************* 用户清单 start *****************************/
function openUserListDrawer(row:any) {
  state.selectItem = row;
  state.userListDrawer.visible = true;
}
function openAddUserDialog() {
  if(state.multiSelection && state.multiSelection.length === 0) {
    proxy.$ElMessage.warning('请选择用户组');
    return;
  }
  state.addUserDialog.visible = true;
}
function updateUserVisible() {
  state.addUserDialog.visible = false;
  handleQuery();
}
/******************************* 用户清单 end *****************************/
/******************************* 角色清单 start *****************************/
function openRoleListDrawer(row:any) {
  state.selectItem = row;
  state.roleListDrawer.visible = true;
}
function openAddRoleDialog() {
  if(state.multiSelection && state.multiSelection.length === 0) {
    proxy.$ElMessage.warning('请选择用户组');
    return;
  }
  state.addRoleDialog.visible = true;
}
function updateRoleVisible() {
  state.addRoleDialog.visible = false;
  handleQuery();
}
/******************************* 角色清单 end *****************************/

</script>
<style scoped lang="scss">

</style>
