<template>
  <div class="p-4">
    <div class="role-header">
      <div class="handle-btns">
        <span class="label-item">角色名称：</span>
        <div class="select-item">
          <a-input v-model:value="searchValue" style="width: 100%;" placeholder="请输入名称"></a-input>
        </div>
        <a-button class="btn" type="primary" @click="searchTable">查询</a-button>
      </div>
      <div class="handle-btns">
        <a-button class="btn" type="primary" @click="handleAdd">新增</a-button>
        <a-button class="btn" type="primary" @click="handleSave">保存</a-button>
      </div>
    </div>
    <div class="role-body">
      <!-- 左侧表格区域 -->
      <div class="left-table">
        <BasicTable @register="registerTable" class="basic-table">
          <template #action="{ record }">
            <TableAction :actions="[
              {
                label: '修改',
                tooltip: '修改',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                tooltip: '删除',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]" />
          </template>
        </BasicTable>
      </div>
      <!-- 右侧操作区域 -->
      <div class="right-opt">
        <div class="form-box">
          <a-form ref="formRef" :model="editForm" :rules="rules" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
            <a-form-item label="角色名称" name="groupName">
              <a-input v-model:value="editForm.groupName" style="width: 100%" placeholder="请输入名称" />
            </a-form-item>
            <a-form-item label="系统功能" name="checkedKeys">
              <div class="tree-box">
                <a-tree checkable :tree-data="menuTreeData" v-model:checkedKeys="editForm.checkedKeys" class="tree-list"
                  :replaceFields="{ children: 'children', key: 'id', title: 'name' }"
                  :scopedSlots="{ title: customTitle }">
                </a-tree>
              </div>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </div>
    <RoleModal v-if="ifShowModal" @closeModal="ifShowModal = false" @onSubmit="onSubmit" />
  </div>
</template>
<script>
import { defineComponent, nextTick, reactive, ref, toRefs, watch, onMounted, createVNode, computed } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import RoleModal from './RoleModal.vue';
import { message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
//角色列表api
import { roleList } from '/@/api/sys/user';
//菜单树api
import { getMenuList } from '/@/api/sys/menu';
//获取与保存角色绑定的菜单数据
import { saveRoleMenu, getRoleMenus } from '/@/api/sys/user';
//保存角色信息
import { delRole, getRoleListByPage, setRoleStatus, saveOrUpdateRoleInfoWithMenu } from '/@/api/system/system';

export default defineComponent({
  name: 'RoleManagement',
  components: { BasicTable, TableAction, ExclamationCircleOutlined, RoleModal },
  setup() {
    const formRef = ref(null)
    const ifShowModal = ref(false)
    const searchValue = ref('')
    const editForm = ref({
      groupName: '',
      sort: '1',
      groupid: '',
      checkedKeys: []
    })
    //表格筛选
    const filteredInfo = ref({
      groupName: null,
    });
    //按名称查询
    const searchTable = () => {
      formRef.value.resetFields();
      filteredInfo.value['groupName'] = [searchValue.value]
    }
    //新增
    const handleAdd = () => {
      ifShowModal.value = true
    }
    //修改
    const handleEdit = (record) => {
      editForm.value.groupName = record.groupName
      editForm.value.sort = record.sort
      editForm.value.groupid = record.groupid
      editForm.value.checkedKeys = []
      getRoleMenus({
        menusId: true,
        systemId: '1',
        roleIds: record.groupid || 'FB264E2A-BBEN-FB9T-9CEU-FF94AF30DB87',//values.groupid,
      }).then(res => {
        editForm.value.checkedKeys = res.map(i => i.id);
      })
    }
    //保存
    const handleSave = () => {
      if (!editForm.value.groupid) {
        message.error('没有选择角色')
        return;
      }
      // 首先保存用户信息，再保存菜单绑定数据
      formRef.value.validate().then(() => {
        let params = {
          groupName: editForm.value.groupName,
          sort: '1',
          groupid: editForm.value.groupid
        }
        saveOrUpdateRoleInfoWithMenu(params).then((res) => {
          if (res === 1) {
            let menusIds = [...new Set([].concat(editForm.value.checkedKeys))]
            saveRoleMenu({
              menusId: menusIds.join(","),
              systemId: "1",
              roleId: editForm.value.groupid
            }).then(r => {
              if (r) {
                message.success('修改成功')
              } else {
                message.error('权限修改失败')
              }
              reload();
              formRef.value.resetFields();
            })
          } else {
            message.error('角色修改失败')
            formRef.value.resetFields();
          }
        });
      }).catch((error) => {
        console.log('error', error);
      });
    }
    //删除
    const handleDelete = (record) => {
      Modal.confirm({
        title: '删除提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确定删除该角色？',
        centered: true,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: (() => {
          delRole(record.groupid).then(res => {
            if (res.resp_code === 0) {
              message.success(res.resp_msg)
              reload();
            } else {
              message.error(res.resp_msg)
            }
          })
          formRef.value.resetFields();
        })
      });
    }

    //表格列
    const columns = computed(() => {
      const filtered = filteredInfo.value || {};
      return [
        {
          title: '角色名称',
          align: 'center',
          dataIndex: 'groupName',
          key: 'groupName',
          filteredValue: filtered.groupName || null,
          onFilter: (value, record) => record.groupName.includes(value)
        },
      ];
    });
    const [registerTable, { reload }] = useTable({
      title: '',
      api: roleList,		 //数据
      // dataSource: [],
      columns: columns,        //表头配置
      bordered: false,
      striped: false,
      useSearchForm: false,     //开启搜索区域
      pagination: {
        hideOnSinglePage: false
      },
      canResize: true,
      showTableSetting: false,  // 显示表格设置
      showIndexColumn: true,
      actionColumn: {
        width: 120,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
      },
    });

    const rules = {
      groupName: [{
        required: true,
        message: '请输入角色名称',
        trigger: 'blur'
      }]
    };
    const menuTreeData = ref([])
    onMounted(() => {
      //此处请求菜单树
      getMenuList().then(res => {
        menuTreeData.value = res
        console.log("此处请求菜单树:", menuTreeData.value);
      })
    })
    const onSubmit = (e) => {
      ifShowModal.value = false
      e && reload()
    }

    function customTitle({ node }) {
      if (node.status === 1) {
        return null;
      }
      return node.name;
    }
    return {
      customTitle,
      ifShowModal,
      formRef,
      searchValue,
      filteredInfo,
      editForm,
      rules,
      menuTreeData,
      searchTable,
      handleAdd,
      handleEdit,
      handleSave,
      handleDelete,
      registerTable,
      onSubmit
    };
  },
});
</script>
<style lang="less" scoped>
.p-4 {
  height: 100%;

  .role-header {
    padding: 10px;
    width: 100%;
    height: 70px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 6px;

    .handle-btns {
      margin-right: 10px;
      display: flex;
      align-items: center;

      &:first-child {
        margin-left: 10px;
        margin-right: 0;
      }

      .select-item {
        width: 200px;
        margin-right: 20px;
      }

      .btn {
        margin-right: 16px;

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .role-body {
    margin-top: 10px;
    height: calc(100% - 80px);
    display: flex;
    justify-content: space-between;

    .left-table {
      padding: 20px 20px 0;
      height: 100%;
      width: 860px;
      margin-right: 10px;
      background-color: #fff;
      border-radius: 6px;

      .basic-table {
        height: calc(100% - 20px);

        ::v-deep .ant-table-title {
          padding: 0 !important;
          display: none;
        }
      }
    }

    .right-opt {
      padding: 20px 20px 0;
      width: calc(100% - 870px);
      height: 100%;
      background-color: #fff;
      border-radius: 6px;

      .form-box {
        // max-height: 855px;
        // overflow: auto;

        ::v-deep .tree-box {
          width: 100%;
          height: 680px;
          overflow: auto;
          border-radius: 2px;
          box-sizing: border-box;
          border: 1px solid #D9D9D9;

          &::-webkit-scrollbar {
            width: 3px;
          }

          &::-webkit-scrollbar-thumb {
            border-radius: 2px;
            background: #ccd5df;
          }

          &::-webkit-scrollbar-track {
            display: none;
          }
        }
      }
    }
  }
}
</style>
