
<template>
  <div>
    <!-- 头部搜索 -->
    <el-form
      v-show="isSearchVisible"
      ref="formData"
      :inline="true"
      :model="formData"
      label-width="110px"
      class="formData">
      <div class="top-select-container">
        <!-- 手机号 -->
        <el-form-item label="手机号：" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <!-- 时间 -->
        <el-form-item label="时间：" prop="time">
          <ChoiceDatePicker @handelChange="handelTimeChange"></ChoiceDatePicker>
        </el-form-item>

        <!-- 权限分组： -->
        <el-form-item label="权限分组：" prop="roleId">
          <el-select v-model="formData.roleId" placeholder="请选择分组">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </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)"
          >添加管理员</el-button
        >
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="deleteAdmin(null)"
          >删除</el-button
        >
      </div>

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

    <!-- 数据 -->
    <el-table ref="userList"
        :data="userList"
        border
        @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="152">
      </el-table-column>
      <el-table-column label="手机号" prop="phone" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="权限分组" prop="roleName" align="center" show-overflow-tooltip>
<!--        <template slot-scope="scope">-->
<!--            {{ getRoleName(scope.row.roleId) }}-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="备注" prop="memo" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="最近登录时间" prop="loginTime" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <div class="flex-box operate-table-box">
            <CustomDelButton icon="el-icon-edit-outline" class="margin-right-width" tip-text="编辑" @onClick="openEditorDialog(scope.row)"></CustomDelButton>
            <CustomButton tip-text="删除" type="danger" is-svg icon="delete" @onClick="deleteAdmin(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 -->
    <!--  编辑的弹窗  -->
    <EditorAdminDialog
      :editor-exist="editorDialogVisible"
      :edit-title="editorDialogTitle"
      :role-list="roleList"
      :select-item="selectItem"
      @closeDialog="editorDialogVisible = false"
      @success="refreshDataEvent"
    ></EditorAdminDialog>

    <!-- 短信校验 -->
    <VerifySmsDialog
      :dialog-show="safeDialogVisible"
      get-sms-url="/admin/User/sendSms"
      @closeDialog="safeDialogVisible = false"
      @smsCodeCallBack="smsCodeCallBack"
    ></VerifySmsDialog>

  </div>

</template>

<script>
import { fetchAdminList, delAdmin } from '@/api/system-manage/permission-manage/admin-list'
import ChoiceDatePicker from '@/components/CustomChoiceDatePicker'
import EditorAdminDialog from './components/admin-editor-dialog'
import VerifySmsDialog from '@/components/VerifySmsDialog/index'
import CustomDelButton from '@/components/CustomButton'

/**
 * 管理员列表
 */
export default {
  components: {
    EditorAdminDialog,
    VerifySmsDialog,
    CustomDelButton,
    ChoiceDatePicker
  },
  data() {
    return {
      deleteMultiple: false,
      isSearchVisible: false,
      // 是否处于安全🔐下
      safe: false,
      // Dialog控制参数
      editorDialogVisible: false,
      editorDialogStyle: {
        '--dialog-width': '620px',
        '--dialog-height': '400px',
        '--title-height': '55px'
      },
      editorDialogTitle: '编辑',
      safeDialogVisible: false,
      safeDialogStyle: {},
      // 筛选条件
      formData: {
        phone: '',
        roleId: '',
        time: ''
      },
      // 分页参数
      totalCount: 0,
      currentPage: 1,
      limit: 20,
      // 权限分组数据
      roleList: [],
      // 管理员数据
      userList: [],
      // 当前选中的数据
      multipleSelection: [],
      selectItem: {
        type: Object,
        default: () => {}
      }
    }
  },
  mounted() {
    this.refreshDataEvent()
  },
  methods: {
    // 验证码回调
    smsCodeCallBack(smsCode) {
      this.confirmDelData(smsCode)
    },
    // 选择时间的回调
    handelTimeChange(val) {
      this.formData.time = val
    },
    // 打开编辑 or 新增
    openEditorDialog(row) {
      if (row === null) {
        this.selectItem = {
          id: null,
          phone: '',
          pwd: '',
          memo: '',
          state: '1',
          roleId: ''
        }
        this.editorDialogTitle = '添加管理员'
        console.log('添加管理员')
      } else {
        console.log('编辑管理员')
        this.editorDialogTitle = '编辑管理员'
        this.selectItem = row
      }
      this.editorDialogVisible = true
      console.log('this editer visable = ' + this.editorDialogVisible)
    },
    // 提交表单
    submitForm() {
      this.refreshDataEvent()
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 当前选中的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.limit = val
      this.refreshDataEvent()
    },
    // 当前页数改变
    handleCurrentPageChange(val) {
      this.currentPage = val
      this.refreshDataEvent()
    },
    // 刷新按钮刷新数据
    refreshData() {
      this.safeDialogVisible = false
      this.editorDialogVisible = false
      this._fetchBaseRequest(true)
    },
    // 刷新数据
    refreshDataEvent() {
      this.safeDialogVisible = false
      this.editorDialogVisible = false
      this._fetchBaseRequest()
    },
    // 根据权限id返回权限名称
    getRoleName(roleId) {
      const roleName = this.roleList.filter(item => item.id === roleId)[0]
      return roleName.roleName
    },
    // 删除管理员
    deleteAdmin(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: '已取消删除'
        })
      })
    },
    // 确认删除数据
    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
      }
      // 删除
      delAdmin(request).then(res => {
        if (parseInt(res.code) === 0) {
          this.safeDialogVisible = false
          this.$message.success('删除成功')
          this.refreshDataEvent()
        } else if (parseInt(res.code) === 401) {
          this.safeDialogVisible = true
          this.$message.error(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 基础请求
    async _fetchBaseRequest(needToast = false) {
      console.log('请求数据')
      const param = {
        phone: this.formData.phone,
        // time: (parseTime(this.formData.time[0]) + '-' + parseTime(this.formData.time[1])),
        roleId: this.formData.roleId,
        p: this.currentPage,
        limit: this.limit
      }
      if (this.formData.time.length > 0) {
        param.time = (this.formData.time[0] + ' - ' + this.formData.time[1])
      }
      let res = {}
      res = await fetchAdminList(param)
      if (parseInt(res.code) === 0 && needToast) this.$message.success('刷新成功~')
      this.userList = res.data.userList
      this.roleList = 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;
    }
    .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>
