<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">

  <div class="app-container">
    <div>
      <el-card>
        <div slot="header" class="clearfix">
          <b><span>用户管理</span></b>
        </div>

        <div class="filter-container">
          <el-button type="primary" size="small" style="round-clip: 10px" @click="insertEvent"
                     :loading="loadButton">添加
          </el-button>
        </div>
        <div style="padding-top: 10px">
          <vxe-table
            ref="xTable"
            border
            export-config
            keep-source
            auto-resize
            resizable
            :edit-rules="rules"
            :loading="loading"
            :data="tableData"
            v-show="showTable"
            show-overflow
            highlight-current-row
            align="center"
          >
            <!--:edit-config="{trigger: 'manual', mode: 'row',autoClear:false,showStatus: true,icon:'none'}"-->
            <vxe-table-column title="用户基本信息" align="center">
              <vxe-table-column
                field="userName"
                title="用户名"
                width="7%"
                align="center"
              />
              <!--:edit-render="{name: '$input', attrs: {type: 'text'}}"-->
              <vxe-table-column
                field="passWord"
                title="密码"
                width="12%"
                align="center"
              />
              <!--:edit-render="{name: '$input', attrs: {type: 'text'}}"-->
              <vxe-table-column
                field="name"
                title="姓名"
                width="7%"
                align="center"
              />
              <!--:edit-render="{name: '$input', attrs: {type: 'text'}}"-->
              <vxe-table-column
                field="status"
                title="状态"
                width="8%"
                align="center"
                :formatter="formatStatus"
              />
              <!--:edit-render="{name: '$select', options: userStatus }"-->
              <vxe-table-column title="操作" width="15%" align="center">
                <template v-slot="{ row }">
                  <!--<template v-if="$refs.xTable.isActiveByRow(row)">-->
                  <!--<el-button-->
                  <!--type="success"-->
                  <!--style="padding: 3px 4px 3px 4px;margin: 2px;"-->
                  <!--size="mini"-->
                  <!--icon="el-icon-edit"-->
                  <!--@click="editSave(row)"-->
                  <!--&gt;保存-->
                  <!--</el-button>-->
                  <!--<el-button-->
                  <!--class="cancel-btn"-->
                  <!--icon="el-icon-refresh"-->
                  <!--type="warning"-->
                  <!--style="padding: 3px 4px 3px 4px;margin: 2px;"-->
                  <!--size="mini"-->
                  <!--@click="cancelRowEvent(row)"-->
                  <!--&gt;取消-->
                  <!--</el-button>-->
                  <!--</template>-->
                  <!--<template v-else>-->
                  <el-button
                    :loading="loadButton"
                    type="primary"
                    style="padding: 3px 4px 3px 4px;margin: 2px;"
                    size="mini "
                    icon="el-icon-edit"
                    @click="editRowEvent(row)"
                  >编辑
                  </el-button>
                  <el-button
                    :loading="loadButton"
                    type="danger"
                    style="padding: 3px 4px 3px 4px;margin: 2px;"
                    size="mini "
                    icon="el-icon-delete"
                    @click="deleteRowEvent(row)"
                  >删除
                  </el-button>
                  <!--</template>-->
                </template>
              </vxe-table-column>
            </vxe-table-column>
          </vxe-table>
          <vxe-modal
            ref="xModal"
            v-model="showEdit"
            :title="selectRow ? '编辑&保存' : '新增&保存'"
            width="800"
            resize
            destroy-on-close
          >
            <el-form
              :model="formData"
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
              title-align="center"
              title-width="100"
            >
              <el-form-item label="用户名" prop="userName" class="formItem" >
                <el-input v-model="formData.userName" placeholder="填写用户名" clearable></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="passWord" class="formItem" >
                <el-input v-model="formData.passWord" placeholder="填写密码" clearable></el-input>
              </el-form-item>
              <el-form-item label="姓名" prop="name" class="formItem" >
                <el-input v-model="formData.name" placeholder="填写姓名" clearable></el-input>
              </el-form-item>
              <el-form-item label="状态" prop="status" class="formItem" >
                <el-select v-model="formData.status" placeholder="请选择状态" size="medium">
                  <el-option
                    v-for="item in userStatus"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="配置菜单" prop="menu" class="formItem" >
                  <el-cascader
                    v-model="formData.menu"
                    :options="options"
                    :props="props"
                    collapse-tags
                  />
              </el-form-item>
              <el-form-item align="center" span="24">
                <el-button status="primary" @click="editSave">保存</el-button>
                <el-button @click="cancelRowEvent">取消</el-button>
              </el-form-item>
            </el-form>
          </vxe-modal>
        </div>
      </el-card>
    </div>

    <!-- 删除提示框 -->
    <el-dialog :visible.sync="delVisible" title="提示" width="300px" center>
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteCancel()">取 消</el-button>
        <el-button type="primary" @click="deleteInfo()">确 定</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>

  export default {
    data() {
      let strTopShiftReg = /(\~(?=\!)|\!(?=\@)|\@(?=\#)|\#(?=\$)|\$(?=\%)|\%(?=\^)|\^(?=\&)|\&(?=\*)|\*(?=\()|\((?=\))|\)(?=\_)|\_(?=\+)|\+(?=\~)){3}/
      let strTopResverShiftReg = /(\+(?=\_)|\_(?=\))|\)(?=\()|\((?=\*)|\*(?=\&)|\&(?=\^)|\^(?=\%)|\%(?=\$)|\$(?=\#)|\#(?=\@)|\@(?=\!)|\!(?=\~)|\~(?=\+)){3}/
      //字母连续规则
      let strReg = /(a(?=b)|b(?=c)|c(?=d)|d(?=e)|e(?=f)|f(?=g)|g(?=h)|h(?=i)|i(?=j)|j(?=k)|k(?=l)|l(?=m)|m(?=n)|n(?=o)|o(?=p)|p(?=q)|q(?=r)|r(?=s)|s(?=t)|t(?=u)|u(?=v)|v(?=w)|w(?=x)|x(?=y)|y(?=z)|z(?=a)){3}[a-z]/i
      let strResverReg = /(a(?=z)|z(?=y)|y(?=x)|x(?=w)|w(?=v)|v(?=u)|u(?=t)|t(?=s)|s(?=r)|r(?=q)|q(?=p)|p(?=o)|o(?=n)|n(?=m)|m(?=l)|l(?=k)|k(?=j)|j(?=i)|i(?=h)|h(?=g)|g(?=f)|f(?=e)|e(?=d)|d(?=c)|c(?=b)|b(?=a)){3}[a-z]/i
      //数字连续规则
      let numReg = /(\`(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)|0(?=\-)|\-(?=\=)|\=(?=\`)){3}/
      let numResverReg = /(\=(?=\-)|\-(?=0)|0(?=9)|9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=\`)|\`(?=\=)){3}/
      //键盘字母横向连续规则
      let keyboardHorizontalReg = /(q(?=w)|w(?=e)|e(?=r)|r(?=t)|t(?=y)|y(?=u)|u(?=i)|i(?=o)|o(?=p)|p(?=q)|a(?=s)|s(?=d)|d(?=f)|f(?=g)|g(?=h)|h(?=j)|j(?=k)|k(?=l)|l(?=a)|z(?=x)|x(?=c)|c(?=v)|v(?=b)|b(?=n)|n(?=m)|m(?=z)){3}[a-z]/i
      let keyboardHorizontalResverReg = /(p(?=o)|o(?=i)|i(?=u)|u(?=y)|y(?=t)|t(?=r)|r(?=e)|e(?=w)|w(?=q)|q(?=p)|l(?=k)|k(?=j)|j(?=h)|h(?=g)|g(?=f)|f(?=d)|d(?=s)|s(?=a)|a(?=l)|m(?=n)|n(?=b)|b(?=v)|v(?=c)|c(?=x)|x(?=z)|z(?=m)){3}[a-z]/i
      //多个相同字母、数字规则
      let sameReg = /([0-9a-zA-Z])\1{3}/
      let keyboardSlopeArr = ["1qaz", "2wsx", "3edc", "4rfv", "5tgb", "6yhn", "7ujm", "8ik,", "9ol.", "0p;/", "/;p0", ".lo9", ",ki8", "mju7", "nhy6", "bgt5", "vfr4", "cde3", "xsw2", "zaq1", "4esz", "5rdx", "6tfc", "7ygv", "8uhb", "9ijn", "0okm", "-pl,", "=[;.", ".;[=", ",lp-", "mko0", "nji9", "bhu8", "vgy7", "cft6", "xdr5", "zse4"]
      let keyboardSlopeShiftArr = ["!qaz", "@wsx", "#edc","$rfv", "%tgb", "^yhn", "&ujm", "*ik<", "(ol>", ")p:?", "?:p)", ">lo(", "<ki*", "mju&", "nhy^", "bgt%", "vfr$", "cde#", "xsw@", "zaq!", "$esz", "%rdx", "^tfc", "&ygv", "*uhb", "(ijn", ")okm", "_pl<", "+{:>", ">:{+", "<lp_", "mko)", "nji(", "bhu*", "vgy&", "cft^", "xdr%", "zse$"]
      const checkName = ({rule, value, callback}) => {
        var userName = this.formData.userName
        var s6 = this.tableDatas
        if (userName == null || userName === '') {
          return Promise.reject(new Error('请填写用户名'))
        }
        for (let i = 0; i < s6.length; i++) {
          if (this.id == '' || this.id == undefined) {
            // 新增
            if ((userName == s6[i].userName)) {
              return Promise.reject(new Error('用户名不能重复'))
            }
          } else {
            // 修改
            if (this.id != s6[i].id) {
              if ((userName == s6[i].userName)) {
                return Promise.reject(new Error('用户名不能重复'))
              }
            }
          }
        }
        return Promise.resolve()
      }
      const checkPassword = (rule, value, callback) => {
        var password = this.formData.passWord
        if (this.fileUploadNodeShowSysValue==0){
          if (sameReg.test(password)) {
            return Promise.reject(new Error('密码不能含有连续4位相同的数字或字母'))
          } else if (strResverReg.test(password)) {
            return Promise.reject(new Error('密码不能含有4位连续的字母'))
          } else if (strReg.test(password)) {
            return Promise.reject(new Error('密码不能含有4位键盘横向方向连续的字符'))
          } else if (numReg.test(password)) {
            return Promise.reject(new Error('密码不能含有4位键盘横向方向连续的字符'))
          } else if (numResverReg.test(password)) {
            return Promise.reject(new Error('密码不能含有4位连续的数字'))
          } else if (keyboardHorizontalReg.test(password)) {
            return Promise.reject(new Error('密码不能含有4位键盘横向方向连续的字母'))
          } else if (keyboardHorizontalResverReg.test(password)) {
            return Promise.reject(new Error('密码不能含有4位键盘横向方向连续的字母'))
          } else if (keyboardSlopeArr.some(v => password.toLowerCase().indexOf(v) > -1)) {
            return Promise.reject(new Error('密码不能含有4位键盘斜向方向连续的字符'))
          }else if (keyboardSlopeShiftArr.some(v => password.toLowerCase().indexOf(v) > -1)) {
            return Promise.reject(new Error('密码不能含有4位键盘斜向方向连续的字符'))
          }else if (strTopShiftReg.test(password)) {
            return Promise.reject(new Error('密码不能含有4位键盘横向方向连续的字符'))
          }else if (strTopResverShiftReg.test(password)) {
            return Promise.reject(new Error('密码不能含有4位键盘横向方向连续的字符'))
          }
        }
        return Promise.resolve()
      }
      return {
        fileUploadNodeShowSysValue: '1',
        id: '',
        tableDatas: [],
        elStations: [],
        elStation: '',
        total: 0,
        pageSize: 5,
        currentPage: 1,
        loadButton: false,
        rowId: '',
        showTable: true,
        tableData: [],
        delVisible: false,
        loading: false,
        // 是否为编辑
        isEdit: false,
        pvRotationMode: [],
        userStatus: [{value: "0", label: "正常"}, {value: "2", label: "禁用"}],
        // 表单验证规则
        rules: {
          userName: [
            {required: true, validator: checkName},
            {message: '输入过长', max: 15}
          ],
          passWord: [
            {required: true, message: '请填写密码', validator: checkPassword},
            {
              pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{7,10}/,
              message: '由8位数字、字母大小写及特殊符号组成'
            }
          ],
          name:[{required: true, message: '请填写姓名', trigger: 'blur'}],
          status:[{required: true, message: '请选择状态', trigger: 'change'}]
        },
        formData:{},
        showEdit:false,
        selectRow:false,
        props: { multiple: true },
        options:[],
        childrenOption:[]
      }
    },
    created() {
      this.getParameterBySysKey()
      this.getAll()
      this.getAllMenu()
    },

    methods: {
      getParameterBySysKey(){
        this.$axios.get('/sysParameter/sysParameterKey/FILE_UPLOAD_NODE_SHOW').then(res => {
          this.fileUploadNodeShowSysValue = res.data.sysValue
        })
      },
      getAll() {
        this.loading = true
        this.$axios.get('/sysUser/').then((res) => {
          this.tableData = res.data
          if (res.data == null) {
            this.showTable = false
          } else {
            this.showTable = true
          }
          this.loading = false
        }).catch((error) => {
          this.$message.error('获取用户信息出错' + error)
        })
      },
      getAllMenu(){
        this.$axios.get('/sysMenu').then(res => {
          // console.log(res.data)
          var data = res.data
          var option = [{value:9001,label:'后台管理', disabled: true}]
          var option9000=[{value:9000,label:'统计查询', disabled: true}]
          for(var i=0;i<data.length;i++){
            var children = []
            if(data[i].children.length>0){
              for (var j =0;j<data[i].children.length;j++) {
                if(data[i].children[j].id ==1){
                  children.push({
                    id: data[i].children[j].id,
                    fId:58,
                    value:data[i].children[j].id,
                    label: data[i].children[j].title,
                    path: data[i].children[j].path,
                    itemPath: data[i].children[j].itemPath,
                    url: data[i].children[j].url
                  })
                  this.childrenOption.push({
                    id: data[i].children[j].id,
                    fId:58,
                    value:data[i].children[j].id,
                    label: data[i].children[j].title,
                    path: data[i].children[j].path,
                    itemPath: data[i].children[j].itemPath,
                    url: data[i].children[j].url
                  })
                }else{
                  children.push({
                    id: data[i].children[j].id,
                    fId:data[i].id,
                    value:data[i].children[j].id,
                    label: data[i].children[j].title,
                    path: data[i].children[j].path,
                    itemPath: data[i].children[j].itemPath,
                    url: data[i].children[j].url
                  })
                  this.childrenOption.push({
                    id: data[i].children[j].id,
                    fId:data[i].id,
                    value:data[i].children[j].id,
                    label: data[i].children[j].title,
                    path: data[i].children[j].path,
                    itemPath: data[i].children[j].itemPath,
                    url: data[i].children[j].url
                  })
                }

              }
            }
            if(data[i].url == '9000'){
              option9000.push({
                id: data[i].id,
                value:data[i].id,
                label: data[i].title,
                itemPath: data[i].itemPath,
                url: data[i].url,
                children:children
              })
            }else{
              option.push({
                id: data[i].id,
                value:data[i].id,
                label: data[i].title,
                itemPath: data[i].itemPath,
                url: data[i].url,
                children:children
              })
            }
          }
          this.options = option.concat(option9000)
          // console.log(this.childrenOption)
        })
      },
      insertEvent(row) {
        this.id = ''
        this.showTable = true
        this.isEdit = false
        // this.loadButton = true
        this.showEdit = true
        this.selectRow = false
        this.formData={}
        // this.$refs.xTable.insert().then(({row}) => this.$refs.xTable.setActiveRow(row))
      },
      editRowEvent(row) {
        this.id = row.id
        this.isEdit = true
        // this.loadButton = true
        this.showEdit = true
        this.selectRow = true
        this.formData = row
        this.formData.menu = this.formatMenu(this.formData.menu)
        // this.$refs.xTable.setActiveRow(row)
      },
      editSave() {
        this.$refs["ruleForm"].validate(valid => {
          if (valid) {
            var menu = []
            if(this.formData.menu != null){
              for(var i=0;i<this.formData.menu.length;i++){
                if(menu.find(value=>value == this.formData.menu[i][0])){
                  menu.push(this.formData.menu[i][1])
                }else{
                  menu.push(this.formData.menu[i][0])
                  menu.push(this.formData.menu[i][1])
                }
              }
              // console.log(this.formData.menu)
              this.formData.menu = menu.toString()
            }else{
              this.formData.menu = ''
            }
            if (this.isEdit) {
              // 编辑保存
              this.$axios.put('/sysUser/', this.formData).then(res => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.loadButton = false
                this.getAll()
              }).catch((error) => {
                // this.$refs.xTable.setActiveRow(row)
                this.$message.error('修改用户出错' + error)
              })
            } else {
              // 新增保存
              this.formData.stationCode = this.elStation
              console.log(this.formData)
              this.$axios.post('/sysUser/', this.formData).then(res => {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.loadButton = false
                this.getAll()
              }).catch((error) => {
                this.$message.error('修改用户出错' + error)
              })
            }
            this.showEdit = false
            this.selectRow = false
          }
        })

      },
      cancelRowEvent(row) {
        // const xTable = this.$refs.xTable
        this.$refs.xModal.close()
        this.loadButton = false
        // xTable.clearActived().then(() => {
        //   // 还原行数据
        //   if (this.isEdit) {
        //     // 编辑
        //     xTable.revertData(row)
        //   } else {
        //     // 新增
        //     xTable.remove(row)
        //   }
        //   this.loadButton = false
        // })
      },
      // 删除场站信息
      deleteRowEvent(row) {
        this.rowId = row.id
        this.delVisible = true
      },
      deleteCancel() {
        this.delVisible = false
      },
      deleteInfo() {
        this.$axios.delete('/sysUser/' + this.rowId).then(res => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.delVisible = false
          this.getAll()
        }).catch((error) => {
          this.$message.error('删除用户出错' + error)
        })
      },
      formatStatus({ cellValue }){
        const item = this.userStatus.find(item => item.value === cellValue)
        return item ? item.label : ''
      },
      formatMenu(menu){
        if(menu === null){
          return null
        }else{
          var data = menu.split(",")
          var menuArr = []
          for (var i=0;i<data.length;i++){
            for(var j=0;j<this.childrenOption.length;j++){
              if(this.childrenOption[j].id == data[i]){
                menuArr.push([this.childrenOption[j].fId,this.childrenOption[j].id])
              }
            }
          }
          return menuArr
        }

      }
    }
  }
</script>

<style scoped>

  .my_table_insert .vxe-body--row.is--new {
    background-color: #f1fdf1;
  }
  .formItem{
    width: 45%;
    display: inline-block;
  }
  /*/deep/*/
  /*.vxe-input--inner{*/
  /*  width: auto;*/
  /*}*/

</style>
