<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>
            <div>
              <el-button v-if="isExport" @click="handleExport" class="serButton" size="small">导出</el-button>
              <el-button @click="handleAdd" class="serButton" size="small">新增</el-button>
            </div>
          </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" draggable :data="arrs" :props="defaultArrProps" highlight-current :filter-node-method="filterArrNode" default-expand-all node-key="user_group_id" @node-click="handleNodeClick" @node-drop="nodeDrop" :allow-drop="allowDrop" :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" :disabled="editGroupDisabled">保存</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="请输入账号组名称" :disabled="editGroupDisabled"></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="请选择上级用户组" :disabled="editGroupDisabled">
                  <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="请输入描述" :disabled="editGroupDisabled"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="newUserManagement-content-right-bottom">
          <div class="head flex">
            <div class="title">账号列表</div>
            <div>
              <el-button @click="handleTableAdd" type="primary" size="small" :disabled="addUserDisabled">新增</el-button>
              <el-button @click="exportHandler('userTableData')" type="primary" size="small" :disabled="addUserDisabled">导出</el-button>
            </div>
          </div>
          <div class="contents">
            <el-table :data="tableData" height="100%" border style="width: 100%" ref="userTableData">
              <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="signInTime" label="登录时间">
                <template slot-scope="scope">
                  <div v-if="scope.row.signInTime">{{ scope.row.signInTime.replace('T',' ') }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="LogoutTime" label="登出时间">
                <template slot-scope="scope">
                  <div v-if="scope.row.LogoutTime">{{ scope.row.LogoutTime.replace('T',' ') }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="email" 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="email">
              <el-input v-model="ruleForm.email" 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'
import XLSX from "xlsx";
import { Format } from '@/utils/validate'
import { exportToExcel } from '@/utils/table'
import { exportJsonToExcel } from '@/utils/Export2Excel.js'
import { parseTime } from '@/utils'
import { mapGetters } from 'vuex'
// import * as XLSX from 'xlsx'
import XLSX_STYLE from 'xlsx-style'
import FileSaver from 'file-saver'
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,
        "email": null
      },
      tableRules: {
        user_name: [{ required: true, message: "请输入账号名称", trigger: "blur" }],
        user_group_id: [{ required: true, message: '请选择账号组', trigger: 'change' }],
        user_pwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ required: true, pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '请输入正确的邮箱格式', trigger: 'blur' }],
      },
      paswordFlag: false,//修改密码
      tableFlag: false,
      title: '新增',
      type: '',
      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: {},
      groupname: '',
      execList: []
    }
  },
  watch: {
    search (val) {
      this.$refs.treeArr.filter(val);
    }
  },
  mounted () {
    this.getTreeData()
    this.upgout()
  },
  computed: {
    ...mapGetters(['authArrs']),
    dataList () {
      return this.arrs
    },
    editGroupDisabled () {
      return !this.type
    },
    addUserDisabled () {
      return !this.treeCheckId
    },
    isExport () {
      const len = this.authArrs.filter(item => item.auth_ident == 'userExport')
      if (len.length) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    async upgout () {
      const { code, returnData } = await this.getQueryList('2003115')
      if (code == 0) {
        this.execList = returnData
      }
    },
    async getTreeData () {
      const { code, returnData } = await this.getQueryListAuth(this.queryId)
      if (code == 0) {
        if (returnData && returnData.length) {
          returnData.map(item => {
            item.user_group_level = Number(item.user_group_level)
            item.user_group_sort = Number(item.user_group_sort)
          })
          this.arrTree = _.cloneDeep(returnData)
          const treeMenu = listToTree(returnData, 'up_user_group_id', 'user_group_id')
          this.arrs = this.orderData(treeMenu)
        }
      }
    },
    orderData (arr) {
      const narr = [...arr]
      if (!narr.length) return []
      narr.map(item => {
        if (item.children?.length) {
          item.children = _.orderBy(item.children, ['user_group_level', 'user_group_sort'], ['asc', 'asc'])
          this.orderData(item.children)
        }
      })
      return narr
    },
    filterArrNode (value, data) {
      if (!value) return true;
      return data.user_group_name.indexOf(value) !== -1;
    },
    handleAdd () {
      this.type = 'add'
      this.treeCheckId = null
      this.tableData = []
      this.clearForm()
      this.formInline.user_group_name = '新建账号组'
      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' })
      // console.log(this.arrs)
      // this.treeCheckId = this.arrs[this.arrs.length-1].user_group_id
    },
    //拖拽目标判断
    allowDrop (draggingNode, dropNode, type) {
      if (draggingNode.parent.id == dropNode.parent.id) {
        return type == "next"
      } else {
        return false
      }
    },
    //拖拽完成
    nodeDrop (draggingNode, dropNode) {
      const [o1, o2] = [{ ...draggingNode.data }, { ...dropNode.data }]
      o1.user_group_sort = dropNode.data.user_group_sort
      o2.user_group_sort = draggingNode.data.user_group_sort
      const https = [this.getChangeList(this.queryId, o1, 2, 'user_group_id'), this.getChangeList(this.queryId, o2, 2, 'user_group_id')]
      this.dropHttp(https)
    },
    async dropHttp (https) {
      const result = await Promise.allSettled(https)
      result.map(item => {
        if (item.status == 'fulfilled') {
          this.$message.success('操作成功')
        } else {
          this.$message.success('操作失败')
        }
      })
      this.getTreeData()
    },
    async handleNodeClick (data) {
      this.groupname = data.user_group_name
      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, { user_group_id: this.rmObj.user_group_id }, 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)
        this.tipMsg(code)
        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
          let mesResult = 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 (data.up_user_group_id) {
                const items = this.arrTree.filter(item => item.user_group_id == data.up_user_group_id)
                if (!items.length) return
                const { user_group_level } = items[0]
                const levels = this.arrTree.filter(item => item.user_group_level == Number(user_group_level) + 1)
                if (!levels.length) return
                const nlevels = _.orderBy(levels, 'user_group_sort', 'asc')
                const { user_group_sort } = nlevels?.at(-1)
                data.user_group_sort = Number(user_group_sort) + 1
                data.user_group_level = Number(user_group_level) + 1
              } else {
                const items = this.arrTree.filter(item => !item.up_user_group_id)
                if (!items.length) return
                const { user_group_level } = items[0]
                const nlevels = _.orderBy(items, 'user_group_sort', 'asc')
                const { user_group_sort } = nlevels?.at(-1)
                data.user_group_sort = Number(user_group_sort) + 1
                data.user_group_level = Number(user_group_level)
              }
              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
              mesResult = result
            }
          }
          if (code == 0) {
            if (this.type == 'add') {
              this.clearForm()
            }
            this.getTreeData()
            this.tipMsg(code)
          } else {
            if (mesResult.code == -1 && mesResult.message.toString().includes('for key')) {
              this.tipMsg(code, '账号组名称重复,请重新输入')
            } else {
              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
      const ruleForm = _.cloneDeep(row)
      ruleForm.user_pwd = ''
      this.ruleForm = ruleForm
    },
    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, message } = await this.getChangeList(SERVICE_ID.getUserTableId, data, 1)
            if (code == -1 && message.toString().includes('for key')) {
              this.tipMsg(code, '账号名称重复,请重新输入')
            } else {
              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()
    },
    //导出
    downFile () {
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#userTableData")
      );
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: "application/octet-stream",
          }),
          this.groupname + Format('yyyy-MM-dd', new Date()), + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    exportHandler: _.throttle(
      function (refName) {
        const table = this.$refs[refName].$el.cloneNode(true)
        const fileName = `${this.groupname + Format('yyyy-MM-dd', new Date())}.xlsx`
        console.log(fileName)
        exportToExcel(table, this.groupname, fileName)
      },
      2000,
      { trailing: false }
    ),
    handleExport () {

      var arr = [];
      let mJson = JSON.parse(JSON.stringify(this.execList));

      // ============ 【添加表列的标头】

      let TableHead = ['登录账号', '用户名', '所属用户组', '用户状态', '登出时间', '登陆时间'];

      // 指定导出字段
      let mField = "登录账号,用户名,所属用户组,用户状态,登出时间,登陆时间";

      // ======================= 【处理mJson数据】

      let mFieldsArray = mField.split(','); // 将 mField 字符串转换为以逗号分隔的数组

      // 遍历 mJson 数组中的每个对象
      for (let i = 0; i < mJson.length; i++) {
        let newObj = {}; // 创建一个新对象存储重新排序后的键名和键值

        // 遍历 mFieldsArray 数组中的每个字段
        for (let j = 0; j < mFieldsArray.length; j++) {
          let field = mFieldsArray[j];
          if (mJson[i].hasOwnProperty(field)) {
            if (field == "accountTime") {
              newObj[field] = mJson[i][field].substring(0, 10); // 将原对象中的对应键名和键值赋给新对象
            }
            else if (field == "goodsStatus") {

              switch (mJson[i][field]) {

                case '0':
                  newObj[field] = "一级";
                  break;
                case '1':
                  newObj[field] = "二级";
                  break;
                case '2':
                  newObj[field] = "三级";
                  break;
                default:
                  newObj[field] = "四级";
              }
            }
            else {
              newObj[field] = mJson[i][field]; // 将原对象中的对应键名和键值赋给新对象
            }

          }

        }
        mJson[i] = newObj; // 将新对象替换原对象
      }

      //  console.log(mJson);
      // ============ 【添加表列的标头】

      // 创建一个空的二维数组
      var arr = [];
      // 使用JSON.parse方法把json变量转换成一个对象数组
      var objArr = mJson;
      // 遍历对象数组，把每个对象的属性值放入一个一维数组中，然后把这个一维数组添加到二维数组中
      for (var i = 0; i < objArr.length; i++) {
        // 创建一个空的一维数组
        var row = []; // 获取当前对象
        var obj = objArr[i]; // 遍历对象的属性，把属性值放入一维数组中

        for (var key in obj) {
          // console.log("### key =" + key + " ###");
          if (key == "CreatDate" || key == "Id") {  // 排除字段
          } else {
            row.push(obj[key]);
          }
        }
        // 把一维数组添加到二维数组中
        arr.push(row);
      }

      arr.unshift(TableHead); // 添加列标头名
      // console.log("######################");
      // console.log(arr);

      // ============ 【添加表格标题行】
      let TableTitle = ["用户列表" + '（' + parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}") + '）'];  // 表标题内容
      // 计算合并标题单元格
      let ColCount = TableHead.length;
      let ColLetter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      let ColIndex = ColCount - 1;
      let m_TitleMerges = "A1:" + ColLetter.charAt(ColIndex) + "1";
      const TitleMerges = [];
      TitleMerges.push(m_TitleMerges);  //["A1:E1"]
      // let TitleMerges=["A1:E1"];
      // ============ 【设置列宽】
      let wscols = [
        { wch: 8 }, // 编号
        { wch: 14 }, // 编码1
        { wch: 12 }, // 分类
        { wch: 20 }, // 名称
        { wch: 12 }, // 品牌
        { wch: 15 }, // 规格
        { wch: 5 }, // 单位
        { wch: 15 }, // 区域
        { wch: 8 }, // 方式
        { wch: 10 }, // 日期
        { wch: 8 }, // 状态
        { wch: 8 }, // 使用者
        { wch: 15 }, // 部门
        { wch: 8 }, // 者
        { wch: 15 }, // 
      ];

      // alert("开始导出");

      // console.log(arr);

      // 开始导出
      exportJsonToExcel({
        // 这里用到了Export2Excel.js
        header: TableTitle,  // 表标题
        data: arr,  // 实际数据从第三行开始
        filename: "明细表",  // 文件名
        merges: TitleMerges,  // 合并A1到C1单元格作为标题行
        bookType: 'xls',  // 生成的文件类型
        autoWidth: true,  // 不自动调整列宽
        XlsWidth: wscols
      });
      // alert("ok")
      // exportExcelGoods()
      // this.$message.success('导出成功')
    },
  }
}
</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>