<template>
  <div>
    <!-- 头部搜索 -->
    <el-form
      v-show="isSearchVisible"
      ref="formData"
      :inline="true"
      :model="formData"
      label-width="180px"
      class="formData">
      <div class="top-select-container">

        <!-- 权限分组名称 -->
        <el-form-item label="权限分组名称：" prop="phone">
          <el-input v-model="formData.roleName" placeholder="请输入权限分组名称"></el-input>
        </el-form-item>

        <!-- 最后更新时间 -->
        <el-form-item label="时间：" prop="time">
<!--          <el-date-picker-->
<!--            v-model="formData.time"-->
<!--            type="daterange"-->
<!--            align="right"-->
<!--            unlink-panels-->
<!--            range-separator="至"-->
<!--            start-placeholder="开始日期"-->
<!--            end-placeholder="结束日期"-->
<!--            :picker-options="pickerOptions">-->
<!--          </el-date-picker>-->
          <CustomChoiceDatePicker @handelChange="handelTimeChange"></CustomChoiceDatePicker>
        </el-form-item>

        <!-- 提交，重置按钮 -->
        <div>
          <el-button type="primary" @click="submitForm"
          >提交</el-button>
          <el-button
            type="info"
            size="mini"
            plain
            @click="resetForm('formData')"
          >重置</el-button
          >
        </div>
      </div>
    </el-form>

    <!-- 操作按钮 -->
    <div class="top-action-button-container">
      <!-- 左边 -->
      <div class="top-action-button-left">
        <el-button
          type="primary"
          icon="el-icon-refresh-right"
          size="mini"
          @click="refreshData"
        ></el-button>
        <el-button
          type="success"
          icon="el-icon-plus"
          size="mini"
          @click="openEditorDialog(null, false)"
        >添加权限分组</el-button
        >
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="openDeleteDialog(null)"
        >删除</el-button
        >
      </div>

      <!-- 右边 -->
      <div class="top-action-button-right">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="isSearchVisible = !isSearchVisible"
        ></el-button>
      </div>
    </div>

    <!-- 数据 -->
    <el-table ref="dataList"
              :data="dataList"
              border
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="152">
      </el-table-column>
      <el-table-column label="权限分组名称" prop="roleName" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="人数" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="span-text-blue" @click="openUseDialog(scope.row)">{{ scope.row.useStr }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="memo" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="最后更新时间" prop="updateAt" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <div class="flex-box">
            <CustomButton tip-text="权限管理" icon="el-icon-edit-outline" @onClick="openEditorDialog(scope.row, false)"></CustomButton>
            <CustomButton tip-text="权限管理" icon="permission" is-svg @onClick="openManageDialog(scope.row)"></CustomButton>
            <CustomButton tip-text="管理员管理" icon="admin" is-svg @onClick="openUseDialog(scope.row)"></CustomButton>
            <CustomButton tip-text="复制" icon="el-icon-copy-document" @onClick="openEditorDialog(scope.row, true)"></CustomButton>
            <CustomButton tip-text="删除" type="danger" is-svg icon="delete" @onClick="openDeleteDialog(scope.row)" />
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="foot-container">
      <el-pagination
        :total="totalCount"
        :current-page="currentPage"
        :page-size="limit"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentPageChange">
      </el-pagination>
    </div>

    <!--  dialog相关  -->
    <EditorDialog
      :show-dialog-visible="isEditorDialogVisible"
      :dialog-title="editorDialogTitle"
      :dialog-style="editorDialogStyle"
      :is-copy="editorDialogCopy"
      :select-item="selectItem"
      @closeDialog="isEditorDialogVisible = false"
    ></EditorDialog>

    <UseStateDialog
      :show-dialog="isUseStateDialogVisible"
      :dialog-style="useDialogStyle"
      :user-list="useUserList"
      @closeDialog="isUseStateDialogVisible = false"
    >
    </UseStateDialog>

    <PermissionManageDialog
      :show-dialog="isPermissionManageDialogVisible"
      :dialog-style="permissionMangeDialogStyle"
      :select-item="selectItem"
      @closeDialog="isPermissionManageDialogVisible = false"
      @successCallBack="refreshDataEvent"
    >
    </PermissionManageDialog>

    <!--  校验dialog  -->
    <VerifySmsDialog
    :get-sms-url="safeGetSmsUrl"
    :dialog-show="isSafeDialogVisible"
    @closeDialog="isSafeDialogVisible = false"
    @smsCodeCallBack="smsCodeCallBack"
    >
    </VerifySmsDialog>

  </div>
</template>

<script>
import { fetchRoleList, delRole } from '@/api/system-manage/permission-manage/permission-setting'
import EditorDialog from './components/permission-editor-dialog'
import UseStateDialog from './components/permission-use-state-dialog'
import PermissionManageDialog from './components/permission-manage-dialog'
import VerifySmsDialog from '@/components/VerifySmsDialog/index'
import CustomButton from '@/components/CustomButton'
import CustomChoiceDatePicker from '@/components/CustomChoiceDatePicker'

/**
 * 权限设置
 *
 */
export default {
  components: {
    EditorDialog,
    UseStateDialog,
    PermissionManageDialog,
    VerifySmsDialog,
    CustomButton,
    CustomChoiceDatePicker
  },
  props: {},
  data() {
    return {
      // UI控制参数
      isSearchVisible: false,
      // 编辑dialog
      isEditorDialogVisible: false,
      editorDialogTitle: '',
      editorDialogStyle: {
        '--dialog-width': '620px',
        '--dialog-height': '350px',
        '--title-height': '55px'
      },
      editorDialogCopy: false,
      // 删除dialog
      isDeleteDialogVisible: false,
      deleteMultiple: false,
      // 使用人数的dialog
      isUseStateDialogVisible: false,
      useDialogStyle: {
        '--dialog-width': '620px',
        '--dialog-height': '255px',
        '--title-height': '55px'
      },
      useUserList: [],
      // 权限管理的Dialog
      isPermissionManageDialogVisible: false,
      permissionMangeDialogStyle: {
        '--dialog-width': '1000px',
        '--dialog-height': '7000px',
        '--title-height': '55px'
      },
      // 短信校验dialog
      isSafeDialogVisible: false,
      safeGetSmsUrl: '/admin/Role/sendSms',
      // 请求表单
      formData: {
        roleName: '',
        time: ''
      },
      // 页数
      totalCount: 0,
      currentPage: 1,
      limit: 20,
      // 返回数据
      dataList: [],
      // 当前选中的数据
      multipleSelection: [],
      selectItem: { type: Object, default: () => {} }
    }
  },
  mounted() {
    this._baseRequest()
  },
  methods: {
    // 短信验证码回调
    smsCodeCallBack(smsCode) {
      this.confirmDelData(smsCode)
    },
    // 选择时间回调
    handelTimeChange(val) {
      this.formData.time = val
    },
    // 打开使用状态Dialog
    openUseDialog(row) {
      this.useUserList = row.userList
      this.isUseStateDialogVisible = true
    },
    // 打开权限管理Dialog
    openManageDialog(row) {
      this.selectItem = row
      this.isPermissionManageDialogVisible = true
    },
    // 打开删除Dialog
    openDeleteDialog(row) {
      if (row === null && this.multipleSelection.length === 0) {
        this.$message.warning('请选择需要删除的数据~')
        return
      }
      const deleteTitle = row !== null ? `是否删除该权限分组，删除后不可恢复` : `是否删除选中的${this.multipleSelection.length}个权限分组，删除后不可恢复`
      this.$confirm(deleteTitle, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认删除
        this.deleteMultiple = row === null
        this.selectItem = row
        this.confirmDelData(null)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 打开编辑Dialog
    openEditorDialog(row, isCopy) {
      this.editorDialogStyle = {
        '--dialog-width': '620px',
        '--dialog-height': '314px',
        '--title-height': '55px'
      }
      if (row === null) {
        this.selectItem = {
          id: '',
          roleName: '',
          memo: ''
        }
        this.editorDialogCopy = false
      } else {
        this.selectItem = row
        this.editorDialogCopy = isCopy
      }
      if (this.editorDialogCopy) {
        this.selectItem.copyRoleName = this.selectItem.roleName
        this.editorDialogStyle = {
          '--dialog-width': '620px',
          '--dialog-height': '378px',
          '--title-height': '55px'
        }
      }
      this.isEditorDialogVisible = true
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 提交表单
    submitForm() {
      this.refreshDataEvent()
    },
    // 选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.limit = val
      this.refreshDataEvent()
    },
    // 当前页数改变
    handleCurrentPageChange(val) {
      this.currentPage = val
      this.refreshDataEvent()
    },
    refreshData() {
      this.isEditorDialogVisible = false
      this.isDeleteDialogVisible = false
      this.isSafeDialogVisible = false
      this.isPermissionManageDialogVisible = false
      this._baseRequest(true)
    },
    // 刷新数据
    refreshDataEvent() {
      this.isEditorDialogVisible = false
      this.isDeleteDialogVisible = false
      this.isSafeDialogVisible = false
      this.isPermissionManageDialogVisible = false
      this._baseRequest()
    },
    // 确认删除
    confirmDelData(smsCode) {
      const array = []
      if (this.deleteMultiple) {
        this.multipleSelection.forEach((item) => array.push(item.id))
      } else {
        array.push(this.selectItem.id)
      }
      const request = {}
      request.ids = array
      if (smsCode !== null) {
        request.code = smsCode
      }
      delRole(request).then(res => {
        if (parseInt(res.code) === 0) {
          this.$message.success('操作成功')
          this.refreshDataEvent()
        } else if (parseInt(res.code) === 401) {
          this.$message.error(res.msg)
          this.isSafeDialogVisible = true
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 基础请求
    async _baseRequest(needToast) {
      console.log('基础请求')
      let res = {}
      const params = {
        roleName: this.formData.roleName
      }
      if (this.formData.time.length === 2) {
        params.time = (this.formData.time[0] + ' - ' + this.formData.time[1])
      }
      res = await fetchRoleList(params)
      if (parseInt(res.code) === 0 && needToast) this.$message.success('刷新成功～')
      this.dataList = res.data.roleList
      this.totalCount = res.data.total
    }
  }
}
</script>

<style lang="scss" scoped>
  // 头部表单提交
  .top-select-container {
    display: flex;
    justify-content: space-between;
  }

  // 头部操作按钮样式
  .top-action-button-container {
    display: flex;
    justify-content: space-between;
  }

  // 数据样式
  .el-table {
    margin-top: 16px;
    .margin-right-width {
      margin-right: 13px;
    }
    .span-text-blue {
      color: #3799FF;
    }
    .span-text-blue:hover{
      cursor: pointer;
    }
    .color-red {
      color: red;
    }
    .color-blue {
      color: #1890FF;
    }
  }

  // 分页样式
  .foot-container {
    width: 100%;
    height: 100%;
    margin-top: 40px;
    align-items: center;
    display: flex;
    justify-content: center;
    align-items: flex-end;
  }
</style>
