<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form label-width="100px">
        <el-col :span="4">
          <el-form-item label="关键字搜索">
            <el-input v-model="KEYWORDS" placeholder="请输入关键字搜索"/>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="用户角色">
            <el-select v-model="ROLE_ID" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in roleList" :key="item.role_ID" :label="item.role_NAME" :value="item.role_ID" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="10px">
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
              搜索
            </el-button>
            <el-button v-waves class="filter-item" type="success" icon="el-icon-refresh" @click="goKeyReset">
              重置
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item style="text-align: right" label-width="0px">
            <el-button v-waves class="filter-item" type="info" icon="el-icon-bottom-right" size="mini" plain @click="importExcel">
              导入
            </el-button>
          </el-form-item>
        </el-col>

      </el-form>
    </div>
    <el-table ref="multipleTable" :data="varList" :header-cell-style="{'font-weight': 'bold','color': '#000'}" tooltip-effect="dark" border fit highlight-current-row>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="USERNAME" label="用户名" />
      <el-table-column prop="NAME" label="姓名" />
      <el-table-column prop="SEX_NAME" label="性别" />
      <!-- <el-table-column prop="DEPARTMENT_NAME" label="部门" /> -->
      <!-- <el-table-column prop="POST_NAME" label="岗位" /> -->
      <el-table-column prop="ROLE_NAME" label="用户角色" />
      <el-table-column prop="PHONE" label="手机号" />
      <el-table-column prop="EMAIL" label="邮箱" />
      <el-table-column prop="AGENCY_NAME" label="代理商" >
        <template slot-scope="{row}">
          <template v-if="row.AGENCY_NAME">
            <div>{{ row.AGENCY_NAME }}</div>
          </template>
          <template v-else>
            <div>平台</div>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="LAST_LOGIN" label="最近登录" />
      <el-table-column prop="IP" label="上次登录IP" />
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="{row}">
          <el-button v-show="edit" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(row)">编辑</el-button>
          <el-button v-show="edit" type="success" icon="el-icon-refresh" size="mini" @click="resetPwd(row.USER_ID,row.USERNAME)">重置密码</el-button>
          <el-button v-show="del" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.USER_ID,row.USERNAME)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <template>
          <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          <el-button v-show="del" type="danger" icon="el-icon-delete" plain @click="makeAll('0')">删除</el-button>
        </template>
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog :visible.sync="dialogFormEdit" :title="dialogType==='editUser'?'修改':'新增'" width="600px">
      <el-form ref="form" :rules="rules" :model="pd" label-width="150px" style="width: 500px;">
        <el-form-item label="用户角色" prop="ROLE_ID">
          <el-select v-model="pd.ROLE_ID" clearable placeholder="请选择用户角色" style="width: 100%">
            <el-option v-for="item in roleList" :key="item.role_ID" :label="item.role_NAME" :value="item.role_ID" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogType != 'editUser'" label="用户名" prop="USERNAME">
          <el-input v-model="pd.USERNAME" placeholder="这里输入用户名..." />
        </el-form-item>
        <el-form-item v-if="dialogType == 'editUser'" label="用户名" >
          <el-input v-model="pd.USERNAME" disabled placeholder="这里输入用户名..." />
        </el-form-item>
        <el-form-item label="姓名" prop="NAME">
          <el-input v-model="pd.NAME" placeholder="这里输入姓名..." />
        </el-form-item>
        <!--        <el-form-item label="代理区域" prop="POSSESSION">-->
        <!--          <el-cascader id="POSSESSION" ref="POSSESSION" v-model="pd.POSSESSION" :options="areaList" :props="areaProps" placeholder="请选择省市县" style="width: 100%"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="性别" prop="SEX">
          <el-select v-model="pd.SEX" placeholder="请选择">
            <el-option v-for="item in uesrInfoDic.xingbieList" :key="item.DICTIONARIES_ID" :label="item.NAME" :value="item.DICTIONARIES_ID"/>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="PHONE">
          <el-input v-model="pd.PHONE" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="pd.EMAIL" placeholder="这里输入备注邮箱..." />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="pd.BZ" type="textarea" placeholder="这里输入备注说明..." />
        </el-form-item>
        <!--        <el-divider content-position="left">创建数量</el-divider>-->
        <!--        <el-form-item v-for="(data,index) in roleGroupList" :label="data.ROLE_NAME" :key="index">-->
        <!--          <el-input-->
        <!--            v-model="data.NUMBER"-->
        <!--            type="number"-->
        <!--            placeholder="这里输入数量..."-->
        <!--            oninput="value=value.replace(/[^\d]/g,'')"-->
        <!--            @wheel.native.prevent="stopScroll($event)" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="创建数量">-->
        <!--          <el-col v-for="(data,index) in levelList" :key="index" :span="24">-->
        <!--            <el-form-item :label="data.NAME">-->
        <!--              <el-input v-model="data.NUM" placeholder="这里输入备注说明..." />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->

        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormDaoru" title="导入" width="800px">
      <template>
        <div class="app-container">
          <el-form ref="form" :model="daoruFrom" label-width="110px" class="in-uploader">
            <el-form-item label="上传附件" prop="FIELDS">
              <div class="uploader">
                <el-input v-model="daoruFrom.FFILEName" :disabled="true" />
                <el-upload :show-file-list="false" :before-upload="beforeFileUpload" class="avatar-uploader" action="" accept=".xls">
                  <el-button type="primary" icon="el-icon-upload" style="margin-left:10px">上传附件</el-button>
                </el-upload>
                <el-button v-waves type="success" icon="el-icon-right" style="margin-left:10px;width:150px" @click="getExcelModel">
                  导出模板
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormDaoru = false">取 消</el-button>
        <el-button type="primary" @click="goUpload">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import { Message } from 'element-ui'
import { upload } from '@/utils/upload'

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    var hasUser = (rule, value, callback) => {
      requestFN(
        '/user/hasUser',
        {
          USERNAME: value,
          tm: new Date().getTime()
        }
      ).then((data) => {
        if (data.result == 'success') {
          callback()
        } else {
          // console.info('用户名重复')
          callback(new Error('用户名重复'))
        }
      }).catch((e) => {

      })
    }
    return {
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      varList: [],
      roleGroupList: [

      ],
      KEYWORDS: '',
      dialogFormDaoru: false,
      dialogFormEdit: false,
      dialogType: 'add',
      uesrInfoDic: {
        xingbieList: []
      },
      daoruFrom: {
        FFILE: '',
        FFILEName: ''
      },
      rules: {
        ROLE_ID: [
          { required: true, message: '角色不能为空', trigger: 'blur' }
        ],
        USERNAME: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9\x21-\x7e]{6,20}$/,
            message: '用户名由6-20个字符组成，不可输入中文' },
          // { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
          { validator: hasUser, trigger: 'blur' }
        ],
        NAME: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        POSSESSION: [
          { required: true, message: '代理区域不能为空', trigger: 'blur' }
        ],
        SEX: [
          { required: true, message: '性别不能为空', trigger: 'blur' }
        ],
        PHONE: [
          { required: true, message: '电话不能为空', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确的手机号码'
          }
        ]

      },
      pd: {
        POSSESSION: '',
        AGENTPROVINCE: '',
        AGENTCITY: '',
        AGENTCOUNTY: '',
        AGENTVILLAGE: '',
        AGENTSTREET: ''
      },
      areaList: [], // 代理区域
      ROLE_ID: '',

      areaProps: {
        lazy: true,
        lazyLoad: this.lazyLoad,
        value: 'numValue',
        id: 'id',
        label: 'label',
        children: 'children',
        checkStrictly: true
      },
      roleList: [],
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      fromExcel: false, // 从excel导入权限
      toExcel: false,	// 导出到excel权限
      add: false,		// 新增按钮
      del: false,		// 删除按钮
      edit: false,	// 修改按钮
      hasUserRet: false
    }
  },
  created() {
    this.getList()
    this.hasButton()
    if (!JSON.parse(sessionStorage.getItem('user')).AGENCY_MANAGEMENT_ID) {
      this.getmRoleList()
    } else {
      this.getroleList('eee570eff038464cbdfac5f8579bbace')
    }
    this.getDicListByPID('21501808bbc344d593fbf9ccfe6c4531', '', 'xingbieList')
  },
  methods: {
    // 加载级联的方法
    lazyLoad(nodeValue, resolve) {
      if (nodeValue.data && (!nodeValue.children || nodeValue.children.length == 0)) {
        this.getDictByDicId(nodeValue.data.id).then(data => {
          resolve(data)
        })
      } else {
        resolve(null)
      }
    },
    // 禁止el-input type=number 时。滑轮控制数字大小
    stopScroll(evt) {
      evt = evt || window.event
      if (evt.preventDefault) {
        // Firefox
        evt.preventDefault()
        evt.stopPropagation()
      } else {
        // IE
        evt.cancelBubble = true
        evt.returnValue = false
      }
      return false
    },
    beforeFileUpload(file) {
      const types = ['xls']
      // const isfile = types.includes(file.type)
      const fileSuffix = file.name.slice(file.name.lastIndexOf('.') + 1)
      const isfile = types.includes(fileSuffix.toLowerCase())
      if (!isfile) {
        this.$message.error('上传附件只能是 xls 格式!')
        return false
      } else {
        this.daoruFrom.FFILE = file
        this.daoruFrom.FFILEName = file.name
        this.$forceUpdate()
        return true
      }
    },
    getExcelModel() {
      this.$confirm('确定要下载excel模板吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.open(config.templatefileUrl + 'template/userAdminExcelTemplate.xls')
      }).catch(() => {
        this.listLoading = false
      })
      this.listLoading = false
    },
    importExcel() {
      this.dialogFormDaoru = true
      this.daoruFrom.FFILE = ''
      this.daoruFrom.FFILEName = ''
    },
    goUpload() {
      const formData = new FormData()
      Object.keys(this.daoruFrom).map(key => {
        formData.append(key, this.daoruFrom[key])
      })
      upload(
        '/user/readExcel2',
        formData
      ).then((data) => {
        if (data.msg) {
          Message({
            message: data.msg,
            type: 'success',
            duration: 5 * 1000
          })
        }
        this.getList()
        this.dialogFormDaoru = false
      }).catch((e) => {
        this.listLoading = false
      })
    },
    resetPwd(id, username) {
      this.$confirm('是否重置密码为Aa@123456?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/user/resetPwd',
          {
            USER_ID: id,
            USERNAME: username
          }
        ).then(() => {
          this.$message({
            message: '重置成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    getList() {
      this.listLoading = true
      requestFN(
        '/user/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          ROLE_ID: this.ROLE_ID,
          PARENT_ID: 'eee570eff038464cbdfac5f8579bbace'
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.userList
        console.log(this.varList)
        this.total = data.page.totalResult
      })
        .catch((e) => {
          this.listLoading = false
        })
    },
    getroleList(ROLE_ID) {
      requestFN(
        '/role/getRoleList',
        {
          ROLE_ID: ROLE_ID
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.roleList = data.roleList
        }
      }).catch((e) => {

      })
    },
    getmRoleList(ROLE_ID) {
      requestFN(
        '/role/getmRoleList',
        {
          ROLE_ID: ROLE_ID
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.roleList = data.roleList
        }
      }).catch((e) => {

      })
    },
    getDicListByPID(pId, id, listName) {
      var url = '/dictionaries/getLevels'
      requestFN(url,
        {
          DICTIONARIES_ID: pId
        }
      ).then((data) => {
        this.uesrInfoDic[listName] = data.list
      }).catch((e) => {

      })
    },
    goEdit(USER_ID) {
      requestFN(
        '/user/goEditUser',
        {
          USER_ID: USER_ID
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.roleGroupList = data.agentNumList
          this.pd = Object.assign({}, data.pd)
          if (data.pd.posOption && data.pd.posOption.length > 0) {
            this.areaList = data.pd.posOption
          }
        }
      }).catch((e) => {

      })
    },
    handleAdd() {
      // this.getDictByDicId('e725d2a91b8248f4b8f49889038df7de').then(data => {
      //   this.areaList = data
      // })
      this.$refs.form && this.$refs.form.clearValidate()
      this.getGroupList()
      this.dialogFormEdit = true
      this.pd = {}
      // this.getroleList()
      this.dialogType = 'saveUser'
    },
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          requestFN(
            '/user/' + this.dialogType,
            {
              USER_ID: this.pd.USER_ID,
              ROLE_ID: this.pd.ROLE_ID,
              USERNAME: this.pd.USERNAME,
              NAME: this.pd.NAME,
              PHONE: this.pd.PHONE,
              EMAIL: this.pd.EMAIL,
              BZ: this.pd.BZ,
              SEX: this.pd.SEX,
              // ROLEGROUPLIST: JSON.stringify(this.roleGroupList),
              // AGENTLEVEL: this.pd.AGENTLEVEL,
              // AGENTPROVINCE: this.pd.AGENTPROVINCE,
              // AGENTCITY: this.pd.AGENTCITY,
              // AGENTCOUNTY: this.pd.AGENTCOUNTY,
              // AGENTVILLAGE: this.pd.AGENTVILLAGE,
              // AGENTSTREET: this.pd.AGENTSTREET,
              // ISAGENT: '1',
              tm: new Date().getTime()
            }
          ).then((data) => {
            this.listLoading = false
            this.dialogFormEdit = false
            this.varList = []
            this.listQuery.page = 1
            this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    handleDelete(id, name) {
      this.$confirm('确定要删除[' + name + ']吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/user/deleteUser',
          {
            USER_ID: id
          }
        ).then((data) => {
          if (data.result == 'success') {
            this.listLoading = false
            this.getList()
          }
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    makeAll(msg) {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要删除的项...',
          type: 'error'
        })
        return false
      }
      const ids = _selectData.map((item, index) => {
        return item.USER_ID
      }).join(',')
      var tishi = ''
      if (msg == '0') {
        tishi = '确定要删除选中的数据吗?'
      } else if (msg == '1') {
        tishi = '确定要给选中的用户发送站内信吗?'
      } else {
        this.$message({
          message: '请选择操作类型...',
          type: 'error'
        })
        return false
      }
      this.$confirm(tishi, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (msg == '0') {
          this.listLoading = true
          requestFN(
            '/user/deleteAllUser',
            {
              USER_IDS: ids
            }
          ).then(() => {
            this.listLoading = false
            this.varList = []
            this.listQuery.page = 1
            this.$refs.multipleTable.clearSelection()
            this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        }
      }).catch(() => {
      })
    },
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    // 重置
    goKeyReset() {
      this.KEYWORDS = ''
      this.ROLE_ID = ''
      this.getQuery()
    },
    handleEdit(row) {
      this.getDictByDicId('e725d2a91b8248f4b8f49889038df7de').then(data => {
        this.areaList = data
      })
      // this.getGroupList()
      if (!row.AGENCY_NAME) {
        this.getmRoleList()
      } else {
        this.getroleList('eee570eff038464cbdfac5f8579bbace')
      }
      this.goEdit(row.USER_ID)
      this.dialogType = 'editUser'
      this.dialogFormEdit = true
    },
    getGroupList() {
      requestFN(
        '/role/getGroupList',
        {
        }
      ).then((data) => {
        this.roleGroupList = []
        data.groupList.forEach((a) => {
          if (a.ROLE_ID != '1') {
            this.roleGroupList.push(a)
          }
        })
        // this.roleGroupList = data.groupList
      }).catch((e) => {
      })
    },

    // 获取数据字典数据
    getDictByDicId(dicId) {
      var dicListVal = []
      return new Promise((resolve) => {
        let id = ''
        if (!dicId) {
          id = '0'
        } else {
          id = dicId
        }
        requestFN(
          '/dictionaries/getLevelsAndSCount',
          {
            DICTIONARIES_ID: id
          }
        ).then((data) => {
          if (data.list.length > 0) {
            dicListVal = data.list.map((e) => {
              if (e.zcount == '0') {
                return { value: e.DICTIONARIES_ID.toString(), numValue: e.BIANMA.toString(), label: e.NAME, id: e.DICTIONARIES_ID, leaf: true }
              } else {
                return { value: e.DICTIONARIES_ID.toString(), numValue: e.BIANMA.toString(), label: e.NAME, id: e.DICTIONARIES_ID, children: [], leaf: false }
              }
            })
          } else {
            dicListVal = undefined
          }
          return resolve(dicListVal)
        }).catch((e) => {
        })
      })
    },
    hasButton() {
      var keys = 'user:add,user:del,user:edit,fhSms,email,fromExcel,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys, tm: new Date().getTime()
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.add = data.userfhadminadd	// 增
          this.del = data.userfhadmindel	// 删
          this.edit = data.userfhadminedit	// 改
          this.fromExcel = data.fromExcel	// 从excel导入权限
          this.toExcel = data.toExcel		// 导出到excel权限
        } else if (data.result == 'exception') {
          // showException('按钮权限', data.exception)// 显示异常
          console.info('按钮权限:', data.exception)
        }
      })
        .catch((e) => {
          this.listLoading = false
        })
    }
  }
}
</script>

// 禁用el-input  type= number 时。右侧出现的可以点击控制数字大小的上下箭头。为了只输入正整数服务
<style scoped>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
  .uploader{
    display: flex;
  }
</style>
