<template>
  <div class="role-manage">
    <ht-table
      @load="loadData"
      :data="data"
      :pageResult="pageResult"
      :selection="true"
      quick-search-props="name,code"
      ref="roleTable"
      :show-custom-column="false"
      :show-export="false"
      :header-cell-class-name="headerCellClassName"
      @row-click="rowClick"
      @selection-change="handleSelectionChange"
    >
      <template v-slot:toolbar>
        <el-button
          size="small"
          type="primary"
          @click="showDialog()"
          icon="el-icon-plus"
          >添加</el-button
        >
        <el-button icon="el-icon-download" @click="dialogImportVisible = true"
          >导入</el-button
        >
        <el-button
          icon="el-icon-upload2"
          @click="exportExcel"
          :disabled="isDisabled"
          >导出</el-button
        >
        <ht-delete-button
          :url="roleDeleteUrl"
          :htTable="$refs.roleTable"
          :disabled="isDisabled"
          >删除</ht-delete-button
        >
      </template>
      <template>
        <ht-table-column type="index" width="50" align="center" label="序号" />
        <ht-table-column prop="id" label="主键" :sortable="true" hidden />
        <ht-table-column
          prop="name"
          label="名称"
          :sortable="true"
          :show-overflow-tooltip="true"
        >
          <template v-slot="{row, column, $index}">
            <el-link
              type="primary"
              @click="handleCommand({row: row, command: 'assignMenu'})"
              title="点击菜单授权"
              >{{ row.name }}</el-link
            >
          </template>
        </ht-table-column>
        <ht-table-column prop="code" label="编码" :sortable="true" />
        <ht-table-column
          prop="enabled"
          label="状态"
          :render-header="renderHeaderMethod"
          :filters="[
            {text: '启用', value: 1},
            {text: '禁用', value: 0}
          ]"
        >
          <template v-slot="{row}">
            <el-switch
              @click.native="handleEnabled(row)"
              slot="reference"
              :value="row.enabled"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
            <span
              class="status_text"
              :class="{'theme-color': row.enabled === 1}"
              >{{ row.enabled === 1 ? '启用' : '禁用' }}
            </span>
          </template>
        </ht-table-column>
        <ht-table-column width="260" label="操作" align="left">
          <template v-slot="{row}">
            <el-button
              type="text"
              @click="handleCommand({row: row, command: 'assignUser'})"
              >分配用户</el-button
            >
            <el-button
              type="text"
              @click="handleCommand({row: row, command: 'copyRoleMenuPerm'})"
              >权限复制</el-button
            >
            <el-dropdown
              size="mini"
              @command="handleCommand"
              class="more-operate-btn__dropdown"
              trigger="click"
            >
              <span class="more-operate-btn"
                >更多操作<i class="el-icon-caret-bottom"></i>
              </span>
              <el-dropdown-menu
                slot="dropdown"
                class="operate-dropdown__button"
              >
                <el-dropdown-item :command="{row: row, command: 'methodAuth'}"
                  >接口授权</el-dropdown-item
                >
                <el-dropdown-item :command="{row: row, command: 'orgAuth'}"
                  >组织授权</el-dropdown-item
                >
                <el-dropdown-item :command="{row: row, command: 'edit'}"
                  >编辑</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </ht-table-column>
      </template>
    </ht-table>

    <ht-sidebar-dialog
      width="28%"
      title="添加角色"
      :visible="dialogVisible"
      :before-close="handleClose"
      append-to-body
    >
      <el-form v-model="role" data-vv-scope="editRoleForm">
        <ht-form-item label="角色名称" prop="name" label-width="100px">
          <ht-input
            v-model="role.name"
            autocomplete="off"
            :validate="{
              required: true,
              regex: {
                exp: '^[\\s\\S]{1,30}$',
                message: '内容超出输入限制'
              }
            }"
            placeholder="请输入名称"
          ></ht-input>
        </ht-form-item>
        <ht-form-item label="角色别名" prop="code" label-width="100px">
          <ht-input
            v-model="role.code"
            v-pinyin="role.name"
            autocomplete="off"
            :validate="{
              required: true,
              alpha_dash: true,
              regex: {
                exp: '^[\\s\\S]{1,30}$',
                message: '内容超出输入限制'
              }
            }"
            placeholder="请输入别名"
            :disabled="role.id ? true : false"
          ></ht-input>
        </ht-form-item>
        <ht-form-item label="状态" label-width="100px">
          <ht-switch
            v-model="role.enabled"
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
            permission="b"
          >
          </ht-switch>
        </ht-form-item>
        <ht-form-item label="描述" label-width="100px">
          <ht-input
            type="textarea"
            v-model="role.description"
            placeholder="请输入描述"
            :maxlength="50"
            show-word-limit
            :autosize="{minRows: 3, maxRows: 5}"
          />
        </ht-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCancle('dialogVisible')">{{
          $t('eip.common.cancel')
        }}</el-button>
        <ht-submit-button
          :url="saveRoleUrl"
          :model="savaRoleData"
          :is-submit="isSubmit"
          :request-method="requestMethod"
          scope-name="editRoleForm"
          :restoreUrl="restoreUrl"
          aliasProp="code"
          @before-save-data="beforeSaveData"
          @after-save-data="afterSaveData"
          >{{ $t('eip.common.save') }}</ht-submit-button
        >
      </div>
    </ht-sidebar-dialog>

    <ht-sidebar-dialog
      width="1040px"
      title="菜单权限复制"
      :visible="dialogVisibleMenuPerm"
      :before-close="handleCloseMenuPerm"
      ref="menuPermSidebardialog"
      append-to-body
    >
      <el-form :model="menuPerm" data-vv-scope="RoleMenuPermForm">
        <ht-form-item label="原角色名称" prop="name" label-width="120px">
          <ht-input v-model="menuPerm.name" permission="r"></ht-input>
        </ht-form-item>
        <ht-form-item label="原角色别名" prop="code" label-width="120px">
          <ht-input v-model="menuPerm.code" permission="r"></ht-input>
        </ht-form-item>
        <ht-form-item label="权限复制角色" label-width="120px">
          <ht-select
            v-model="menuPerm.newCodes"
            :options="roleCodesOptions"
            multiple
            :validate="{required: true}"
          />
        </ht-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCancle('dialogVisibleMenuPerm')">{{
          $t('eip.common.cancel')
        }}</el-button>
        <ht-submit-button
          :url="saveRoleCopy"
          :isSubmit="true"
          scopeName="RoleMenuPermForm"
          @after-save-data="dialogVisibleMenuPerm = false"
          >{{ $t('eip.common.save') }}</ht-submit-button
        >
      </div>
    </ht-sidebar-dialog>

    <ht-load-data
      ref="htLoadData"
      :url.sync="loadDataUrl"
      context="uc"
      @after-load-data="afterLoadData"
    ></ht-load-data>
    <!-- 角色用户管理 -->
    <user-role-manager append-to-body ref="userRoleManager"></user-role-manager>
    <!-- 菜单授权 -->
    <role-menu-auth append-to-body ref="roleMenuAuth"></role-menu-auth>
    <!-- 接口授权 -->
    <role-method-auth append-to-body ref="roleMethodAuth"></role-method-auth>
    <!-- 组织授权 -->
    <role-org-auth ref="roleOrgAuth"></role-org-auth>
    <!-- 导入 -->
    <el-dialog
      :visible.sync="dialogImportVisible"
      append-to-body
      title="角色导入"
      width="50%"
    >
      <el-form ref="form" label-width="150px">
        <ht-form-item label="默认模板">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-download"
            @click="downloadTemplate()"
            >模板下载</el-button
          >
        </ht-form-item>
        <ht-form-item label="文件">
          <el-upload
            style="display: inline-block"
            :action="importUrl"
            :http-request="handleImport"
            :on-success="hadleUploadResult"
            :on-error="hadleUploadResult"
            :headers="uploadHeaders"
            :on-exceed="onExceed"
            accept=".xlsx,.xls"
            :before-upload="beforeUpload"
            :limit="1"
            :data="{isCheck: true}"
            :auto-upload="false"
            ref="upload"
          >
            <el-button size="small" icon="el-icon-upload"
              >选择Excel文件</el-button
            >
          </el-upload>
        </ht-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelConfirm()">取 消</el-button>
        <el-button
          type="primary"
          @click="submitImport"
          element-loading-text="拼命导入中"
          v-loading.fullscreen.lock="fullscreenLoading"
          >确 定</el-button
        >    
      </div>
    </el-dialog>

    <el-dialog
      title="温馨提示"
      :visible="myDialogVisible"
      :before-close="beforeClose2"
      name="myDialogVisible"
      width="30%"
      custom-class="upload-dialog"
      top="30vh"
      append-to-body
    >
      <span>部分角色编码已存在/已被删除，请确认重复项的导入操作！</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="default" @click="beforeClose2">取消</el-button>
        <el-button type="primary" @click="confirmSubmit('update')"
          >覆盖更新</el-button
        >
        <el-button type="primary" @click="confirmSubmit('recover')"
          >直接恢复</el-button
        >
        <el-button type="primary" @click="confirmSubmit('jump')"
          >跳过重复项</el-button
        >  
      </span>
    </el-dialog>
  </div>
</template>
<script>
import uc from '@/api/uc.js'
import utils from '@/hotent-ui-util.js'
import req from '@/request.js'

import tableHeaderFilter from '@/mixins/tableHeaderFilter.js'

import eipUserDialog from '@/components/dialog/EipUserDialog.vue'
const userRoleManager = () => import('@/views/uc/UserRoleManager.vue')
const roleMenuAuth = () => import('@/views/uc/RoleMenuAuth.vue')
const roleMethodAuth = () => import('@/views/uc/RoleMethodAuth.vue')
const RoleOrgAuth = () => import('@/views/uc/RoleOrgAuth.vue')
export default {
  components: {
    eipUserDialog,
    userRoleManager,
    roleMenuAuth,
    roleMethodAuth,
    RoleOrgAuth
  },
  mixins: [tableHeaderFilter],
  computed: {
    roleDeleteUrl: function() {
      return window.context.uc + '/api/role/v1/role/deleteRoleByIds'
    },
    saveRoleUrl: function() {
      let preUrl = window.context.uc + '/api/role/v1/role'
      if (this.role.id) {
        preUrl += '/updateRole'
      } else {
        preUrl += '/addRole'
      }
      return preUrl
    },
    restoreUrl: function () {
      return window.context.uc + '/api/role/v1/role/restoreRoleByAlias/'
    },
    requestMethod: function() {
      return this.role.id ? 'PUT' : 'POST'
    },
    roleCodesOptions: function() {
      let result = []
      for (let role of this.allowRoles) {
        let obj = {}
        obj.key = role.code
        obj.value = role.name
        result.push(obj)
      }
      return result
    },
    saveRoleCopy: function() {
      return `${window.context.portal}/sys/sysRoleAuth/v1/saveCopy?oldCode=${this.menuPerm.code}&newCodes=${this.menuPerm.newCodes}`
    },
    // importUrl: function() {
    //   return window.context.uc + "/api/role/v1/roles/import";
    // },
    uploadHeaders: function(mapState) {
      return {
        Authorization: 'Bearer ' + this.$store.state.login.currentUser.token
      }
    },
    savaRoleData(){
      const {code, name, enabled, description} = this.role || {}
      return {
        code,
          name,
          enabled,
          description:description || '',
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogVisibleMenuPerm: false,
      dialogImportVisible: false,
      role: {
        name: '',
        code: '',
        enabled: 1
      },
      isSubmit: false,
      data: [],
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0
      },
      loadDataUrl: '',
      menuPerm: {},
      allowRoles: [],
      fullscreenLoading: false,
      myDialogVisible: false,
      importUrl: '',
      uploadFile: null,
      selectedList: [],
      isDisabled: true
    }
  },
  watch: {
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectedList = selection
    },
    switchClick() {},
    handleEnabled(row) {
      this.$confirm(
        `是否要${row.enabled === 1 ? '禁用' : '启用'}此角色?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        let {name,code,description} = row //解构需要的入参参数
        uc.updateRoleData({name,code,description, enabled: row.enabled === 1 ? 0 : 1}).then(
          ({data}) => {
            if (data.state) {
              this.$message.success(row.enabled === 1 ? '禁用成功' : '启用成功')
              this.$refs.roleTable.load()
            } else {
              this.$message.warning(data.message)
            }
          }
        )
      })
    },
    handleImport(param) {
      this.uploadFile = param.file
      let formData = new FormData()
      formData.append('file', param.file)
      uc.importRole(formData).then(resp => {
        if (resp.state) {
          if (resp.message && resp.message == 'confirmUpload') {
            this.myDialogVisible = true
          } else {
            this.$message({type: 'success', message: resp.message})
            this.handleClose()
            this.loadData() //重新加载列表数据
          }
        } else {
          this.handleClose()
        }
      }).finally(() => {
        this.fullscreenLoading = false
      })
    },
    confirmSubmit(arg) {
      let formData = new FormData()
      formData.append('file', this.uploadFile)
      req
        .post(
          `${window.context.uc}/api/role/v1/roles/importRoleData?status=${arg}`,
          formData
        )
        .then(rep => {
          this.hadleUploadResult(rep.data)
        })
    },
    beforeClose2() {
      this.myDialogVisible = false
      this.fullscreenLoading = false
    },
    rowClick(row, column, event) {
      this.$refs.roleTable.$refs.htTable.toggleRowSelection(row)
    },
    handleClose() {
      this.dialogVisible = false
      this.fullscreenLoading = false
      this.dialogImportVisible = false
    },
    handleCloseMenuPerm() {
      this.dialogVisibleMenuPerm = false
    },
    showDialog(row) {
      this.dialogVisible = true
      if (row) {
        // this.role = row;
        //setTimeout(() => this.$validator.validateAll());
        this.loadDataUrl = `/api/role/v1/role/getRole?code=${row.code}`
      } else {
        this.role = {name: '', code: '', enabled: 1}
      }
    },
    dialogCancle(dialogVisible) {
      this[dialogVisible] = false
    },
    loadData(param, cb) {
      uc.getRolePage(param)
        .then(response => {
          this.data = response.rows
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
        })
        .finally(() => cb())
    },
    handleCommand(params) {
      switch (params.command) {
        case 'edit':
          this.showDialog(params.row)
          break
        case 'delete':
          break
        case 'assignUser':
          this.$refs.userRoleManager.showDialog(params.row.code)
          break
        case 'assignMenu':
          this.$refs.roleMenuAuth.showDialog(params.row.code)
          break
        case 'methodAuth':
          this.$refs.roleMethodAuth.showDialog(params.row.code)
          break
        case 'copyRoleMenuPerm':
          this.menuPerm = params.row
          this.dialogVisibleMenuPerm = true
          this.loadDataUrl = `/api/role/v1/roles/getNotCodeAll?code=${params.row.code}`
          break
        case 'orgAuth':
          this.$refs.roleOrgAuth.showDialog(params.row)
        default:
          break
      }
    },
    async beforeSaveData() {
      this.isSubmit = true
    },
    afterSaveData() {
      this.dialogVisible = false
      this.$refs.roleTable.load()
    },
    afterLoadData(data) {
      // 菜单权限复制
      if (this.dialogVisibleMenuPerm) {
        this.allowRoles = data
      }
      // 编辑角色
      if (this.dialogVisible) {
        this.role = data.value
        setTimeout(() => this.$validator.validateAll('editRoleForm'))
      }
    },
    //导入
    onExceed(file) {
      this.$message.warning('只能选择一个Excel文件!')
    },
    beforeUpload(file) {
      if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
        this.$message.warning('只能导入Excel文件!')
        return false
      }
      this.fullscreenLoading = true
    },
    hadleUploadResult(response, file, fileList) {
      this.fullscreenLoading = false
      this.myDialogVisible = false
      if (response.state) {
        this.$message.success(response.message)
        this.dialogImportVisible = false
        this.$refs.upload.clearFiles()
        this.$refs.roleTable.load()
      } else {
        this.$message.error(response.message + '：' + response.value)
      }
    },
    cancelConfirm() {
      this.$refs.upload.clearFiles()
      this.dialogImportVisible = false
    },
    //下载模板
    downloadTemplate() {
      window.location.href =
        window.context.manage + '/static/excel/exportRole.xls'
    },
    exportExcel(data) {
      let selection = this.$refs.roleTable.$refs.htTable.selection
      if (!selection || selection.length == 0) {
        this.$message({type: 'warning', message: '请至少选择一条记录'})
        return
      }
      let ids = []
      for (let i = 0; i < selection.length; i++) {
        ids.push(selection[i].id)
      }
      let url =
        window.context.uc + '/api/role/v1/roles/export?ids=' + ids.join(',')
      req.download(url)
    },
    submitImport() {
      if (
        !this.$refs.upload.uploadFiles ||
        this.$refs.upload.uploadFiles.length == 0
      ) {
        this.$message.warning('请选择要导入的数据文件!')
        return false
      }
      this.$refs.upload.submit()
    }
  }
}
</script>
<style lang="scss" scoped>
div[aria-invalid='true'] >>> .el-input__inner,
div[aria-invalid='true'] >>> .el-input__inner:focus {
  border-color: #f56c6c;
}
.role-manage {
  padding: 24px;
  height: calc(100% - 48px);
}
</style>
