<template>
  <div>
    <a-card size="small" :bordered="false" class="roleList-wrap searchBoxNormal">
      <div ref="tableSearch" class="table-page-search-wrapper">
        <!-- 搜索条件 -->
        <a-form layout="inline" id="roleList-form" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="角色名称">
                <a-input
                  allowClear
                  v-model.trim="queryParam.name"
                  placeholder="请输入角色名称"
                  :maxLength="30"
                  id="roleList-name"
                  @pressEnter="$refs.table.refresh(true)" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="状态">
                <v-select code="ENABLE_FLAG" v-model="queryParam.isEnable" allowClear placeholder="请选择状态" id="roleList-isEnable"></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="$refs.table.refresh(true)" id="roleList-handSubmit" style="margin-right: 10px;">查询</a-button>
              <a-button type="" @click="reset" id="roleList-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <!-- 操作按钮 -->
      <a-spin :spinning="spinning" tip="Loading...">
        <div class="table-operator">
          <a-button type="primary" v-if="$hasPermissions('B_power_role_add')" @click="openModal" id="roleList-openModal">新增</a-button>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+70+'px' }"
          size="small"
          rowKey="id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          style="word-break: break-all;"
          :defaultLoadData="false"
          bordered>
          <!-- 启用禁用 -->
          <span slot="status" slot-scope="text, record">
            <a-switch
              v-if="$hasPermissions('B_power_role_enable')"
              checkedChildren="启用"
              unCheckedChildren="禁用"
              :id="'roleList-isEnable-btn'+record.id"
              v-model="record.isEnable"
              @change="changeFlagHandle(text, record)" />
            <span v-else>{{ record.isEnable==1?'已启用':'已禁用' }}</span>
          </span>
          <!-- 角色描述 -->
          <template slot="remarks" slot-scope="text, record">
            <span class="text-overflows" :title="record.remarks">{{ record.remarks ?record.remarks : '--' }}</span>
          </template>
          <!-- 操作 -->
          <span slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              class="button-info"
              :id="'roleList-usePower-btn'+record.id"
              v-if="$hasPermissions('M_power_role_menu')"
              @click="openMenuModal(record,1)"
            >
              功能权限
            </a-button>
            <a-button
              size="small"
              type="link"
              class="button-info"
              :id="'roleList-pricePower-btn'+record.id"
              v-if="$hasPermissions('M_power_role_menu')"
              @click="openMenuModal(record,0)"
            >
              价格权限
            </a-button>
            <a-button
              size="small"
              type="link"
              class="button-info"
              :id="'roleList-edit-btn'+record.id"
              v-if="$hasPermissions('B_power_role_edit')"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              :id="'roleList-del-btn'+record.id"
              v-if="!record.isEnable && $hasPermissions('B_power_role_del')"
              @click="delect(record)"
            >
              删除
            </a-button>
            <span v-if="!$hasPermissions('M_power_role_menu') && !$hasPermissions('B_power_role_edit') && (record.isEnable && !$hasPermissions('B_power_role_del'))">--</span>
          </span>
        </s-table>
      </a-spin>
      <!-- 添加角色弹窗 -->
      <roleModal :visible="showModal" @refresh="$refs.table.refresh()" :nowData="itemData" @close="closeRole"></roleModal>
      <!-- 价格权限、功能权限弹窗 -->
      <menuModal :visible="showMenuModal" @refresh="$refs.table.refresh()" :nowData="menuData" @close="showMenuModal = false"></menuModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import roleModal from './roleModal.vue'
import menuModal from './menuModal.vue'
// 接口
import { getPowerRoleList, updateEnableStatus, delectRolePower, getMenuList } from '@/api/power-role.js'
export default {
  name: 'PowerRoleList',
  mixins: [commonMixin],
  components: { STable, VSelect, roleModal, menuModal },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      // 查询参数
      queryParam: {
        name: '', // 角色名称
        isEnable: ''// 状态
      },
      showModal: false, // 角色弹窗
      showMenuModal: false, // 权限弹窗
      itemData: {}, // 编辑行数据
      menuData: {}, // 角色列表
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '15%', align: 'center' },
        { title: '角色名称', dataIndex: 'name', width: '25%', align: 'center' },
        { title: '角色描述', dataIndex: 'remarks', width: '25%', align: 'center', scopedSlots: { customRender: 'remarks' } },
        { title: '状态', width: '15%', align: 'center', scopedSlots: { customRender: 'status' } },
        { title: '操作', width: '15%', align: 'center', scopedSlots: { customRender: 'action' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        // 获取列表数据 有分页
        return getPowerRoleList(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 计算表格序号
            const no = (data.pageNo - 1) * data.pageSize
            for (let i = 0; i < data.list.length; i++) {
              const _item = data.list[i]
              _item.no = no + i + 1
              _item.isEnable = _item.isEnable + '' === '1'
            }
          }
          this.spinning = false
          return data
        })
      },
      optionAlertShow: false
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      // vm.$refs.table.refresh()
    })
  },
  methods: {
    // 关闭角色弹窗
    closeRole () {
      this.showModal = false
      this.itemData = {}
    },
    // 刷新列表
    refreshTable () {
      this.$refs.table.refresh(true)
    },
    // 重置
    reset () {
      this.queryParam.name = ''
      this.queryParam.isEnable = ''
      this.refreshTable()
    },
    // 新增
    openModal () {
      this.showModal = true
      this.itemData = {}
    },
    // 打开分配权限弹窗
    openMenuModal (row, type) {
      this.getMenuList(row.id, type)
    },
    // 获取菜单树列表
    getMenuList (id, type) {
      const _this = this
      getMenuList({
        id: id
      }).then(res => {
        if (res.status == 200) {
          _this.menuData = res.data
          _this.menuData.type = type
          this.showMenuModal = true
        }
      })
    },
    // 删除
    delect (row) {
      const _this = this
      this.$confirm({
        title: '警告',
        content: '删除后无法恢复，确认删除?',
        centered: true,
        onOk () {
          _this.spinning = true
          delectRolePower({
            id: row.id
          }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 编辑
    handleEdit (row) {
      this.showModal = true
      this.itemData = row
    },
    // 修改状态
    changeFlagHandle (text, record) {
      const _data = {
        id: record.id,
        flag: record.isEnable ? '1' : '0'
      }
      this.spinning = true
      updateEnableStatus(_data).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinning = false
        } else {
          this.$refs.table.refresh()
          this.spinning = false
        }
      })
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 236
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.reset()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.reset()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  }
}
</script>
<style scoped>
	.action-button {
		line-height: 40px;
		white-space: nowrap;
		padding: 5px 10px;
		background-color: #1890ff;
		border-radius: 4px;
		color: #fff;
		margin-right: 5px;
	}
	.red-text {
		background-color: red;
	}
	.menu-text {
		background-color: #f90;
	}
</style>
