<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="关键字">
              <a-input v-model="queryParam.keyword" placeholder="请输入账户或姓名"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              label="客户端"
            >
              <a-select v-model="queryParam.clientId" @change="clientIdChange">
                <a-select-option
                  v-for="item in clientIds"
                  :key="item.clientId"
                  :label="item.name"
                  :value="item.clientId">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8 || 24" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button
                type="primary"
                @click="()=>{
                  this.getMenus()
                  $refs.table.refresh(true)
                }">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="$refs.baseModal.base(null,queryParam.clientId)">新增</a-button>
      <!-- <a-button type="dashed" @click="tableOption">{{ optionAlertShow && '关闭' || '开启' }} alert</a-button> -->
      <!--<a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-popconfirm title="是否要冻结所选角色？" @confirm="handleChangeRoleStatus()">
            <a-menu-item key="1"><a-icon type="delete" /><a>删除</a></a-menu-item>
          </a-popconfirm>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>-->
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="roleId"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      showPagination="auto"
    >
      <!--<span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>-->
      <span slot="status" slot-scope="text">
        <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
      </span>

      <span slot="action" slot-scope="record">
        <template>
          <a @click="handleEdit(record)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm v-if="record.status === 1" title="是否要冻结角色？" @confirm="handleChangeRoleStatus(record.roleId, 2)">
            <a>冻结</a>
          </a-popconfirm>
          <a-popconfirm v-if="record.status === 2" title="是否要启用该角色？" @confirm="handleChangeRoleStatus(record.roleId, 1)">
            <a>启用</a>
          </a-popconfirm>
          <!--<a-divider type="vertical" />
          <a-popconfirm title="是否要重置该用户密码？" @confirm="handleResetPwd(record.id)">
            <a>重置密码</a>
          </a-popconfirm>-->
        </template>
      </span>
    </s-table>
    <base-form ref="baseModal" :menus="menus" @ok="handleOk"/>
    <!--<create-form ref="createModal" @ok="handleOk" :roleList="roleList"/>-->
    <!--<update-form ref="updateModal" @ok="handleOk" :roleList="roleList"/>-->
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseForm from './modules/BaseForm'
import { Constant } from '@/constant'
import BaseTool from '@/utils/tool'
import { getRolePage, fetchRole, updateStatus } from '@/api/upms/role'
import { getMenuTree } from '@/api/upms/menu'
import { queryClientDetail } from '@/api/upms/oauth-client-detail'

export default {
  name: 'RoleList',
  components: {
    STable,
    Ellipsis,
    BaseForm
  },
  data () {
    return {
      mdl: {},
      // 查询参数
      queryParam: {
        clientId: 'end'
      },
      // 表头
      columns: [
        {
          title: '角色名称',
          dataIndex: 'roleName'
        },
        {
          title: '角色标识',
          dataIndex: 'roleCode'
        },
        {
          title: '所属客户端',
          dataIndex: 'clientId'
        },
        {
          title: '描述',
          dataIndex: 'remark'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          sorter: true
        },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData.parameter', parameter)
        parameter = {
          ...parameter,
          dataScope: {
            sortBy: 'desc',
            sortName: 'update_time'
          }
        }
        return getRolePage(Object.assign(parameter, this.queryParam))
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      menus: [],
      clientIds: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true
    }
  },
  filters: {
    statusFilter (type) {
      if (BaseTool.String.isBlank(type)) {
        type = 1
      }
      return Constant.RoleStatus[type].text
    },
    statusTypeFilter (type) {
      if (BaseTool.String.isBlank(type)) {
        type = 1
      }
      return Constant.RoleStatus[type].status
    }
  },
  created () {
    // 查询客户端
    this.getClientIds()
    this.tableOption()
    this.getMenus()
  },
  methods: {
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: false, // Column configuration not to be checked
                name: record.userId
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    getClientIds () {
      queryClientDetail().then(res => {
        this.clientIds = res.data
      })
    },
    getMenus () {
      getMenuTree({ clientId: this.queryParam.clientId, visible: true }).then(res => {
        this.menus = res.data
      })
    },
    handleEdit (record) {
      fetchRole({ roleId: record.roleId }).then(res => {
        this.$refs.baseModal.base(res.data)
      })
    },
    handleChangeRoleStatus (roleId, status) {
      let roleIds = []
      if (this.BaseTool.String.isBlank(roleId)) {
        const length = this.selectedRows.length
        if (length === 0) {
          this.$message.info(`请选择要操作的记录`)
          return
        }
        roleIds = this.selectedRows.map(item => item.id)
      } else {
        roleIds = [roleId]
      }
      updateStatus({
        roleIds: roleIds,
        status: status
      }).then(res => {
        this.$message.info(res.message)
        this.handleOk()
      }).catch(res => {})
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    clientIdChange (val) {
      this.getMenus()
      this.$refs.table.refresh(true)
    },
    resetSearchForm () {
      this.queryParam = {
        clientId: 'end'
      }
      this.getMenus()
      this.$refs.table.refresh(true)
    }
  }
}
</script>
