<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-row mb-10">
        <div class="filter-group ">
          <div class="filter-lable">
            用户名称：
          </div>
          <div class="filter-width">
            <el-input v-model="KEYWORDS" placeholder="请输入关键字" class="filter-item" />
          </div>
        </div>
        <div class="filter-group">
          <div class="filter-lable">
            属地：
          </div>
          <div class="filter-width">
            <el-cascader ref="POSSESSION" v-model="POSSESSION" :options="areaList" :props="areaProps" placeholder="请选择省市县" style="width: 100%"/>
          </div>
        </div>
        <div class="filter-group">
          <div class="filter-lable">
            用户级别：
          </div>
          <div class="filter-width">
            <el-select v-model="LEVEL" placeholder="请选择" label="属地">
              <el-option v-for="item in UserLevelList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
        </div>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
          搜索
        </el-button>
        <el-button class="filter-item" type="success" icon="el-icon-refresh" @click="goKeyReset">
          重置
        </el-button>
      </div>
    </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 :formatter="statusFormat" prop="USERLEVEL" label="用户级别"/>
      <el-table-column prop="ROLE_NAME" label="属地" >
        <template slot-scope="{row}">
          {{ row.CITY_NAME }} {{ row.COUNTRY_NAME?('-- '+ row.COUNTRY_NAME ):'' }}
          {{ row.VILLAGE_NAME?(' -- '+row.VILLAGE_NAME):'' }} {{ row.STREET_NAME?(' -- '+row.STREET_NAME):'' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <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="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="110px" style="width: 500px;">
        <el-form-item v-if="false" :disabled="dialogType == 'editUser'" label="角色" prop="ROLE_ID">
          <el-select v-model="pd.ROLE_ID" :disabled="dialogType == 'editUser'" clearable placeholder="请选择角色">
            <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 label="用户名" prop="NAME">
          <el-input v-model="pd.NAME" placeholder="这里输入姓名..." />
        </el-form-item>
        <el-form-item label="性别" prop="SEX">
          <el-select v-model="pd.SEX" clearable placeholder="请选择角色">
            <el-option v-for="item in sexList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号" >
          <el-input v-model="pd.USERNAME" placeholder="请输入账号..." />
        </el-form-item>
        <el-form-item label="密码" >
          <el-input v-model="pd.PASSWORD" placeholder="默认：123456" />
        </el-form-item>
        <el-form-item label="所属区域" prop="POSSESSION">
          <el-cascader id="POSSESSION" ref="POSSESSION" v-model="pd.POSSESSION" :options="areaList" :props="areaProps" :placeholder="POSSESSION_NAME" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="用户级别" >
          <el-select v-model="pd.USERLEVEL" placeholder="请选择" label="属地">
            <el-option v-for="item in UserLevelList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="false" label="备注">
          <el-input v-model="pd.BZ" type="textarea" placeholder="这里输入备注说明..." />
        </el-form-item>
        <el-divider v-if="false" 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>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</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

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

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

      ],
      KEYWORDS: '',
      dialogFormEdit: false,
      dialogType: 'add',
      rules: {
        ROLE_ID: [
          { required: true, message: '角色不能为空', trigger: 'blur' }
        ],
        USERNAME: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', 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' }
        ]

      },
      pd: {
        POSSESSION: '',
        AGENTPROVINCE: '',
        AGENTCITY: '',
        AGENTCOUNTRY: '',
        AGENTVILLAGE: '',
        AGENTSTREET: '',
        SEX: null,
        USERLEVEL: null
      },
      sexList: [
        { label: '男', value: '1' },
        { label: '女', value: '2' }
      ],
      areaList: [], // 代理区域
      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,
      POSSESSION: null,
      LEVEL: null,
      addLEVEL: null,
      UserLevelList: [
        { label: '省级', value: '1' },
        { label: '市级', value: '2' },
        { label: '区县级', value: '3' },
        { label: '乡镇级', value: '4' }
      ],
      POSSESSION_NAME: ''
    }
  },
  created() {
    this.getList()
    this.hasButton()
    this.getGroupList()
    this.getroleList()
    this.getAreaDict('e725d2a91b8248f4b8f49889038df7de', '0').then(data => {
      this.areaList = data
    })
  },
  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
    },
    getList() {
      this.listLoading = true
      requestFN(
        '/user2/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.userList
        this.total = data.page.totalResult
      })
        .catch((e) => {
          this.listLoading = false
        })
    },
    getroleList(USER_ID) {
      requestFN(
        '/role/getRoleList',
        {
          USER_ID: USER_ID
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.roleList = data.roleList
        }
      }).catch((e) => {

      })
    },

    goEdit(USER_ID) {
      requestFN(
        '/user2/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.getGroupList()
      this.dialogFormEdit = true
      this.pd = {}
      // this.getroleList()
      this.POSSESSION_NAME = '请选择省市县'
      this.dialogType = 'saveUser'
    },
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          if (this.pd.POSSESSION && this.pd.POSSESSION.length > 0) {
            this.pd.USER_PROVINCE = this.pd.POSSESSION[0] || ''
            this.pd.USER_CITY = this.pd.POSSESSION[1] || ''
            this.pd.USER_COUNTRY = this.pd.POSSESSION[2] || ''
            this.pd.USER_VILLAGE = this.pd.POSSESSION[3] || ''
            this.pd.USER_STREET = this.pd.POSSESSION[4] || ''
          }
          requestFN(
            '/user2/' + this.dialogType,
            {
              USER_ID: this.pd.USER_ID,
              USERNAME: this.pd.USERNAME,
              PASSWORD: this.PASSWORD,
              NAME: this.pd.NAME,
              AGENTLEVEL: this.pd.USERLEVEL,
              USER_PROVINCE: this.pd.USER_PROVINCE,
              USER_CITY: this.pd.USER_CITY,
              USER_COUNTRY: this.pd.USER_COUNTRY,
              USER_VILLAGE: this.pd.USER_VILLAGE,
              USER_STREET: this.pd.USER_STREET,
              USERLEVEL: this.pd.USERLEVEL,
              SEX: this.pd.SEX,
              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(
          '/user2/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(
            '/user2/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()
    },
    handleEdit(row) {
      this.getDictByDicId('e725d2a91b8248f4b8f49889038df7de').then(data => {
        this.areaList = data
      })
      if (row.USER_PROVINCE || row.USER_PROVINCE || row.USER_COUNTRY || row.USER_VILLAGE || row.USER_STREET) {
        this.POSSESSION_NAME = ''
        if (row.PROVINCE_NAME) {
          this.POSSESSION_NAME += row.PROVINCE_NAME
        }
        if (row.CITY_NAME) {
          this.POSSESSION_NAME += '/' + row.CITY_NAME
        }
        if (row.COUNTRY_NAME) {
          this.POSSESSION_NAME += '/' + row.COUNTRY_NAME
        }
        if (row.VILLAGE_NAME) {
          this.POSSESSION_NAME += '/' + row.VILLAGE_NAME
        }
        if (row.STREET_NAME) {
          this.POSSESSION_NAME += '/' + row.STREET_NAME
        }
      } else {
        this.POSSESSION_NAME = '请选择省市县'
      }
      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
        })
    },
    getAreaDict(dicId, level, disabled) {
      var dicListVal = []
      return new Promise((resolve) => {
        let id = ''
        if (!dicId) {
          id = '0'
        } else {
          id = dicId
        }
        requestFN(
          '/dictionaries/getAreaDict',
          {
            DICTIONARIES_ID: id,
            LEVEL: level,
            DISABLED: disabled

          }
        ).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, disabled: e.DISABLED, level: e.LEVEL }
              } else {
                return { value: e.DICTIONARIES_ID.toString(), numValue: e.BIANMA.toString(), label: e.NAME, id: e.DICTIONARIES_ID, children: [], leaf: false, disabled: e.DISABLED, level: e.LEVEL }
              }
            })
          } else {
            dicListVal = undefined
          }
          return resolve(dicListVal)
        }).catch((e) => {
        })
      })
    },
    statusFormat(row, column) {
      if (row.USERLEVEL === '1') {
        return '省级'
      } else if (row.USERLEVEL === '2') {
        return '市级'
      } else if (row.USERLEVEL === '3') {
        return '区县级'
      } else if (row.USERLEVEL === '4') {
        return '乡镇级'
      } else {
        return row.USERLEVEL
      }
    },
    goKeyReset() {
      this.POSSESSION = []
      this.KEYWORDS = ''
      this.LEVEL = ''
    }
  }
}
</script>

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