<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
<!--      <el-col :span="4" :xs="24">-->
<!--        <div class="head-container">-->
<!--          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"-->
<!--                    style="margin-bottom: 20px"/>-->
<!--        </div>-->
<!--        <div class="head-container">-->
<!--          <el-tree-->
<!--            :data="deptOptions"-->
<!--            :props="defaultProps"-->
<!--            :expand-on-click-node="false"-->
<!--            :filter-node-method="filterNode"-->
<!--            ref="tree"-->
<!--            default-expand-all-->
<!--            @node-click="handleNodeClick"/>-->
<!--        </div>-->
<!--      </el-col>-->
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <div class="filter-container" style="margin-bottom: 15px">
          <el-input
            v-model="search.keyWord"
            placeholder="关键字"
            style="width: 200px;"
            class="filter-item"
            :size="tableSize"
            @keyup.enter.native="handleFilter"/>
          <template>
            <!-- `checked` 为 true 或 false -->
            <el-checkbox v-model="checked" @change="checkLock">查看已禁用</el-checkbox>
          </template>

          <el-button :size="tableSize" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            搜索
          </el-button>
          <el-button
            v-if="webType && isChoose == false && permissionFlag4"
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            icon="el-icon-plus"
            :size="tableSize"
            @click="handleCreate(1)">
            增加用户
          </el-button>
<!--          <el-button-->
<!--            v-if="webType && isChoose == false && permissionFlag1"-->
<!--            class="filter-item"-->
<!--            style="margin-left: 10px;"-->
<!--            type="primary"-->
<!--            icon="el-icon-plus"-->
<!--            :size="tableSize"-->
<!--            @click="handleCreate(2)">-->
<!--            增加人员-->
<!--          </el-button>-->
          <el-button
            v-if="type == 1"
            :size="tableSize"
            class="filter-item"
                     style="margin-left: 10px;"
                     type="success"
                     @click="chooseList">选择</el-button>
        </div>
        <el-table
          :data="tableData"
          border
          v-loading="listLoading"
          style="width: 100%;margin-bottom: 20px;"
          :size="tableSize"
          ref="userList"
          row-key="id"
          @selection-change="selectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            v-if="type == 1"
            :reserve-selection="true"
          >
          </el-table-column>
          <!--      <el-table-column-->
          <!--        prop="id"-->
          <!--        label="用户ID">-->
          <!--      </el-table-column>-->
          <el-table-column
            prop="loginName"
            label="登录名称">
          </el-table-column>
          <el-table-column
            prop="userName"
            label="用户名">
          </el-table-column>
<!--          <el-table-column-->
<!--            prop="deptName"-->
<!--            label="部门">-->
<!--          </el-table-column>-->
<!--          <el-table-column-->
<!--            prop="email"-->
<!--            label="邮箱">-->
<!--          </el-table-column>-->
          <el-table-column
            prop="phoneNumber"
            label="手机">
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态">
            <template slot-scope="{row}">
              <el-tag v-if="row.status==0" type="success">
                正常
              </el-tag>
              <el-tag v-else="row.status==1" type="danger">
                停用
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="155">
            <template slot-scope="{row}">
          <span v-if="row.createTime">
          {{ row.createTime | getTime }}
            </span>
            </template>
          </el-table-column>
          <el-table-column v-if="type !=1" fixed="left" label="操作" align="center" width="300"
                           class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <template v-if="webType">
                <template v-if="!isChoose">
              <el-button v-if="permissionFlag5" @click="handleUpdate(row.id,1)" class="operateBtn" type="primary" size="mini">
                权限设定
              </el-button>
              <el-button @click="resetPwd(row.id)" class="operateBtn" type="success" size="mini">
                重置密码
              </el-button>
              <!--          <el-button @click="dialogVisible = true" class="operateBtn" type="warning" size="mini">-->
              <!--            修改密码-->
              <!--          </el-button>-->
              <el-button @click="editStatus(row.id,'1')" class="operateBtn" type="danger" v-if="row.status==0"
                         size="mini">
                停用
              </el-button>
              <el-button @click="editStatus(row.id,'0')" class="operateBtn" v-else size="mini">
                启用
              </el-button>
<!--                  <el-button v-if="permissionFlag2" @click="handleUpdate(row.id,2)" class="operateBtn" type="primary" size="mini">-->
<!--                    编辑-->
<!--                  </el-button>-->
<!--                  <el-button v-if="permissionFlag3" @click="configUser(row.id)" class="operateBtn" type="warning" size="mini">-->
<!--                    角色配置-->
<!--                  </el-button>-->

                </template>
                <template v-else>
                  <el-button @click="sourceType == 1? chooseThisTo(row):chooseThis(row)" type="primary" size="mini">
                    选择
                  </el-button>
                </template>
              </template>
              <template v-else>
                <el-button @click="ERPChoose(row)" type="primary" size="mini">
                  选择
                </el-button>
              </template>
            </template>
          </el-table-column>

        </el-table>

        <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page" :limit.sync="listData.pageSize" @pagination="getHomeInfo" />
      </el-col>
    </el-row>
    <el-dialog :close-on-click-modal="false" title="修改密码" :visible.sync="dialogVisible" width="80%">
    <el-form label-width="130px" label-position="right">
      <el-form-item label="旧密码">
        <el-input v-model="oldPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码">
        <el-input v-model="newPassword" type="password"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="changePwd">确 定</el-button>
    </div>

  </el-dialog>

    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
    <roledialog @tableRefresh="tableRefresh" ref="roleDialog"></roledialog>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import {listUser, changeMyPassword, resetLoginUser, getDeptTreeData} from '@/api/system/user.js'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Roledialog from './Roledialog.vue'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import {ifPermission} from "@/api/order/orderList";

export default {
  name: 'User',
  components: {
    Pagination,
    Cancledialog,
    Roledialog
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'roles'
    ])
  },
  props: {
    isChoose: {
      type: Boolean,
      default: false
    },
    type: {
      type: Number,
      default: 0
    },
    tableSize: {
      type: String,
      default: ''
    },
    /**
     * 调用来源
     * 0 普通调用
     * 1 查询统计调用
     */
    sourceType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      webType: true,
      total: 0,
      listLoading: false,
      tableData: [],

      // 部门树数据
      deptOptions: undefined,
      deptName: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },

      dialogVisible: false,
      oldPassword: '',
      newPassword: '',
      checked: false,
      search: {
        keyWord: '',
        status: 0,
        deptId: undefined
      },
      listData: {
        total: 0,
        page: 1,
        pageSize: 10
      },
      chooseInfoList: [],
      permissionFlag1: false,
      permissionFlag2: false,
      permissionFlag3: false,
      permissionFlag4: false,
      permissionFlag5: false,
    }
  },
  mounted() {

    this.getHomeInfo()
    this.getDeptTree()

    this.checkPermission('system:user:addinfo')
    this.checkPermission('system:user:editinfo')
    this.checkPermission('system:user:configrole')
    this.checkPermission('system:user:add')
    this.checkPermission('system:user:edit')
  },
  methods: {
    // 判断权限
    checkPermission(perString) {
      const _that = this
      var data = {
        permission: perString
      }
      ifPermission(data).then(res => {
        // console.log(res)
        if (res.data == 1) {
          if (perString == 'system:user:addinfo') {
            _that.permissionFlag1 = true
          }
          if (perString == 'system:user:editinfo') {
            _that.permissionFlag2 = true
          }
          if (perString == 'system:user:configrole') {
            _that.permissionFlag3 = true
          }
          if (perString == 'system:user:add') {
            _that.permissionFlag4 = true
          }
          if (perString == 'system:user:edit') {
            _that.permissionFlag5 = true
          }
        }
      })
    },
    handleCreate(type) {
      //type 1 管理员增加 2人事增加
      // 增加
      const _that = this
      if(type == 1){
        _that.$refs.roleDialog.getRole()
      }
      _that.$refs.roleDialog.handleCreateAdd(type)
      _that.$refs.roleDialog.innerText = ''
    },
    handleUpdate(id,type) {
      // 修改
      const _that = this
      if(type == 1){
        _that.$refs.roleDialog.getRole()
      }
      _that.$refs.roleDialog.handleUpdata(id,type)
      _that.$refs.roleDialog.innerText = ''
    },
    //角色配置
    configUser(id){
      const _that = this
      _that.$refs.roleDialog.getRole()
      _that.$refs.roleDialog.handleConfig(id)
      _that.$refs.roleDialog.innerText = ''
    },
    // 获取列表信息
    getHomeInfo() {
      const _that = this
      var params = _that.search
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      var data = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }
      listUser(data).then(response => {
        var data = response
        _that.tableData = response.data
        _that.listData.total = response.total
      })
    },

    // 获取部门树
    getDeptTree() {
      var _that = this
      var data = {}
      getDeptTreeData(data).then(res => {
        // console.log(res)

        const deptData = _that.getDeptsData(res.data)
        var all = {
          title: '全部',
          name: '全部',
          id: 0
        }
        deptData.unshift(all)
        _that.deptOptions = deptData
      })
    },
    getDeptsData(data) {
      var deptData = data
      // console.log(deptData)
      deptData.forEach((item, index) => {
        const parentId = item.pId
        if (parentId === 0) {
          // 是根元素的hua ,不做任何操作,如果是正常的for-i循环,可以直接continue.
        } else {
          // 如果ele是子元素的话 ,把ele扔到他的父亲的child数组中.
          deptData.forEach(d => {
            if (d.id === parentId) {
              let childArray = d.children
              if (!childArray) {
                childArray = []
              }
              childArray.push(item)
              d.children = childArray
              deptData.splice(index, 1)
            }
          })
        }
      })
      return deptData
    },
    // 关键字筛选部门树
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    checkLock() {
      if (this.checked) {
        this.search.status = 1;
      } else {
        this.search.status = 0
      }
    },

    // 部门树选中
    handleNodeClick(data) {
      var _that = this
      _that.search.deptId = data.id;
      // console.log(data);
      _that.$refs.roleDialog.innerText =data.name;
      _that.$refs.roleDialog.checkedDept =data.name;
      _that.$refs.roleDialog.handleTree =true;
      _that.$refs.roleDialog.getRole()
      _that.$refs.roleDialog.treeData =data;
      _that.getHomeInfo()
    },

    tableRefresh() {
      // 刷新表格
      this.getHomeInfo()
    },
    handleFilter() {
      this.listData.page = 1
      this.getHomeInfo()
    },
    // 启用禁用
    editStatus(id, status) {
      var _that = this
      var printerTypeInfo = {
        id: id,
        status: status
      }
      var params = {
        'info': JSON.stringify(printerTypeInfo)
      }

      var url = '/system/voidLoginUser'
      _that.$refs.confirmDialog.updataClick(params, url)
    },
    // 重置密码
    resetPwd(id) {
      var _that = this
      var info = {
        id: id
      }
      var params = {
        'info': JSON.stringify(info)
      }

      resetLoginUser(params).then(response => {
        // console.log(response)
        if (response.httpCode == 200) {
          _that.$alert('密码重置为123456', {
            confirmButtonText: '确定',
            callback: action => {

            }
          })
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 修改密码
    changePwd() {
      var _that = this
      var data = {
        'oldPassword': _that.oldPassword,
        'newPassword': _that.newPassword
      }
      changeMyPassword(data).then(response => {
        if (response.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '修改成功',
            type: 'success'
          })
        }
      })
    },
    // 弹窗内选择操作
    chooseThis(row) {
      // console.log('点击选择');
      this.$emit('chooseUser', row)
    },
    // 多选
    chooseList() {
      this.$emit('chooseUser', this.chooseInfoList)
    },
    selectionChange(val) {
      const _that = this
      _that.chooseInfoList = val
    },
    // 查询统计选择
    chooseThisTo(row) {
      var data = {
        id: row.id,
        name: row.userName
      }
      this.$emit('chooseRow', data)
    },
    ERPChoose(row) {
      // this.$message.error(row)
      dyERP.sendJson(JSON.stringify(row))
    },
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.operateBtn {
  margin: 5px 0;
}
</style>
