<template>
  <div class="mod-user">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.userName" placeholder="用户账号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()" type="primary">查询</el-button>
        <el-button v-if="isAuth('sys:user:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button v-if="isAuth('sys:user:save')" :disabled="this.showButton" type="primary"
                   @click="specialAuthorize()"
        >特殊权限
        </el-button>
        <el-button v-if="isAuth('sys:user:save')" :disabled="this.showButton" type="primary"
                   @click="siteAuthorize()"
        >工厂授权
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      :height="height"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      highlight-current-row
      @current-change="handleCurrentChange"
      style="width: 100%;">
      <!--      <el-table-column-->
      <!--        type="selection"-->
      <!--        header-align="center"-->
      <!--        align="center"-->
      <!--        width="50">-->
      <!--      </el-table-column>-->
      <!--      <el-table-column-->
      <!--        prop="userId"-->
      <!--        header-align="center"-->
      <!--        align="center"-->
      <!--        width="80"-->
      <!--        label="ID">-->
      <!--      </el-table-column>-->
      <el-table-column
        prop="username"
        header-align="center"
        align="center"
        label="用户账号">
      </el-table-column>
      <el-table-column
        prop="userDisplay"
        header-align="center"
        align="center"
        label="用户名">
      </el-table-column>
      <el-table-column
        prop="email"
        header-align="center"
        align="center"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="mobile"
        header-align="center"
        align="center"
        label="手机号">
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        label="状态">
        <template slot-scope="scope">
          <el-link v-if="scope.row.status === 0" type="success">禁用</el-link>
          <el-link v-else type="danger">正常</el-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        width="180"
        label="创建时间">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <a type="text" size="small" @click="generateData(scope.row)">审核</a>
          <a v-if="isAuth('sys:user:update')" type="text" size="small"
             @click="addOrUpdateHandle(scope.row.userId)">修改</a>
          <a v-if="isAuth('sys:user:delete')" type="text" size="small" @click="deleteHandle(scope.row.userId)">删除</a>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      highlight-current-row
      @current-change="handleCurrentChange"
      :current-page="pageIndex"
      :page-sizes="[20, 50, 100, 200,500]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <!--  审核权限   -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" v-drag :title="inputSearch1"
               :visible.sync="setUp.reviewFlag" width="560px">
      <template>
        <el-transfer v-model="checked" :data="transferData" :titles="['所有权限', '当前权限']"></el-transfer>
      </template>
      <span slot="footer" class="dialog-footer">
      <el-button @click="setUp.reviewFlag = false">取消</el-button>
      <el-button type="primary" :disabled="setUp.saveButton" @click="saveUserRoleFlag()">确定</el-button>
    </span>
    </el-dialog>
    <!--  特殊权限  -->
    <el-dialog
      v-drag
      :title="'特殊性权限'"
      :visible.sync="specialVisible"
      width="820px"
      :append-to-body="true">
      <el-table
        :data="securityList"
        border
        :height="securityHeight"
        v-loading="dataListLoading"
        style="width: 100%;">
        <el-table-column
          v-for="(item,index) in columnList" :key="index"
          :sortable="item.columnSortable"
          :prop="item.columnProp"
          :header-align="item.headerAlign"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :align="item.align"
          :fixed="item.fixed"
          :min-width="item.columnWidth"
          :label="item.columnLabel">
          <template slot-scope="scope">
            <span v-if="!item.columnHidden"> {{ scope.row[item.columnProp] }}</span>
            <span v-if="item.columnHidden">
              <el-checkbox v-model="scope.row[item.columnProp] "></el-checkbox>
            </span>
            <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]"
                                               style="width: 100px; height: 80px"/></span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveUserSecurity()">确定</el-button>
        <el-button @click="specialVisible = false" type="primary">取消</el-button>
    </span>
    </el-dialog>
    <!--  工厂授权  -->
    <el-dialog
      style="font-size: 12px"
      v-drag
      :title="'工厂授权'"
      :visible.sync="siteVisible"
      width="520px"
      :append-to-body="true">
      <el-transfer v-model="selectSitList" :data="siteList" :titles="['未授权工厂', '已授权工厂']"></el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveUserAssessSite()">确定</el-button>
        <el-button @click="siteVisible = false" type="primary">取消</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import {getUserAccessSiteList, saveUserAccessSiteList} from '@/api/factory/accessSite.js'
import {getSiteList} from '@/api/factory/site.js'
import AddOrUpdate from './user-add-or-update'
import {getUserBusinessRoleList, saveUserBusinessRole,} from '@/api/auditManagement/auditType.js'

import {
  getUserSpecialSecurity,
  saveUserSpecialSecurity,
  updateUserSpecialSecurity
} from '@/api/factory/userSpecialSecurity.js'


export default {
  data() {
    return {
      showButton: true,
      height: 200,
      securityHeight: 200,
      specialVisible: false,
      siteVisible: false,
      currentData: {},
      userId: this.$store.state.user.name,
      transferData: [],
      checked: [],
      inputSearch1: '审核权限',
      //设置
      setUp: {
        reviewFlag: false,
        saveButton: false,
      },
      dataForm: {
        userName: ''
      },
      columnList: [
        {
          userId: this.$store.state.user.name,
          serialNumber: 'security' + this.$route.meta.menuId + 'securitydesc',
          tableId: this.$route.meta.menuId + 'security',
          tableName: "securityTable",
          columnProp: "securitydesc",
          headerAlign: "center",
          align: "left",
          columnLabel: "参数描述",
          columnHidden: false,
          columnImage: false,
          columnWidth: 70,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false,
        },
        {
          userId: this.$store.state.user.name,
          serialNumber: 'security' + this.$route.meta.menuId + 'securitydesc',
          tableId: this.$route.meta.menuId + 'security',
          tableName: "securityTable",
          columnProp: "module",
          headerAlign: "center",
          align: "left",
          columnLabel: "模块",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          columnWidth: 20,
          sortLv: 0,
          status: true,
          fixed: false,
        },
        {
          userId: this.$store.state.user.name,
          serialNumber: 'security' + this.$route.meta.menuId + 'securitydesc',
          tableId: this.$route.meta.menuId + 'security',
          tableName: "securityTable",
          columnProp: "itemvalue",
          headerAlign: "center",
          align: "center",
          columnLabel: "参数值",
          columnHidden: true,
          columnImage: false,
          columnSortable: false,
          columnWidth: 10,
          sortLv: 0,
          status: true,
          fixed: false,
        },
      ],
      dataList: [],
      securityList: [],
      selectSpecialList: [],
      siteList: [],
      selectSitList: [],
      selectUser: {},
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    }
  },
  components: {
    AddOrUpdate
  },
  activated() {
    this.getDataList()
  },
  mounted() {
    this.$nextTick(() => {
      this.securityHeight = window.innerHeight - 400;
      this.height = window.innerHeight - 200;
    })
  },
  methods: {

    // 特殊权限
    specialAuthorize() {
      this.specialVisible = true
      this.searchUserSpecialSecurity()
    },
    // 获取特殊权限
    searchUserSpecialSecurity() {
      saveUserSpecialSecurity({userid: this.selectUser.username}).then(({data}) => {
        if (data.code === 0) {
          getUserSpecialSecurity(this.selectUser.username).then(({data}) => {
            if (data.code === 0) {
              this.securityList = data.dataList.map(item => {
                item.itemvalue = item.itemvalue == 'Y' ? true : false;
                return item;
              })
            }
          })
        }
      })
    },
    // 保存用户权限
    saveUserSecurity() {
      let  securityList = JSON.parse(JSON.stringify(this.securityList)).map(item => {
        item.itemvalue = item.itemvalue === true ? 'Y' : 'N';
        return item;
      })
      updateUserSpecialSecurity(securityList).then(({data}) => {
        if (data.code === 0) {
          this.$message.success(data.msg)
          this.specialVisible = false
        }else {
          this.$message.success(data.msg)
        }
      })
    },
    // 授权工厂
    siteAuthorize() {
      this.siteVisible = true
      this.searchSiteList()

    },
    // 保存选中的授权工厂
    saveUserAssessSite() {
      let accessSiteList = this.selectSitList.map(item => {
        let itemSite = {
          userid: this.selectUser.username,
          site: item
        }
        return itemSite;
      })
      let accessSite = {
        userid: this.selectUser.username,
        accessSiteList: accessSiteList
      }

      saveUserAccessSiteList(accessSite).then(({data}) => {
        if (data.code === 0) {
          this.$message.success(data.msg)
          this.siteList = []
          this.selectSitList = []
          this.siteVisible = false
        } else {
          this.$message.warning(data.msg)
        }
      })
    },
    // 获取用户已授权的工厂列表
    searchUserAccessSiteList() {
      getUserAccessSiteList({userid: this.selectUser.username}).then(({data}) => {
        this.selectSitList = data.dataList
      })
    },
    // 获取所有可用工厂
    searchSiteList() {
      getSiteList({active: 'Y'}).then(({data}) => {
        this.siteList = data.dataList
        this.searchUserAccessSiteList()
      })
    },
    // 选中行
    handleCurrentChange(val) {
      this.selectUser = val
      this.showButton = false
    },
    saveUserRoleFlag() {
      let saveList = []
      let currentList = this.checked
      // 当前未选择记录
      if (currentList.length == 0) {
        this.$confirm("当前未选择记录,是否继续？", '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          let data = {
            userId: this.currentData.userId,
          }
          saveList.push(data);
          this.saveUserBusinessRole(saveList)
        }).catch(() => {
          return
        })
      } else {
        for (let i = 0; i < currentList.length; i++) {
          let data = {
            userId: this.currentData.userId,
            roleItemNo: currentList[i],
            selectFlag: 'Y',
          }
          saveList.push(data);
        }
        this.saveUserBusinessRole(saveList)
      }
    },
    saveUserBusinessRole(saveList) {
      saveUserBusinessRole(saveList).then(({data}) => {
        this.$alert(data.msg, '操作提示', {
          confirmButtonText: '确定',
          callback: action => {
            if (data.code == 0) {
              this.setUp.reviewFlag = false
            }
            this.setUp.saveButton = false
          }
        });
      })
    },
    generateData(row) {
      this.currentData = row
      let queryData = {
        active: 'Y',
        userId: this.currentData.userId,
      }
      getUserBusinessRoleList(queryData).then(({data}) => {
        let rows1Data = data.map.rows1
        let rows2Data = data.map.rows2
        let forData = []
        let checkedList = []
        for (let i = 0; i < rows1Data.length; i++) {
          forData.push({
            key: rows1Data[i].roleItemNo,
            label: rows1Data[i].roleDesc,
          });
        }
        for (let j = 0; j < rows2Data.length; j++) {
          checkedList.push(rows2Data[j].roleItemNo)
        }
        this.transferData = forData;
        this.checked = checkedList
        this.setUp.reviewFlag = true
      })
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/sys/user/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'username': this.dataForm.userName
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle(id) {
      var userIds = id ? [id] : this.dataListSelections.map(item => {
        return item.userId
      })
      this.$confirm(`确定对[id=${userIds.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sys/user/delete'),
          method: 'post',
          data: this.$http.adornData(userIds, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('操作成功')
            this.getDataList()
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style scoped lang="scss">
/* 穿梭框外框高宽度 */
/deep/ .el-transfer-panel {

  width: 600px;
  height: 400px;
}

/* 穿梭框内部展示列表的高宽度 */
/deep/ .el-transfer-panel__list {

  height: 375px;
}
</style>
