<template>
  <div class="app-container">
    <div class="app-container">
      <div class="filter-container">
        <el-input v-model="getdataListParm.parammaps.empCode" placeholder="用户名" style="width: 140px;" class="filter-item" />
        <el-input v-model="getdataListParm.parammaps.empname" placeholder="姓名" style="width: 140px;" class="filter-item" />
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add"> 新增 </el-button>
      </div>
      <el-table v-loading="listLoading" element-loading-text="给我一点时间" :data="list" border fit highlight-current-row style="width: 100%;" :row-style="rowStyle" :cell-style="cellStyle" class="elTable" row-key="id" default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column label="用户名称" header-align="center" width="120px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" min-width="120px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.empname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" min-width="120px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.deptname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="120px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.roleName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="顺序" min-width="80px" 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="操作" header-align="center" align="center" width="260" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button type="warning" size="mini" @click="handleRole(row)"> 角色 </el-button>
            <el-button type="primary" size="mini" @click="form_edit(row)"> 编辑 </el-button>
            <el-button v-if="row.status!='已删'" size="mini" type="danger" @click="handleDelete(row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>=0" :total="total" :page.sync="getdataListParm.offset" :limit.sync="getdataListParm.pagecount" @pagination="get_table_data" />

      <!-- 编辑 -->
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
        <el-form ref="dataForm" :rules="rules" :model="dataform" label-position="left" label-width="100px" style="width: 600px; margin-left:50px;">
          <el-form-item label="职工名" prop="empid">
            <el-autocomplete ref="empid" v-model="dataform.empname" value-key="empid" class="inline-input" :fetch-suggestions="formNameSearch" placeholder="请输入内容" style="width:80%" @select="handleformNameSelect">
              <template slot-scope="{ item }">
                <div class="name" style="display: inline;">姓名： {{ item.empname }}</div>
                <span class="addr"> 职位：{{ item.position }}</span>
              </template>
            </el-autocomplete>
          </el-form-item>

          <el-form-item label="用户名" prop="username">
            <el-input ref="username" v-model="dataform.username" />
          </el-form-item>
          <el-form-item label="顺序" prop="sort">
            <el-input ref="sort" v-model="dataform.sort" />
          </el-form-item>
          <el-form-item label="启用" prop="enable">
            <el-switch ref="enable" v-model="dataform.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 type="primary" @click="form_edit_save()"> 确认 </el-button>
          <el-button @click="dialogFormVisible = false"> 关闭 </el-button>
        </div>
      </el-dialog>

      <!-- 新增 -->
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisibleAdd" :close-on-click-modal="false">
        <el-form ref="dataForm" :rules="rules" :model="dataform" label-position="left" label-width="100px" style="width: 600px; margin-left:50px;">
          <el-form-item label="职工名" prop="empid">
            <el-autocomplete ref="empid" v-model="dataform.empname" value-key="empid" class="inline-input" :fetch-suggestions="formNameSearch" placeholder="请输入内容" style="width:100%" @select="handleformNameSelect">
              <template slot-scope="{ item }">
                <div class="name" style="display: inline;">姓名： {{ item.empname }}</div>
                <span class="addr"> 职位：{{ item.position }}</span>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input ref="username" v-model="dataform.username" />
          </el-form-item>
          <el-form-item label="角色" prop="rolename">
            <el-select filterable v-model="dataform.selectedRole" style="width:500px;" multiple placeholder="请选择">
              <el-option v-for="(item,index) in rolelist" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="启用" prop="enable">
            <el-switch ref="enable" v-model="dataform.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 type="primary" @click="add_dialog_save()"> 确认 </el-button>
          <el-button @click="dialogFormVisibleAdd = false"> 关闭 </el-button>
        </div>
      </el-dialog>

      <!-- 角色 -->
      <el-dialog :title="textMap['role']" :visible.sync="dialogRoleVisible" :close-on-click-modal="false">
        <el-form :rules="rules" label-position="left" label-width="100px" style="width: 600px; margin-left:50px;">
          <el-form-item label="角色" prop="rolename">
            <el-select filterable v-model="selectedRole" style="width:500px;" multiple placeholder="请选择">
              <el-option v-for="(item,index) in rolelist" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="updateRole()"> 确认 </el-button>
          <el-button @click="dialogRoleVisible = false"> 关闭 </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { isIntegerZero } from '@/utils/validate'
import { PostDataByName, GetDataByName, GetDataByNames, form_edit_saveRelation, ExecDataByConfig } from '@/api/common'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
export default {
  name: 'User',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [{ sqlname: '', id: 0, sqlstr: '' }],
      total: 0,
      listLoading: true,
      requestParam: {
        name: 'createapisql',
        offset: 0,
        pagecount: 0,
        params: []
      },
      send_select_list: [
        { name: 'getRoleall', offset: 0, pagecount: 0, parammaps: { pastureid: Cookies.get('pastureid') } },
        { name: 'getEmpall', offset: 0, pagecount: 0, params: [] }
      ],
      requestFilterParams: {
        returntype: 'Map',
        parammaps: {}
      },
      form_edit_saveRelationParam: {
        name: '',
        dataname: '',
        datavalue: '',
        valuename: '',
        values: []
      },
      dataform: {
        empname: '',
        position: '',
        username: '',
        fullname: '',
        empid: '',
        id: '',
        sort: '',
        enable: 1,
        selectedRole: ''
      },
      temp1: {
        empname: '',
        empid: '',
        position: ''
      },
      rolelist: [],
      emplist: [],
      getdataListParm: {
        name: 'getuserallL',
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          pastureId: Cookies.get('pastureid'),
          empCode: '',
          empname: ''
        }
      },
      rules: {
        empid: [{ required: true, message: '用户名必填', trigger: 'blur' }],
        username: [{ type: 'string', required: true, message: '用户名必填', trigger: 'change' }],
        empname: [{ type: 'string', required: true, message: '职工名必填', trigger: 'change' }],
        // rolename: [{ required: true, message: '角色必填', trigger: 'blur' }],

        sort: [{ validator: isIntegerZero, trigger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogRoleVisible: false,
      selectedRole: '',
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        role: '选择角色'
      },
      dialogFormVisibleAdd: false,
      postDataPramas: {},
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },
  created() {
    this.get_table_data()
  },
  methods: {
    deptenter() {
      this.$nextTick(() => {
        this.$refs['remark'].focus()
      })
    },
    get_table_data() {
      this.listLoading = true
      GetDataByNames(this.send_select_list).then(response => {
        this.rolelist = response.data.getRoleall.list
        this.emplist = response.data.getEmpall.list
        GetDataByName(this.getdataListParm).then(response => {
          this.list = response.data.list
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 0.5 * 1000)
        })
      })
    },
    handleFilter() {
      this.listLoading = true
      this.getdataListParm.offset = 1
      this.get_table_data()
    },
    resetRequestParam() {
      this.dataform.username = ''
      this.dataform.fullname = ''
      this.dataform.empid = ''
      this.dataform.id = ''
      this.dataform.empname = ''
      this.dataform.position = ''
      this.dataform.sort = '0'
      this.dataform.enable = 1
      this.dataform.selectedRole = ''
    },
    form_add() {
      this.resetRequestParam()
      this.dialogStatus = 'create'
      this.dialogFormVisibleAdd = true
    },
    add_dialog_save() {
      var role_Array = []
      for (let i = 0; i < this.dataform.selectedRole.length; i++) {
        var role_obj = {}
        this.$set(role_obj, 'role_id', this.dataform.selectedRole[i])
        role_Array.push(role_obj)
      }
      this.dataform.selectedRole = role_Array
      console.log(this.dataform)
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataform.selectedRole.length <= 0) {
            this.$message({ type: 'warning', message: '请检查角色是否未填写', duration: 2000 })
            return false
          } else {
            this.postDataPramas.common = { 'returnmap': '0' }
            this.postDataPramas.data = []
            this.postDataPramas.data[0] = {              'name': 'createUser', 'type': 'e', 'parammaps': {
                username: this.dataform.username,
                empid: this.dataform.empid,
                sort: '0',
                enable: this.dataform.enable
              }            }
            this.postDataPramas.data[1] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.dataform.selectedRole } }
            this.postDataPramas.data[1].children = []
            this.postDataPramas.data[1].children[0] = {              'name': 'insertUserRole', 'type': 'e', 'parammaps': {
                user_id: '@createUser.LastInsertId',
                role_id: '@insertSpotList.role_id'
              }            }
            ExecDataByConfig(this.postDataPramas).then(response => {
              console.log('新增保存发送参数', this.postDataPramas)
              if (response.msg === 'fail') {
                var username = new RegExp('username')
                if (username.test(response.data)) {
                  this.$notify({
                    title: '',
                    message: '该用户名称已存在',
                    type: 'warning',
                    duration: 2000
                  })
                } else {
                  this.$notify({
                    title: '失败',
                    message: response.data,
                    type: 'warning',
                    duration: 2000
                  })
                }
              } else {
                this.dialogFormVisibleAdd = false
                this.get_table_data()
                this.$notify({
                  title: '',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000
                })
              }
            })
          }
        }
      })
    },
    add_dialog_save_again() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'createUser'
          this.requestParam.params = []
          this.requestParam.params[0] = this.dataform.username
          this.requestParam.params[1] = this.dataform.empid
          this.requestParam.params[2] = this.dataform.sort
          this.requestParam.params[3] = this.dataform.enable
          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.get_table_data()
              this.resetRequestParam()
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            } else {
              var username = new RegExp('username')
              if (username.test(response.data)) {
                this.$notify({
                  title: '',
                  message: '该用户名称已存在',
                  type: 'warning',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '失败',
                  message: response.data,
                  type: 'warning',
                  duration: 2000
                })
              }
            }
          })
        }
      })
    },
    handleRole(row) {
      this.requestParam.name = 'getRoleByUser'
      this.requestParam.params = []
      this.requestParam.params[0] = row.id
      this.requestParam.pagecount = 0
      this.requestParam.returntype = 'list'
      this.dataform.id = row.id
      this.dialogRoleVisible = true
      GetDataByName(this.requestParam).then(response => {
        this.selectedRole = response.data.lists.role_id
      })
    },
    updateRole() {
      this.form_edit_saveRelationParam.name = 'user_role'
      this.form_edit_saveRelationParam.dataname = 'user_id'
      this.form_edit_saveRelationParam.datavalue = this.dataform.id
      this.form_edit_saveRelationParam.valuename = 'role_id'
      this.form_edit_saveRelationParam.values = this.selectedRole

      form_edit_saveRelation(this.form_edit_saveRelationParam).then(() => {
        this.dialogRoleVisible = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
        this.get_table_data()
      })
    },
    form_edit(row) {
      this.dataform.id = row.id
      this.dataform.username = row.username
      this.dataform.empid = row.empid
      this.dataform.sort = row.sort
      this.dataform.enable = row.enable
      this.dataform.empname = row.empname
      this.dataform.position = row.position
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    form_edit_save() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'updateUser'
          this.requestParam.params = []
          this.requestParam.params[0] = this.dataform.username
          this.requestParam.params[1] = this.dataform.empid
          this.requestParam.params[2] = this.dataform.sort
          this.requestParam.params[3] = this.dataform.enable
          this.requestParam.params[4] = this.dataform.id
          PostDataByName(this.requestParam).then(() => {
            this.$nextTick(() => {
              this.get_table_data()
              this.resetRequestParam()
            })
            this.dialogFormVisible = false
          })
        }
      })
    },
    change_enable(index, row) {

      console.log(row)
      this.requestParam.name = 'updateUser'
      this.requestParam.params = []


      this.requestParam.params[0] = row.username
      this.requestParam.params[1] = row.empid
      this.requestParam.params[2] = row.sort


      // if(row.enable == 1){
      //   this.requestParam.params[3] = 0
      // } else {
      //   this.requestParam.params[3] = 1
      // }

      this.requestParam.params[4] = row.id
      PostDataByName(this.requestParam).then(() => {
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleDelete(row) {
      MessageBox.confirm('确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deleteUser'
        this.requestParam.params = []
        this.requestParam.params[0] = row.id
        PostDataByName(this.requestParam).then(() => {
          this.get_table_data()
          this.resetRequestParam()
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },

    formNameSearch(queryString, cb) {
      this.requestFilterParams.name = 'userSolr'
      this.requestFilterParams.parammaps['pastureId'] = this.$store.state.user.pastureid
      this.requestFilterParams.parammaps['empname'] = queryString
      GetDataByName(this.requestFilterParams).then(response => {
        cb(response.data.list)
      })
    },
    handleformNameSelect(item) {
      this.dataform.username = item.empCode
      this.dataform.empid = item.id
      this.$set(this.dataform, 'empname', item.empname)
      this.$set(this.dataform, 'position', item.position)
      // this.dataform.empname = item.empname
      // this.dataform.position = item.position
    }
  }
}
</script>
