<template>
  <div class="app-container">


      <!-- <el-button v-if="isRoleEdit" class="import" style="float: right;" @click="form_inport">导入</el-button>
      <el-dropdown style="float: right;margin-right: 10px;">
        <el-button class="export">导出</el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="form_export(1)">导出模板</el-dropdown-item>
          <el-dropdown-item @click.native="form_export(2)">导出数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown> -->


    <div class="search">

      <el-input v-model="table.getdataListParm.parammaps.userName" placeholder="用户名称" style="width: 180px;" class="filter-item" clearable />
      <el-input v-model="table.getdataListParm.parammaps.empName" placeholder="员工姓名" style="width: 180px;" class="filter-item" clearable />

      <el-select v-model="table.getdataListParm.parammaps.departmentId" placeholder="部门" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="(item,index) in departNameList" :key="index" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="table.getdataListParm.parammaps.enable" placeholder="是否启用" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="(item,index) in enableList" :key="index" :label="item.name" :value="item.id" />
      </el-select>

      <el-button class="successBorder" @click="form_search">查询</el-button>
      <el-button class="successBorder" @click="form_clear">重置</el-button>
      <el-button v-if="isRoleEdit" class="success"   @click="form_add">添加</el-button>
    </div>

    <div class="table">
      <el-table :key="table.tableKey" v-loading="table.listLoading" element-loading-text="给我一点时间" :data="table.list" border fit highlight-current-row style="width: 100%;" :row-style="rowStyle" :cell-style="cellStyle" class="elTable table-fixed" :max-height="myHeight">
        <!-- <el-table-column type="selection" align="center" width="50" /> -->
        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (table.pageNum-1) * table.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名称" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="员工姓名" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.empName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.departmentName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.roleName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="顺序" width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="启用" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="change_enable(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="380" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <!-- <el-button v-if="isRoleEdit" class="miniSuccess" @click="form_edit(row)">编辑</el-button>
            <el-button v-if="isRoleEdit" class="miniDanger" @click="form_delete(row)">删除</el-button> -->

            <el-button class="miniSuccess" @click="handleScanningCode(row)">扫码接收消息</el-button>
            <el-button class="miniSuccess" @click="form_edit(row)">编辑</el-button>
            <el-button class="miniDanger" @click="form_delete(row)">删除</el-button>
            <el-button class="miniSuccess" @click="handleResetPassword(row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="get_table_data" />
    </div>

    <!-- 新增/编辑 -->
    <el-dialog :title="textMap[create.dialogStatus]" :visible.sync="create.dialogFormVisible" :close-on-click-modal="false" width="40%">
      <div class="app-add">
        <el-form ref="temp" :rules="create.rules" :model="create.temp" label-position="right" label-width="150px" style="width: 80%;margin:0 auto 50px">

          <el-form-item label="用户名称：" prop="userName">
            <el-input ref="userName" v-model="create.temp.userName" class="filter-item" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="员工：" prop="empId">
            <el-select ref="empId" v-model="create.temp.empId" filterable class="filter-item" style="width: 100%;" :disabled="create.dialogStatus=='see'" @change="changeCustomer">
              <el-option v-for="(item,index) in empnameList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门：" prop="departmentName">
            <el-input ref="departmentName" v-model="create.temp.departmentName" class="filter-item" style="width: 100%;" disabled/>
          </el-form-item>
          <el-form-item label="角色：" prop="roleId">
            <el-select ref="roleId" v-model="create.temp.roleId" filterable class="filter-item" style="width: 100%;" :disabled="create.dialogStatus=='see'" @change="changeRolename">
              <el-option v-for="(item,index) in roleNameList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input ref="remark" v-model="create.temp.remark" />
          </el-form-item>
          <el-form-item label="顺序：" prop="sort">
            <el-input ref="sort" v-model="create.temp.sort" />
          </el-form-item>
          <el-form-item label="启用：" prop="enable">
            <el-switch ref="enable" v-model="create.temp.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="create.dialogFormVisible = false;get_table_data()">关闭</el-button>
          <el-button v-if="create.dialogStatus==='create' || create.dialogStatus==='update'" class="success" @click="create.dialogStatus==='create'?add_dialog_save():form_edit_save()">确认</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[QRcode.dialogStatus]" :visible.sync="QRcode.dialogFormVisible" :close-on-click-modal="false" width="50%">
      <div class="QRcode">
        <div class="content">
          <div class="title">
            <p>微信接收系统待办等消息，必须先扫码关注公众号；</p >
            <p>请将下方二维码分享给需要接收信息的用户扫码</p >
          </div>
          <div style="font-weight: 600;">关注微信：</div>
          <img :src="imgUrl" alt=""></img>
        </div>
        <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom: 40px;">
          <el-button class="save" :disabled="isokDisable" @click="QRcode.dialogFormVisible = false;">确认</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { GetDataByName, PostDataByName, failproccess, ExecDataByConfig, GetDataByNames, checkButtons, calculativeWidth } from '@/api/common'
import { isIntegerZero } from '@/utils/validate'
import Cookies from 'js-cookie'
import { parseTime } from '@/utils/index.js'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
import { constants } from 'zlib';
export default {
  name: 'User',
  components: { Pagination },
  data() {
    return {
      myHeight:document.documentElement.clientHeight - 85 - 160,
      isokDisable: false,
      isRoleEdit: [],
      enableList: [{ id: 1, name: '是' }, { id: 0, name: '否' }], // 是否启用
      departNameList: [],
      empnameList: [],
      roleNameList: [],
      //表格请求参数~
      table: {
        getdataListParm: {
          name: 'getuserallL',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: {
            userName: '',
            empName: '',
            departmentId: '',
            enable: '',
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        temp: {}
      },

      QRcode:{
        dialogStatus: '',
        dialogFormVisible:false,
      },
      textMap: {
        QRcode:'提示'
      },
      imgUrl:'',

      // 新增/编辑
      create: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: { userName: '', departmentName: '', empId: '', roleId: '', roleName: '', remark: '', sort: '', enable: 1 },
        rules: {
          userName: [{ required: true, message: '必填', trigger: 'blur' }],
          empId: [{ required: true, message: '必填', trigger: 'blur' }],
          roleId: [{ required: true, message: '必填', trigger: 'blur' }]

        },
        getdataListParm2: {
          name: 'getDetByCid',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: { id: "" }
        },
      },
      textMap: {
        create: '添加',
        update: '编辑'
      },

      requestParam: {},

      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },

  created() {
    this.get_table_data()

    this.get_select_list()

    // this.get_auto_buttons()
  },

  methods: {

    handleScanningCode(row){
      this.QRcode.dialogStatus = 'QRcode'
      this.QRcode.dialogFormVisible = true
      // this.imgUrl = 'http://tmrwatch.cn/wx/code?scene_str=tmrwatch_test.'+ Cookies.get('pastureid')+'.'+ row.username + '.'+row.empname


        // this.imgUrl = 'http://tmrwatch.cn/wx/code?scene_str=crm.'+ row.userName


        this.imgUrl = process.env.VUE_APP_BASE_API + 'wx/code?scene_str=crm.'+ row.userName
      console.log(this.imgUrl)
    },
    //获取按钮权限
    get_auto_buttons() {
      const Edit = 'DungScores'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },

    //获取所有下拉框的内容
    get_select_list() {
      GetDataByName({ name: 'getDepartmentsSelect', offset: 0, pagecount: 0, parammaps: {} }, ).then(response => {
        this.departNameList = response.data.list
        console.log("部门下拉框", response)
      })
      GetDataByName({ name: 'getEmpList', offset: 0, pagecount: 0, parammaps: {} }, ).then(response => {
        this.empnameList = response.data.list
        console.log("员工下拉框", response)
      })
      GetDataByName({ name: 'getRoleAll', offset: 0, pagecount: 0, parammaps: {} }, ).then(response => {
        this.roleNameList = response.data.list
        console.log("角色下拉框", response)
      })


    },


    //加载表格
    get_table_data() {
      this.table.listLoading = true
      console.log("this.table.getdataListParm======>", this.table.getdataListParm)
      GetDataByName(this.table.getdataListParm).then(response => {
        console.log('table数据======>', response.data.list)
        if (response.data.list !== null) {
          for (var i = 0; i < response.data.list.length; i++) {
            response.data.list[i].enable = parseInt(response.data.list[i].enable)
          }

          this.table.list = response.data.list
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
          this.table.total = response.data.total
        } else {
          this.table.list = []
        }
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    form_search() {
      console.log('点击了查询')

      this.table.getdataListParm.offset = 1
      this.get_table_data()
    },
    form_clear() {
      console.log('点击了重置')


      this.table.getdataListParm.parammaps.userName = ''
      this.table.getdataListParm.parammaps.empName = ''
      this.table.getdataListParm.parammaps.departmentId = ''
      this.table.getdataListParm.parammaps.enable = ''
      this.table.getdataListParm.offset = 1
      this.get_table_data()
    },

    // 添加
    form_reset() {
      this.create.temp = { userName: '', departmentName: '', empId: '', roleId: '', roleName: '', remark: '', sort: '', enable: 1 }
    },


    //监听 - 员工
    changeCustomer(item) {
      console.log(item)
      this.create.getdataListParm2.parammaps.id = item
      this.getGroupNameId()
    },

    changeRolename(item) {
      this.create.temp.roleName = this.roleNameList.find(obj => obj.id == item).name
    },

    // 部门名称
    getGroupNameId() {
      GetDataByName(this.create.getdataListParm2).then(response => {
        if (response.data.list !== null) {
          this.create.temp.departmentName = response.data.list[0].name
          this.create.temp.departmentId = response.data.list[0].id
          console.log('集团名称', response.data.list)
        }
      })
    },

    //添加
    form_add() {
      console.log('点击了新增')
      this.form_reset()
      this.create.dialogStatus = 'create'
      this.create.dialogFormVisible = true
    },
    //添加保存
    add_dialog_save() {
      console.log('点击了新增保存')
      this.$refs['temp'].validate(valid => {
        if (valid) {

          //新增保存
          this.requestParam.name = 'createUser'
          this.requestParam.parammaps = this.create.temp

          var send_data = {
              "common": {"returnmap": "0"},
              "data": [
                {
                  "name": "createUser",
                  "type": "e",
                  "parammaps": this.create.temp
                },
                {
                   "name": "clearUserRoleByUserId",
                   "type": "e",
                   "parammaps": {
                    "id": "@createUser.LastInsertId"
                  }
              }, {
                "name": "insertUserRole",
                "type": "e",
                "parammaps": {
                "id": "@createUser.LastInsertId",
                "roleId": this.create.temp.roleId
                }
              }, {
                "name": "refreshUserIdOfEmployees",
                "type": "e",
                "parammaps": {
                "id": "@createUser.LastInsertId",
                "empId": this.create.temp.empId
                }
              } ]
              }
              ExecDataByConfig(send_data).then(response => {
            console.log('新增保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.get_table_data()
            } else {
              this.$notify({ title: '失败', message: '保存失败', type: 'error', duration: 2000 })
            }
          })


        }
      })
    },


    // 编辑
    form_edit(row) {
      console.log('点击了编辑', row)


      this.create.temp = Object.assign({}, row)
      this.create.temp.id = row.id
      this.create.dialogStatus = 'update'
      this.create.dialogFormVisible = true

      this.create.getdataListParm2.parammaps.id = row.empid
      this.getGroupNameId()
    },

    // 编辑保存
    form_edit_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {


          var send_data =  {
              "common":{"returnmap":"0"},
              "data":[
                {
                  "name":"updateUser",
                  "type":"e",
                  "parammaps":this.create.temp
                },
                {
                  "name": "clearUserRoleByUserId",
                  "type":"e",
                  "parammaps": {"id": this.create.temp.id}
                },
                {
                  "name": "insertUserRole",
                  "type":"e",
                  "parammaps":{"id":this.create.temp.id,"roleId":this.create.temp.roleId}
                }, {
                  "name": "clearUserIdOfEmployees",
                  "type": "e",
                  "parammaps": {
                  "id":this.create.temp.id
                  }
                }, {
                  "name": "refreshUserIdOfEmployees",
                  "type": "e",
                  "parammaps": {
                  "id": this.create.temp.id,
                  "empId": this.create.temp.empId
                  }
                }
             ]
            }


          ExecDataByConfig(send_data).then(response => {
            console.log('编辑保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.get_table_data()
            } else {
              this.$notify({ title: '失败', message: '保存失败', type: 'error', duration: 2000 })
            }
          })
        }
      })
    },

    // 表格中的启用
    change_enable(index, row) {
      this.requestParam.name = 'updateUser'
      this.requestParam.parammaps = this.create.temp

      console.log(row)

     var send_data = {
      "name":"updateUser",
      "parammaps":   {
        "userName":row.userName,"departmentName":row.departmentName,"empId":row.empId,"roleId":row.roleId,"roleName":row.roleName,"remark":row.remark,"sort":row.sort,"enable":row.enable,"id": row.id}
    }

      PostDataByName(send_data).then(response => {
        console.log('表格中的启用发送参数', send_data)
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.create.dialogFormVisible = false
          this.get_table_data()
        } else {
          this.$notify({ title: '失败', message: '保存失败', type: 'error', duration: 2000 })
        }
      })


    },

    // 删除
    form_delete(row) {
      MessageBox.confirm('是否确认删除此信息?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deleteUser'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.id = row.id
        PostDataByName(this.requestParam).then(response => {
          if (response.msg === 'fail') {
            this.$notify({ title: '删除失败', message: response.data, type: 'warning', duration: 2000 })
          } else {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.get_table_data()
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    handleResetPassword(row) {
      MessageBox.confirm('是否确认将此用户密码重置为默认密码123456？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'initPassword'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.pastureid = row.pastureid
        this.requestParam.parammaps.id = row.id
        PostDataByName(this.requestParam).then(() => {
          this.get_table_data()

          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '重置密码成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },

    // 导出
    form_export(item) {
      if (item == 1) {
        console.log('点击了导出模板')
      } else {
        console.log('点击了导出数据')
      }
    },

    // 导入
    form_inport() {
      console.log('点击了导入')
    }

  }
}
</script>
<style lang="scss" scoped>
.search {
  padding-top: 10px;
  clear: both;
}
.table {
  margin-top: 10px;
}
</style>
