<template>
  <div class="newUserManagement">
    <div class="flex-wrap newUserManagement-content">
      <div class="newUserManagement-content-left">
        <!-- <div class="head flex">
          <div class="title">账号组列表</div>
          <el-button @click="handleAdd" class="serButton" type="primary" plain size="small">新增</el-button>
        </div>
        <div class="contents">
          <el-scrollbar ref="scroll" style="height: 100%">
            <el-tree  :data="data"  :props="defaultProps" :expand-on-click-node="false" highlight-current node-key="user_group_id" default-expand-all @node-click="handleNodeClick">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span class="customTxt">{{ node.label }}</span>
                <span v-show="treeCheckId == data.user_group_id" class="customBtn">
                  <span v-if="data.user_group_id != 0" @click.stop="handleRemove(node, data)">删除</span>
                </span>
              </span>
            </el-tree>
          </el-scrollbar>
        </div> -->
        <div class="newService-content-left-top">
          <div class="flex head">
            <div class="title">账号组列表</div>
            <el-button @click="handleAdd" class="serButton" size="small">新增</el-button>
          </div>
          <div class="search">
            <el-input size="small" placeholder="请输入内容" clearable prefix-icon="el-icon-search" :filter-node-method="filterArrNode" v-model="search">
            </el-input>
          </div>
        </div>
        <div class="newService-content-left-bottom">
          <template v-if="dataList.length">
            <el-scrollbar ref="scroll" style="height: 100%">
              <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
                <!-- <div v-for="(item,index) in dataList" :key="index" @click.stop="handleNodeClick(item,index)" :class="index == activeIndex ? 'active':''" class="contents flex">
                  <div class="left">
                    <span class="txt">{{ item.user_group_name }}</span>
                  </div>
                  <div v-show="activeIndex == index" class="right">
                    <span @click.stop="handleRemove(item)" class="error">删除</span>
                  </div>
                </div> -->
                <el-tree ref="treeArr" :data="arrs" :props="defaultArrProps" highlight-current :filter-node-method="filterArrNode" default-expand-all node-key="user_group_id" @node-click="handleNodeClick" :expand-on-click-node="false">
                  <span class="custom-tree-node" slot-scope="{ node,data }">
                    <div class="flex">
                      <span class="customTxt">{{ node.label }}</span>
                      <span v-show="treeCheckId == data.user_group_id" class="customBtn">
                        <span v-if="data.user_group_id" @click.stop="handleRemove(data)">删除</span>
                      </span>
                    </div>
                  </span>
                </el-tree>
              </div>
            </el-scrollbar>
          </template>
          <template v-else>
            <el-empty description="暂无数据"></el-empty>
          </template>
        </div>
      </div>
      <div class="newUserManagement-content-right flex1">
        <div class="newUserManagement-content-right-top">
          <div class="head flex">
            <div class="title">账号组信息</div>
            <el-button @click="handleSave" type="primary" size="small">保存</el-button>
          </div>
          <div class="contents">
            <el-form :inline="true" :rules="rules" ref="form" :model="formInline" class="demo-form-inline">
              <el-form-item prop="user_group_name" label="账号组名称">
                <el-input style="width:260px;margin-right: 30px;" size="small" v-model="formInline.user_group_name" placeholder="请输入账号组名称"></el-input>
              </el-form-item>
              <el-form-item prop="up_user_group_name" label="上级用户组">
                <el-select style="width:260px;margin-right: 30px;" size="small" clearable v-model="formInline.up_user_group_id" placeholder="请选择上级用户组">
                  <el-option v-for="item in arrTree" :key="item.user_group_id" :label="item.user_group_name" :value="item.user_group_id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="描述">
                <el-input style="width:260px;" size="small" v-model="formInline.user_group_comment" placeholder="请输入描述"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="newUserManagement-content-right-bottom">
          <div class="head flex">
            <div class="title">账号列表</div>
            <el-button @click="handleTableAdd" type="primary" size="small">新增</el-button>
          </div>
          <div class="contents">
            <el-table :data="tableData" height="100%" border style="width: 100%">
              <el-table-column prop="user_name" label="用户名">
              </el-table-column>
              <el-table-column prop="user_status" label="状态">
                <template slot-scope="scope">
                  <div>{{ scope.row.user_status ? '启用' :'禁用' }}</div>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="token_valid_duration" label="令牌有效时长">
              </el-table-column> -->
              <el-table-column prop="user_comment" label="描述">
              </el-table-column>
              <el-table-column label="操作" width="235">
                <template slot-scope="scope">
                  <el-button @click="handleTablepaswod(scope.row)" type="primary" plain size="small">修改密码 </el-button>
                  <el-button @click="handleTableEdit(scope.row)" type="primary" plain size="small">编辑 </el-button>
                  <!-- <el-button @click="handleTableAuth(scope.row)" type="primary" plain size="small">账号授权 </el-button> -->
                  <el-button @click="handleTableDel(scope.row)" type="danger" size="small">删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <Dialog :flag="paswordFlag">
      <div class="dialog-content">
        <div class="title">{{ dataTitle }}</div>
        <div class="contents">
          <el-form ref="ruleForms" :model="ruleForm" :rules="tableRules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="账号密码" prop="user_pwd">
              <div class="flex-wrap">
                <el-input v-model="ruleForm.user_pwd" class="r25" size="small" placeholder="请输入密码" />
                <el-button size="small" @click="restPwd" style="position: relative;top: 4px;" class="r26" type="primary">生成密码</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="foot right">
          <el-button size="small" @click="handleOkSk('ruleForms')" class="r24" type="primary">确定</el-button>
          <el-button @click="eledite" size="small">取消</el-button>
        </div>
      </div>
    </Dialog>
    <Dialog :flag="tableFlag">
      <div class="dialog-content">
        <div class="title">{{ dataTitle }}</div>
        <div class="contents">
          <el-form ref="ruleForm" :model="ruleForm" :rules="tableRules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="账号组关联" prop="user_gropu_id">
              <el-select style="width: 100%" size="small" v-model="ruleForm.user_group_id" placeholder="请选择">
                <el-option v-for="item in arrTree" :key="item.user_group_id" :label="item.user_group_name" :value="item.user_group_id"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="账号名称" prop="user_name">
              <el-input v-model="ruleForm.user_name" size="small" placeholder="请输入账号名称" />
            </el-form-item>
            <!-- <el-form-item label="账号密码" prop="user_pwd">
              <div class="flex-wrap">
                <el-input v-model="ruleForm.user_pwd" class="r25" size="small" placeholder="请输入密码" />
                <el-button size="small" @click="restPwd" style="position: relative;top: 4px;" class="r26" type="primary">生成密码</el-button>
              </div>
            </el-form-item> -->
            <el-form-item label="二级密码" prop="user_sec_pwd">
              <el-input v-model="ruleForm.user_sec_pwd" size="small" placeholder="请输入二级密码" />
            </el-form-item>
            <!-- <el-form-item label="令牌有限期" prop="token_valid_duration">
              <el-input v-model="ruleForm.token_valid_duration" size="small" placeholder="请输入令牌有限期(小时)" />
            </el-form-item> -->
            <el-form-item label="账号描述" prop="user_comment">
              <el-input v-model="ruleForm.user_comment" size="small" type="textarea" :rows="3" placeholder="请输入账号描述" />
            </el-form-item>
            <el-form-item label="是否启用" prop="user_status">
              <el-radio v-model="ruleForm.user_status" :label="2">是</el-radio>
              <el-radio v-model="ruleForm.user_status" :label="0">否</el-radio>
            </el-form-item>
          </el-form>
        </div>
        <div class="foot right">
          <el-button size="small" @click="handleOk('ruleForm')" class="r24" type="primary">确定</el-button>
          <el-button @click="eledite" size="small">取消</el-button>
        </div>
      </div>
    </Dialog>
    <Dialog :flag="dialogFlag" class="dialog-check-group">
      <div class="dialog-wrapper">
        <div class="title">角色列表</div>
        <div class="content">
          <!-- <el-tree ref="columnSetTree" :data="tableCols" :class="colsCheckClass" show-checkbox node-key="index" :default-expand-all="true" :props="{
              label: 'role_name',
              children: 'role_ID',
            }" :default-checked-keys="checkedKeysTemp" @check="handleCheck" /> -->
          <el-checkbox v-model="item.role_status" v-for="(item, index) in tableCols" :key="index" @change="handleCheckedCitiesChange(item)">{{ item.role_name }}</el-checkbox>
        </div>
        <div class="foot right t30">
          <!-- <el-button size="medium" class="r24" type="primary" @click="onCheck">确定</el-button> -->
          <el-button size="medium" @click="hide">关闭</el-button>
        </div>
      </div>
    </Dialog>
    <Dialog :flag="rmFlag">
      <div class="airportInfoDialog">
        <div class="title del-title">删除</div>
        <div class="content del-content">
          <span class="el-icon-error error r10"></span>您是否确认删除<span class="error l10">{{ rmTitle }}</span>
          ？
        </div>
        <div class="foot right Delfoot">
          <el-button size="small" class="r24" @click="tableRemove" type="danger">删除</el-button>
          <el-button size="small" @click="rmFlag = false">取消</el-button>
        </div>
      </div>
    </Dialog>
  </div>
</template>

<script>
import pb from '@/layout/mixin/getPublicData'
import Dialog from '@/layout/components/Dialog'
import pf from '@/layout/mixin/publicFunc'
import MD5 from 'blueimp-md5'
import { listToTree } from '@/utils/validate'
export default {
  name: 'NewManageMent',
  components: { Dialog },
  mixins: [pb, pf],
  data () {
    return {
      data: [
        {
          up_user_group_id: -1,
          user_group_comment: '',
          user_group_id: 0,
          user_group_name: '全部账号组',
          user_group_status: true,
          children: []
        }
      ],
      search: '',
      activeIndex: null,
      loading: false,
      treeCheckId: '',
      formInline: {
        user_group_name: '',
        user_group_comment: '',
        up_user_group_id: ''
      },
      rules: {
        user_group_name: [{ required: true, message: '请输入账号组名称', trigger: 'blur' }],
      },
      ruleForm: {
        "token_valid_time": null,
        "token_valid_duration": null,
        "user_code": null,
        "user_code_expire": null,
        "user_comment": null,
        "user_group_id": null,
        "user_id": null,
        "user_name": null,
        "user_pwd": null,
        "user_sec_pwd": null,
        "user_status": null,
        "user_token": null
      },
      tableRules: {
        user_name: [{ required: true, message: "请输入账号名称", trigger: "blur" }],
        user_group_id: [{ required: true, message: '请选择账号组', trigger: 'change' }],
        user_pwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      paswordFlag: false,//修改密码
      tableFlag: false,
      title: '新增',
      type: 'add',
      dataType: 'add',
      dataTitle: '新增账号',
      dataObj: {},
      defaultProps: {
        children: 'children',
        label: 'user_group_name'
      },
      tableData: [],
      rmFlag: false,
      rmObj: {},
      rmTitle: '',
      options: [],
      rmType: '1',
      tableCols: [],
      dialogFlag: false,
      checkedKeysTemp: [],
      userId: '',
      arrs: [],
      authId: null,
      defaultArrProps: {
        children: 'children',
        label: 'user_group_name'
      },
      arrTree: [],
      treeCheckObj: {}
    }
  },
  watch: {
    search (val) {
      this.$refs.treeArr.filter(val);
    }
  },
  mounted () {
    this.getTreeData()
  },
  computed: {
    dataList () {
      return this.arrs
    },
  },
  methods: {
    async getTreeData () {
      const { code, returnData } = await this.getQueryListAuth(this.queryId)
      if (code == 0) {
        if (returnData && returnData.length) {
          this.arrTree = _.cloneDeep(returnData)
          const treeMenu = listToTree(returnData, 'up_user_group_id', 'user_group_id')
          this.arrs = treeMenu
        }
      }
    },
    filterArrNode (value, data) {
      if (!value) return true;
      return data.user_group_name.indexOf(value) !== -1;
    },
    handleAdd () {
      const datas = this.arrs.filter(item => item.user_group_name == '新建账号组')
      if (datas && datas.length) {
        return
      }
      this.arrs.push({ user_group_name: '新建账号组', user_group_id: 'test' })
      this.type = 'add'
      this.treeCheckId = null
      this.tableData = []
      this.clearForm()
      this.formInline.user_group_name = '新建账号组'
      // console.log(this.arrs)
      // this.treeCheckId = this.arrs[this.arrs.length-1].user_group_id
    },
    async handleNodeClick (data) {
      if (data.user_group_id) {
        const datas = this.arrTree.filter(item => item.user_group_id == data.up_user_group_id)
        this.treeCheckId = data.user_group_id
        this.treeCheckObj = _.cloneDeep(data)
        this.formInline = _.cloneDeep(data)
        if (data.user_group_id != 'test') {
          if (!data.up_user_group_id || datas.length < 1) {
            this.formInline.up_user_group_id = ''
          }
          this.type = 'edit'
          const { code, returnData } = await this.getQueryList(SERVICE_ID.getUserTableId, {
            up_user_group_id: data.user_group_id
          })
          if (code == 0 && returnData && returnData.length) {
            this.tableData = returnData
          } else {
            this.tableData = []
          }
        }
      }
    },
    //清空表单
    clearForm () {
      const data = this.formInline
      for (const key in data) {
        if (Object.hasOwnProperty.call(data, key)) {
          data[key] = null
        }
      }
      this.$refs['form'].resetFields()
    },
    clearTableForm () {
      const data = this.ruleForm
      for (const key in data) {
        if (Object.hasOwnProperty.call(data, key)) {
          data[key] = null
        }
      }
      setTimeout(() => {
        this.$refs['ruleForm'].resetFields()
      }, 50);
    },
    restPwd () {
      this.ruleForm.user_pwd = '123!@#QWEqwe'
    },
    //树删除
    handleRemove (data) {
      this.rmTitle = data.user_group_name
      this.rmFlag = true
      this.rmObj = data
      this.rmType = '1'
    },
    async tableRemove () {
      if (this.rmType == '1') {
        const { user_group_id } = this.treeCheckObj
        if (user_group_id == 'test') {
          this.arrs.pop()
        } else {
          if (this.rmObj.children) {
            delete this.rmObj.children
          }
          const { code } = await this.getChangeList(this.queryId, this.rmObj, 3)
          if (code == 0) {
            this.getTreeData()
            this.rmObj = {}
            this.clearForm()
            this.tipMsg(code)
          }
        }
      } else {
        const { user_name } = this.dataObj
        const { user_group_id } = this.treeCheckObj
        const { code } = await this.getChangeList(SERVICE_ID.getUserTableId, { user_name, up_user_group_id: user_group_id }, 3)
        if (code == 0) {
          const { returnData } = await this.getQueryList(SERVICE_ID.getUserTableId, {
            up_user_group_id: this.dataObj.up_user_group_id
          })
          this.tableData = returnData
          this.dataObj = {}
          this.clearTableForm()
        }
      }
      this.rmFlag = false
    },
    async handleSave () {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          let code = null
          this.formInline.user_group_id = this.treeCheckId
          const data = _.cloneDeep(this.formInline)
          // console.log(this.type)
          if (this.type = 'edit') {
            const id = this.formInline.user_group_id
            if (id && id != 'test') {
              const res = await this.getChangeList(this.queryId, data, 2, 'user_group_id')
              code = res.code
            } else {
              let result = null
              if (id == 'test') {
                data.user_group_id = null
                result = await this.getChangeList(this.queryId, data, 1)
              } else {
                result = await this.getChangeList(this.queryId, data, 1)
              }
              code = result.code
            }
          }
          if (code == 0) {
            if (this.type == 'add') {
              this.clearForm()
            }
            this.getTreeData()
          }
          this.tipMsg(code)
        }
        else {
          return false
        }
      })
    },
    handleTableAdd () {
      if (this.treeCheckObj.user_group_id) {
        this.tableFlag = true
        this.dataType = 'add'
        this.dataTitle = '新增账号'
        this.clearTableForm()
        this.ruleForm.user_group_id = this.treeCheckObj.user_group_id
      } else {
        this.$message.error('请选中用户后再操作')
      }
    },
    handleTableEdit (row) {
      row.user_group_id = row.up_user_group_id
      this.tableFlag = true
      this.dataType = 'edit'
      this.userId = row.user_id
      this.dataTitle = '编辑账号'
      this.ruleForm = _.cloneDeep(row)
    },
    async handleTableAuth (row) {
      this.dialogFlag = true
      const result = await this.getQueryList(SERVICE_ID.roleListId)
      const msg = await this.getQueryList(SERVICE_ID.userAuthorizationId, {
        user_id: row.user_id
      })
      if (result.code == 0 && result.returnData && result.returnData.length) {
        this.tableCols = result.returnData
        this.tableCols.forEach(element => {
          element.user_id = row.user_id
        });
      }
      if (msg.code == 0 && msg.returnData && msg.returnData.length) {
        msg.returnData.forEach(element => {
          this.tableCols.forEach(res => {
            if (res.role_ID == element.role_id) {
              res.role_status = true
            }
          });
        });
      }
      // console.log(this.tableCols)
      // console.log(code)
    },
    handleTablepaswod (row) {
      this.paswordFlag = true
      this.dataType = 'edit'
      this.dataTitle = '修改密码'
      this.userId = row.user_id
      this.ruleForm = _.cloneDeep(row)
    },
    async handleTableDel (row) {
      this.dataObj = row
      this.rmTitle = row.user_name
      this.rmFlag = true
      this.rmType = '2'
    },
    async handleCheckedCitiesChange (data) {
      let arr = {}
      let event = null
      if (data.role_status == true) {
        event = 1
        arr = {
          role_id: data.role_ID,
          user_id: data.user_id
        }
      } else if (data.role_status == false) {
        event = 3
        arr = {
          role_id: data.role_ID,
          user_id: data.user_id
        }
      }
      const { code } = await this.getChangeList(SERVICE_ID.userAuthorizationId, arr, event)
      this.tipMsg(code)
    },
    hide () {
      this.dialogFlag = false
    },
    async handleOkSk () {
      const id = this.ruleForm.user_group_id || this.ruleForm.user_id
      if (id) {
        const r = PLATFROM_CONFIG.editRule
        const b = r.test(this.ruleForm.user_pwd)
        if (b) {
          this.ruleForm.user_pwd = MD5(this.ruleForm.user_pwd)
          const data = _.cloneDeep(this.ruleForm)
          const { user_id, user_pwd } = data
          const newData = {
            user_id,
            user_pwd
          }
          const { code } = await this.getChangeList(SERVICE_ID.getUserTableId, newData, 2, 'user_id')
          this.tipMsg(code)
          const result = await this.getQueryList(SERVICE_ID.getUserTableId, {
            up_user_group_id: this.treeCheckObj.user_group_id
          })
          this.tableData = result.returnData
          // this.clearTableForm()
          this.tableFlag = false
          this.paswordFlag = false
        } else {
          this.$message.error('请根据密码规则设置密码')
        }
      }
    },
    async handleOk (data) {
      this.$refs[data].validate(async (valid) => {
        if (valid) {
          // this.ruleForm.user_pwd= MD5(this.ruleForm.user_pwd)
          if (this.dataType == 'add') {
            this.ruleForm.up_user_group_id = this.ruleForm.user_group_id
            delete this.ruleForm.user_group_id
            const data = this.ruleForm
            const { code } = await this.getChangeList(SERVICE_ID.getUserTableId, data, 1)
            this.tipMsg(code)
          } else {
            const id = this.ruleForm.user_group_id || this.ruleForm.user_id
            if (id) {
              this.ruleForm.user_pwd = MD5(this.ruleForm.user_pwd)
              this.ruleForm.up_user_group_id = this.ruleForm.user_group_id
              const data = _.cloneDeep(this.ruleForm)
              delete data.user_group_id
              delete data.user_pwd
              const { code } = await this.getChangeList(SERVICE_ID.getUserTableId, data, 2, 'user_id')
              this.tipMsg(code)
            }
          }
          const result = await this.getQueryList(SERVICE_ID.getUserTableId, {
            up_user_group_id: this.treeCheckObj.user_group_id
          })
          this.tableData = result.returnData
          this.clearTableForm()
          this.tableFlag = false
          this.paswordFlag = false
        }
        else {
          return false
        }
      })
    },
    eledite () {
      this.paswordFlag = false
      this.tableFlag = false
      this.clearTableForm()
    }
  }
}
</script>

<style lang="scss" scoped>
.newUserManagement {
  padding: 24px;
  height: calc(100vh - 80px);
  .custom-tree-node {
    flex: 1;
    font-size: 14px;
    padding-right: 24px;
    .customBtn {
      color: #dd3838;
      font-size: 12px;
      margin-top: 3px;
    }
  }
  &-content {
    height: 100%;
    .title {
      font-size: 20px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #101116;
    }
    &-left {
      height: 100%;
      width: 440px;
      background: #ffffff;
      box-shadow: 0px 3px 3px 0px rgba(0, 0, 0, 0.1);
      border-radius: 4px;
      margin-right: 16px;
      .newService-content-left-top {
        padding: 24px 24px 18px 24px;
        .search {
          margin-top: 18px;
        }
      }
      .newService-content-left-bottom {
        height: calc(100% - 130px);
        padding-right: 5px;
      }
      .contents {
        // margin-top: 24px;
        padding: 0 24px;
        height: 42px;
        line-height: 42px;
        .left {
          font-size: 16px;
          font-family: Microsoft YaHei;
          font-weight: bold;
          color: #101116;
        }
        .right {
          color: #dd3838;
          cursor: pointer;
        }
        .custom-tree-node {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 14px;
          padding-right: 8px;
          .customBtn {
            color: #dd3838;
            font-size: 12px;
          }
        }
      }
      .active {
        background: #e4f3f9;
      }
    }
    &-right {
      &-top {
        height: 136px;
        background: #ffffff;
        box-shadow: 0px 3px 3px 0px rgba(0, 0, 0, 0.1);
        border-radius: 4px;
        padding: 24px;
        .contents {
          .el-form-item {
            margin-bottom: 0;
            margin-top: 20px;
          }
        }
      }
      &-bottom {
        margin-top: 16px;
        height: calc(100% - 152px);
        background: #ffffff;
        box-shadow: 0px 3px 3px 0px rgba(0, 0, 0, 0.1);
        border-radius: 4px;
        padding: 24px;
        .contents {
          margin-top: 24px;
          height: calc(100% - 50px);
        }
      }
    }
  }
}
</style>