<template>
  <div class="position-container">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="职位列表" name="list">
        <!--        <el-row>-->
        <!--          <el-button icon="el-icon-date" @click="allSort()" class="add">批量排序</el-button>-->
        <!--          <el-button icon="el-icon-setting" @click="allResetCache()" class="add">重置缓存</el-button>-->
        <!--        </el-row>-->
        <el-form :inline="true" :model="searchParam" class="demo-form-inline head-form">
          <el-form-item label="关键词">
            <el-input clearable v-model="searchParam.keyword" size="small" placeholder="ID或名称" style="width: 150px"/>
          </el-form-item>
          <el-form-item label="状态">
            <el-select clearable filterable v-model="searchParam.status" size="small" placeholder="-请选择-"
                       style="width: 150px">
              <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="添加人">
            <el-select clearable filterable v-model="searchParam.createUser" size="small" placeholder="-请选择-"
                       style="width: 150px">
              <el-option v-for="item in createUser" :key="item.id" :label="item.username" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="巡检时间">
            <el-date-picker
              placeholder="选择的时间"
              style="width: 220px"
              size="small"
              clearable
              value-format="yyyy-MM-dd"
              v-model="searchParam.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button :loading="tableLoading" @click="search" size="small" icon="el-icon-search" type="primary">搜索</el-button>
            <el-button @click="initSearchParam();search()" icon="el-icon-refresh-right"
                       type="primary" size="small"
                       style="background-color: #fff; border: 1px solid #ccc ; color: #666">清空
            </el-button>
          </el-form-item>
        </el-form>
        <el-table stripe ref="table" :height="tableHeight" v-loading="tableLoading" :data="postList"
                  border row-key="id">
          <el-table-column show-overflow-tooltip type="selection" align="center"/>
          <el-table-column show-overflow-tooltip prop="id" label="ID" align="center" width="100"/>
          <el-table-column show-overflow-tooltip prop="sort" label="排序" align="center" width="100"/>
          <el-table-column show-overflow-tooltip prop="name" label="名称" align="center"/>
          <el-table-column show-overflow-tooltip prop="level" label="级别" align="center"/>
          <el-table-column show-overflow-tooltip prop="remark" label="备注" align="center"/>
          <el-table-column show-overflow-tooltip prop="status" label="状态" align="center" width="120">
            <template slot-scope="{row}">
              {{ row.status === 1 ? '正常' : '禁用' }}
              <el-switch v-if="isAdmin||btnRule.some(btn=>btn=='status')" v-model="row.status" :active-value="1" :inactive-value="2" size="small"
                         @change="changeStatus(row)"/>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="createUsername" label="添加人" align="center"/>
          <el-table-column show-overflow-tooltip prop="formatCreateTime" label="添加时间" align="center" width="160"/>
          <el-table-column v-if="isAdmin||(btnRule.filter(value=>value=='edit'||value=='drop').length>0)"  width="100" label="操作">
            <template slot-scope="scoped">
              <el-row>
                <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='edit')" class="item" effect="dark" content="编辑" placement="bottom">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleAddRole(scoped.row)"/>
                </el-tooltip>
                <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='drop')" class="item" effect="dark" content="删除" placement="bottom">
                  <el-button type="danger" size="mini" class="el-icon-delete"
                             @click="handleDelete(scoped.row)"></el-button>
                </el-tooltip>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="page-current">
          <el-pagination
            background
            :current-page="currentPage"
            :page-size="pageSize"
            prev-text="上一页"
            next-text="下一页"
            layout="total, prev, pager, next, jumper"
            style="display: inline-block;"
            @current-change="handleCurrentChange"
            :total="count"/>
          <el-button class="sure-page-btn">确定</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="isAdmin||btnRule.some(btn=>btn=='add')" label="添加职位" name="add">
        <el-form ref="ruleForm" v-loading="loading" :model="ruleForm" size="small" label-width="100px"
                 style="width: 50%">
          <el-form-item label="名称" prop="name" :rules="[{
                    required: true, message: '名称不能为空', trigger: 'blur'
                  },
                {min: 2, max: 10, message: '长度在2 到 10 个字符', trigger: 'blur'}]">
            <el-input maxlength="10" clearable v-model="ruleForm.name" size="small" placeholder="请输入名称"/>
          </el-form-item>
          <el-form-item label="备注" prop="remark" :rules="[
                {min: 0, max: 200, message: '不超过200个字符', trigger: 'blur'}]">
            <el-input maxlength="200" clearable v-model="ruleForm.remark" type="textarea" rows="5" size="small" placeholder="请输入备注"/>
          </el-form-item>
          <el-form-item label="级别">
            <el-input clearable v-model="ruleForm.level" size="small"/>
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number size="small" v-model="ruleForm.sort"></el-input-number>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch v-model="ruleForm.status" :active-value="1" :inactive-value="2" size="small"/>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-document-add" :loading="addBtnLoading" type="primary" size="small" @click="submitForm('ruleForm',1)"
            >立即提交
            </el-button>
            <el-button icon="el-icon-back" size="small" @click="resetForm('ruleForm')">返回</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

    </el-tabs>
    <!-- 编辑角色 -->
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" center :visible.sync="addDialogVisible" title="编辑岗位">
      <el-form ref="ruleForm" v-loading="loading" :model="ruleForm" size="small" label-width="50px">
        <el-form-item label="名称" prop="name" :rules="[{
                    required: true, message: '名称不能为空', trigger: 'blur'
                  },
                {min: 2, max: 10, message: '长度在2 到 10 个字符', trigger: 'blur'}]">
          <el-input maxlength="10" clearable v-model="ruleForm.name" size="small" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark" :rules="[
                {min: 0, max: 200, message: '不超过200个字符', trigger: 'blur'}]">
          <el-input maxlength="200" clearable v-model="ruleForm.remark" type="textarea" rows="5" size="small" placeholder="请输入备注"/>
        </el-form-item>
        <el-form-item label="级别">
          <el-input clearable v-model="ruleForm.level" size="small"/>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number size="small" v-model="ruleForm.sort"></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="ruleForm.status" :active-value="1" :inactive-value="2" size="small"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                      <el-button icon="el-icon-document-add" :loading="addBtnLoading" type="primary" size="medium" @click="submitForm('ruleForm',2)"
                      >提交
            </el-button>
            <el-button icon="el-icon-back" size="medium" @click="resetForm('ruleForm') ; addDialogVisible = false ">关闭</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import adminApi from '@/api/permission/admin'
  import positionApi from '@/api/permission/position'

  export default {
    name: "position",
    data() {
      return {
        // 当前页
        currentPage: 1,
        // 总条数
        count: 0,
        // 每页条数
        pageSize: 10,
        addBtnLoading: false,
        tableLoading: false,
        // 显示编辑角色弹框
        addDialogVisible: false,
        dialogType: 'new',
        // 用户按钮权限
        btnRoles: [],
        activeName: 'list',
        // 状态
        status: [{
          value: '1',
          label: '正常'
        }, {
          value: '2',
          label: '禁用'
        }],
        delBtnLoading: false,
        createUser: [],
        // 搜索
        searchParam: {
          keywords: '',
          status: '',
          createUser: '',
          time: '',
        },
        postList: [],
        ruleForm: {
          name: '',
          remark: '',
          level: '',
          sort: 1,
          status: 1
        },
        options: [],
        loading: false,
        tableHeight: document.body.clientHeight - 290,
        btnRule:[],
        isAdmin:false
      }
    },
    created() {
      const {btnRule,isAdmin} = this.$store.state.user
      this.btnRule=btnRule
      this.isAdmin=isAdmin
      this.pageSize = parseInt((document.body.clientHeight -344) / 50)
    },
    mounted() {
      this.tableLoading = true
      this.getAllList()
      this.getAdminList()
    },
    watch: {
      activeName() {
        this.initRuleForm()
      }
    },
    methods: {
      initRuleForm() {
        this.ruleForm = {
          name: '',
          remark: '',
          level: '',
          sort: 1,
          status: 1
        }
      },
      // 改变状态
      changeStatus(data) {
        var content = ''
        if (data.status === 1) {
          content = '确定要启用吗？'
        } else {
          content = '确定要禁用吗？'
        }
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            status: data.status == 1 ? '2' : '1',
            id: data.id
          }
          this.tableLoading = true
          positionApi.postChangeStatus(params).then(res => {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
            this.getAllList()
          }).catch(e => {
            let postList = JSON.parse(JSON.stringify(this.postList))
            for (let i = 0; i < postList.length; i++) {
              if (postList[i].id == data.id) {
                postList[i].status = data.status == 1 ? 2 : 1
              }
            }
            this.postList = Object.assign([], postList)
            this.tableLoading = false
          })
        }).catch(() => {
          let postList = JSON.parse(JSON.stringify(this.postList))
          for (let i = 0; i < postList.length; i++) {
            if (postList[i].id == data.id) {
              postList[i].status = data.status == 1 ? 2 : 1
            }
          }
          this.postList = Object.assign([], postList)
          this.$message({
            type: 'info',
            message: '已取消该操作！'
          })
        })
      },
      getAdminList() {
        adminApi.getAdminList().then(res => {
          let createUser = res.data ? res.data : []
          this.createUser = createUser.filter(item => item.status == 1)
        }).catch(e => {
          this.createUser = []
        })
      },
      initSearchParam() {
        this.searchParam = {
          keywords: '',
          status: '',
          createUser: '',
          time: '',
        }
      },
      handleCurrentChange(value) {
        this.currentPage = value
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      // 搜索
      search() {
        this.currentPage = 1
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      // 分页
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`)
      },
      // 获取列表
      getAllList() {
        // 设置分页
        let searchParam = JSON.parse(JSON.stringify(this.searchParam))
        searchParam.page = this.currentPage
        searchParam.pageSize =this.pageSize
        if (searchParam.time && searchParam.time.length > 0) {
          searchParam.startTime = new Date(searchParam.time[0]).getTime() / 1000
          searchParam.endTime = new Date(searchParam.time[1]).getTime() / 1000
          delete searchParam.time
        }
        positionApi.postList(searchParam).then(res => {
          this.postList = res.data.records
          this.count = res.data.total
          this.tableLoading = false
        }).catch(err => {
          this.postList = []
          this.tableLoading = false
        })
      },
      // 新增角色
      handleAddRole(data) {
        this.ruleForm = JSON.parse(JSON.stringify(data))
        this.addDialogVisible = true
      },
      // 删除角色
      handleDelete(data) {
        this.$confirm('您确定要删除岗位吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delBtnLoading = true
          positionApi.postDel({id: data.id}).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.delBtnLoading = false
            this.tableLoading = true
            this.getAllList()
          }).catch(e => {
            this.delBtnLoading = false
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 重置缓存
      resetCache(res) {
        alert('调接口，重置缓存')
      },
      submitForm(formName, type) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
            this.addBtnLoading = true
            if (type == 1) {
              positionApi.postAdd(ruleForm).then(res => {
                this.addBtnLoading = false
                this.initRuleForm()
                this.$refs[formName].resetFields()
                this.tableLoading = true
                this.$message({
                  type: 'success',
                  message: '添加成功！'
                })
                this.getAllList()
              }).catch(e => {
                this.addBtnLoading = false
              })
            } else {
              positionApi.postEdit(ruleForm).then(res => {
                this.addBtnLoading = false
                this.initRuleForm()
                this.$refs[formName].resetFields()
                this.addDialogVisible = false
                this.tableLoading = true
                this.$message({
                  type: 'success',
                  message: '编辑成功！'
                })
                this.getAllList()
              }).catch(e => {
                this.addBtnLoading = false
              })
            }
          } else {
            return false
          }
        })
      },
      resetForm(formName) {
        this.initRuleForm()
        this.$refs[formName].resetFields()
        this.activeName = 'list'
      }
    }
  }
</script>

<style lang="less">

  .position-container {
    width: 100%;

    .head-form {
      width: 100% !important;
    }

    .page-current {
      text-align: center;
      padding: 15px 5px;
      padding-bottom: 0px;

      .sure-page-btn {
        display: inline-block;
        height: 28px;
        line-height: 0;
        width: 46px;
        padding: 0;
        vertical-align: top;
      }
    }
  }


</style>
