<template>
  <div class="newUserManagement">
    <div class="newUserManagement-head manageTitle">用户管理</div>
    <div class="flex-wrap newUserManagement-content">
      <div class="newUserManagement-content-left" style="padding: 0;">
        <!-- <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" 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>
              </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 label="描述">
                <el-input style="width:773px;" 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" border style="width: 100%">
              <el-table-column prop="user_name" label="用户名">
              </el-table-column>
              <el-table-column prop="user_status" label="状态">
              </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="325">
                <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="ruleForm" :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="handleOk" 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 options" :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" 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'
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: ''
      },
      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: []
    }
  },
  mounted () {
    this.getTreeData()
  },
  computed: {
    dataList () {
      return this.arrs.filter(data => !this.search || data.user_group_name.toLowerCase().includes(this.search.toLowerCase()))
    },
  },
  methods: {
    async getTreeData () {
      const result = await this.getQueryList(this.queryId)
      if (result && result.length) {
        // this.dataList = result
        this.arrs.push(...result)
        // this.options = result
        // this.data[0].children = result
      }
    },
    handleAdd () {
      this.type = 'add'
      this.treeCheckId = null
      this.tableData = []
      this.clearForm()
    },
    async handleNodeClick (data,index) {
      this.activeIndex = index
      if (data.user_group_id !== 0) {
        this.treeCheckId = data.user_group_id
        this.formInline = _.cloneDeep(data)
        this.type = 'edit'
        const result = await this.getQueryList(SERVICE_ID.getUserTableId, {
          user_group_id: data.user_group_id
        }, 'user_group_id')
        this.tableData = result
      } else {
        alert('不可选中')
        return 
        // this.formInline.user_group_name = ''
        // this.formInline.user_group_comment = ''
      }
    },
    //清空表单
    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 () {
      let code = null
      if (this.rmType == '1') {
        code = await this.getChangeList(this.queryId, this.rmObj, 3)
        if (code) {
          this.getTreeData()
          this.rmObj = {}
          this.clearForm()
        }
      } else {
        code = await this.getChangeList(SERVICE_ID.getUserTableId, this.dataObj, 3)
        if (code) {
          const result = await this.getQueryList(SERVICE_ID.getUserTableId, {
            user_group_id: this.dataObj.user_group_id
          },'user_group_id')
          this.tableData = result
          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 = this.formInline
          if (this.type == 'add') {
            code = await this.getChangeList(this.queryId, data, 1, 'user_group_id')
          } else {
            const id = this.formInline.user_group_id
            if (id) {
              code = await this.getChangeList(this.queryId, data, 2,'user_group_id')
            }
          }
          if (code) {
            if (this.type == 'add') {
              this.clearForm()
            }
            this.getTreeData()
          }
        }
        else {
          return false
        }
      })
    },
    handleTableAdd () {
      if (this.treeCheckId !=0) {
        this.tableFlag = true
        this.dataType = 'add'
        this.dataTitle = '新增账号'
        this.clearTableForm()
        this.ruleForm.user_group_id = this.treeCheckId
      }
    },
    handleTableEdit (row) {
      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 code = await this.getQueryList(SERVICE_ID.userAuthorizationId, {
        user_id: row.user_id
      }, 'user_id')
      
      this.tableCols = result
      this.tableCols.forEach(element => {
        element.user_id = row.user_id
      });
      code.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 code = null
      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
        }
      }
      code = await this.getChangeList(SERVICE_ID.userAuthorizationId,arr, event)
    },
    hide () {
      this.dialogFlag = false
    },
    async handleOk () {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          let code = null
          const data = this.ruleForm
          this.ruleForm.user_id = this.userId
          this.ruleForm.user_pwd= MD5(this.ruleForm.user_pwd)
          if (this.dataType == 'add') {
            code = await this.getChangeList(SERVICE_ID.getUserTableId, data, 1,'user_id')
          } else {
            const id = this.ruleForm.user_group_id
            if (id) {
              code = await this.getChangeList(SERVICE_ID.getUserTableId, data, 2,'user_id')
            }
          }
          if (code) {
            if (this.dataType == 'add') {
              this.clearTableForm()
            }
            const result = await this.getQueryList(SERVICE_ID.getUserTableId, {
              user_group_id: this.formInline.user_group_id
            }, 'user_group_id')
            this.tableData = result
          }
          this.tableFlag = false
          this.paswordFlag = false
        }
        else {
          return false
        }
      })
    },
    eledite () {
      this.paswordFlag = false
      this.tableFlag = false
      this.clearTableForm()
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../newRole/css/index.scss";
.newUserManagement {
  padding: 24px;
  height: calc(100vh - 80px);
  &-content {
    height: calc(100% - 58px);
    margin-top: 30px;
    .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;
      padding: 24px;
      .contents {
        // margin-top: 24px;
        height: calc(100% - 56px);
        .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;
          }
        }
      }
    }
    &-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;
        }
      }
    }
  }
}
</style>