<template>
  <section class="card-height-full card-flex-1 card-flex-column">
    <a-row :gutter="8" class="card-height-full card-flex-1">
      <!-- 角色列表 -->
      <a-col :xs="24" :sm="24" :md="14" :lg="14" :xl="14" class="card-flex-column card-height-full card-full-left">
        <a-card :bordered="false" class="search-card-class">
          <!-- 条件搜索 -->
          <a-form layout="inline" labelAlign="right" @keydown.enter.native="handleQuery">
            <a-row :gutter="[16, 16]">
              <a-col :md="8" :sm="24">
                <a-form-item label="角色名">
                  <a-input v-model="queryParam.roleName" placeholder="请输入角色名" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="组织名">
                  <a-input v-model="queryParam.orgName" placeholder="请输入组织名" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                  <a-button type="primary" @click="handleQuery"> <a-icon type="search" />查询 </a-button>
                  <a-button click="resetQuery"> <a-icon type="redo" />重置 </a-button>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
        <a-card :bordered="false" class="table-card-class">
            <!-- 操作 -->
            <div class="table-operations">
              <a-button
                type="dashed"
                shape="circle"
                :loading="loading"
                :style="{ float: 'right' }"
                icon="reload"
                @click="getList"
              />
              <a-button type="primary" @click="$refs.createForm.handleAdd()" v-hasPermi="['system:role:add']">
                <a-icon type="plus" />新增
              </a-button>
              <!-- <a-button
              type="primary"
              :disabled="single"
              @click="$refs.createForm.handleUpdate(undefined, ids)"
              v-hasPermi="['system:role:edit']"
            >
              修改
            </a-button> -->
              <a-button
                class="delete-btn"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['system:role:remove']"
              >
                <a-icon type="delete" />删除
              </a-button>
            </div>
            <!-- 数据展示 -->
              <a-table
                :loading="loading"
                size="middle"
                :scroll="{ x: '600px', y: innerHeight }"
                rowKey="roleId"
                :columns="columns"
                :data-source="list"
                :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                :pagination="false"
                :customRow="customRowClick"
                :row-class-name="rowClassName"
              >
                <span slot="status" slot-scope="text, record">
                  <a-popconfirm
                    ok-text="是"
                    cancel-text="否"
                    @confirm="confirmHandleStatus(record)"
                    @cancel="cancelHandleStatus(record)"
                  >
                    <span slot="title"
                      >确认<b>{{ record.status === '1' ? '启用' : '关闭' }}</b
                      >吗?</span
                    >
                    <a-switch
                      checked-children="开"
                      un-checked-children="关"
                      :checked="record.status == 0"
                      :disabled="record.roleId == '1'"
                    />
                  </a-popconfirm>
                </span>
                <!-- <span slot="createTime" slot-scope="text, record">
              {{ parseTime(record.createTime) }}
            </span> -->
                <span slot="operation" slot-scope="text, record">
                  <a
                    @click="$refs.createForm.handleUpdate(record, undefined)"
                    v-hasPermi="['system:role:edit']"
                    :disabled="record.roleId == '1'"
                  >
                    修改
                  </a>
                  <!--  <a-divider type="vertical" v-hasPermi="['system:role:edit']" />
              <a @click="$refs.createDataScopeForm.handleDataScope(record)" v-hasPermi="['system:role:edit']">
                <a-icon type="lock" />数据权限
              </a> -->
                  <a-divider type="vertical" v-hasPermi="['system:role:remove']" />
                  <a
                    @click="handleDelete(record)"
                    v-hasPermi="['system:role:remove']"
                    :disabled="record.roleId == '1'"
                    class="reset-or-delete-link"
                    >删除
                  </a>
                </span>
              </a-table>
          <!-- 分页 -->
          <a-pagination
            show-size-changer
            show-quick-jumper
            :current="queryParam.pageNum"
            :total="total"
            :page-size="queryParam.pageSize"
            :showTotal="(total) => `共 ${total} 条`"
            @showSizeChange="onShowSizeChange"
            @change="changeSize"
          />
        </a-card>
      </a-col>
      <!-- 权限管理 -->
      <a-col :xs="24" :sm="24" :md="10" :lg="10" :xl="10" class="card-flex-column card-height-full card-full-right">
        <a-card :bordered="false" class="table-card-class">
          <a-tabs default-active-key="1">
            <a-tab-pane key="1" tab="菜单权限">
              <menu-permissions ref="menuPermissions" :statusOptions="statusOptions" @ok="getList"></menu-permissions>
            </a-tab-pane>
            <a-tab-pane key="2" tab="用户管理">
              <role-user ref="roleUser" :role="selectedRole" />
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>
    <!-- 增加修改 -->
    <create-form ref="createForm" :statusOptions="statusOptions" @ok="getList" />
    <!-- 批量删除 -->
    <delete-form ref="DeleteFormRef" @delete-roles="deleteRoles" />
    <!-- 数据权限对话框 -->
    <create-data-scope-form ref="createDataScopeForm" @ok="getList" />
  </section>
</template>

<script>
import { listRole, delRole, exportRole, changeRoleStatus } from '@/api/system/role'
import CreateForm from './modules/CreateForm'
import CreateDataScopeForm from './modules/CreateDataScopeForm'
import MenuPermissions from './modules/MenuPermissions'
import RoleUser from './modules/RoleUser.vue'
import DeleteForm from './modules/DeleteForm'
import { mixin, mixinDevice } from '@/utils/mixin'
export default {
  name: 'Role',
  mixins: [mixin, mixinDevice],
  components: {
    CreateForm,
    CreateDataScopeForm,
    MenuPermissions,
    RoleUser,
    DeleteForm,
  },
  data() {
    return {
      list: [],
      selectedRowKeys: [],
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      loading: false,
      total: 0,
      // 状态数据字典
      statusOptions: [],
      queryParam: {
        pageNum: 1,
        pageSize: 20,
        roleName: undefined,
        orgName: undefined,
        roleKey: undefined,
        status: undefined,
      },
      columns: [
        // {
        //   title: '角色编号',
        //   dataIndex: 'roleId',
        //   align: 'center',
        // },
        {
          title: '角色名',
          dataIndex: 'roleName',
          align: 'center',
        },
        {
          title: '组织',
          dataIndex: 'org.orgName',
          align: 'center',
        },
        // {
        //   title: '权限标识',
        //   dataIndex: 'roleKey',
        //
        //   align: 'center',
        // },
        // {
        //   title: '排序',
        //   dataIndex: 'roleSort',
        //   align: 'center',
        // },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
          align: 'center',
        },
        // {
        //   title: '创建时间',
        //   dataIndex: 'createTime',
        //   scopedSlots: { customRender: 'createTime' },
        //   align: 'center',
        // },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 120,
          scopedSlots: { customRender: 'operation' },
          align: 'center',
          fixed: 'right',
        },
      ],
      activeKey: 1,
      // 表单参数
      // form: {
      //   roleId: undefined,
      //   roleName: undefined,
      //   orgName: undefined,
      //   roleKey: undefined,
      //   roleSort: 0,
      //   status: '0',
      //   menuIds: [],
      //   menuCheckStrictly: true,
      //   remark: undefined,
      // },
      // open: false,
      // menuExpand: false,
      // menuNodeAll: false,
      // rules: {
      //   roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
      //   roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
      //   roleSort: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }],
      // },
      // defaultProps: {
      //   children: 'children',
      //   title: 'label',
      //   key: 'value',
      // },

      selectedRole: undefined,
    }
  },
  computed: {
    innerHeight() {
      const h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
      return h - 315
    },
  },
  filters: {},
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.result
    })
  },
  watch: {},
  methods: {
    /** 查询定时任务列表 */
    getList() {
      this.loading = true
      listRole(this.queryParam).then((response) => {
        this.list = response.result.data
        this.total = response.result.totalCount
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.queryParam = {
        pageNum: 1,
        pageSize: 20,
        roleName: undefined,
        orgName: undefined,
        roleKey: undefined,
        status: undefined,
      }
      this.handleQuery()
    },
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map((item) => {
        return {
          id: item.roleId,
          name: item.roleName,
        }
      })
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    customRowClick(record, index) {
      return {
        on: {
          dblclick: () => {
            console.log(record, index)
            this.selectedRole = { ...record }
            this.$refs.menuPermissions.handleUpdate(record, undefined)
          },
        },
      }
    },
    /* 任务状态修改 */
    confirmHandleStatus(row) {
      const text = row.status === '1' ? '启用' : '关闭'
      row.status = row.status === '0' ? '1' : '0'
      changeRoleStatus(row.roleId, row.status)
        .then(() => {
          this.$message.success(text + '成功', 3)
        })
        .catch(function () {
          this.$message.error(text + '异常', 3)
        })
    },
    cancelHandleStatus(row) {},
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this
      const roleIds = row.roleId || this.ids
      if (row.roleId) {
        this.$confirm({
          title: '确认删除所选中数据?',
          content: '当前选中编号为' + roleIds + '的数据',
          onOk() {
            return that.deleteRoles(roleIds)
          },
          onCancel() {},
        })
      } else {
        this.$refs.DeleteFormRef.openDeleteForm(roleIds)
      }
    },
    deleteRoles(roleIds) {
      delRole(roleIds).then(() => {
        this.onSelectChange([], [])
        this.getList()
        this.$message.success('删除成功', 3)
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk() {
          return exportRole(that.queryParam).then((response) => {
            that.download(response.msg)
            that.$message.success('导出成功', 3)
          })
        },
        onCancel() {},
      })
    },
    rowClassName(record) {
      return record?.roleId === this.selectedRole?.roleId ? 'selected-table-row' : ''
    },
  },
}
</script>

<style lang="less" scoped>
.table-operations {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 5px;
 
}
.ant-pagination{
  display: flex;
  justify-content: flex-end;
  margin-bottom: 5px;
  margin-top: 5px;
}
.card-height-full {
  /deep/ .ant-card-body {
    display: flex;
    flex: 1;
    flex-direction: column;
  }
}
/deep/ .ant-table-tbody .selected-table-row {
  background: #b6bdc2 !important;
}
</style>
