<template>
  <a-spin :tip="aSpinLoading" :spinning="spinning" class="spinOuter">
    <a-row :gutter="10" style="height: 100%">
      <a-col :md="6" :sm="24" style="padding-right: 15px; width: 260px; height: 100%">
        <a-card :bordered="false" class="aCardTree">
          <!-- 按钮操作区域 -->
          <a-row style="margin-left: 14px">
            <!-- <a-button @click="handleAdd(1)" type="primary">添加部门</a-button> -->
            <!-- <a-button @click="handleAdd(2)" type="primary">添加下级</a-button> -->
            <!-- <a-button type="primary" icon="download" @click="handleExportXls('部门信息')" >导出</a-button> -->
            <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
              <a-button type="primary" icon="import">导入</a-button>
            </a-upload>
            <a-button title="删除多条数据" @click="batchDel" type="default">批量删除</a-button> -->
            <!-- <a-button @click="refresh" type="default" icon="reload" :treeLoading="treeLoading">刷新</a-button> -->
          </a-row>
          <div style="background: #fff; height: 100%; overflow-y: auto; overflow-x: hidden">
            <!-- <a-alert type="info" :showIcon="true">
              <div slot="message">
                当前选择：<span>{{selectTreeRow.title}}</span>
                <a v-if="this.currSelected.title" style="margin-left: 10px" @click="onClearSelected">取消选择</a>
              </div>
            </a-alert> -->
            <!-- <div style="font-size: 20px;">区划树</div> -->
            <!-- <a-input-search @search="onSearch" style="width:100%;" placeholder="请输入行政区划"/> -->
            <!-- 树-->
            <a-spin :spinning="treeLoading">
              <a-input-search @search="onSearchDepart" style="width: 100%" placeholder="请输入部门简称搜索" />
              <a-col :md="10" :sm="24" style="width: 100%; max-height: calc(100vh - 220px); overflow: auto">
                <template>
                  <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
                    <span style="user-select: none">
                      <a-tree
                        :tree-data="treeData"
                        class="treeArea"
                        @select="selectTree"
                        :selectedKeys="selectedKeys"
                        :expandedKeys.sync="expandedKeys"
                        :show-line="true"
                        :loadData="onLoadTreeData"
                        :replaceFields="replaceFields"
                      />
                    </span>
                    <!--新增右键点击事件,和增加添加和删除功能-->
                    <!-- <a-menu slot="overlay">
                      <a-menu-item @click="handleAdd(3)" key="1">添加</a-menu-item>
                      <a-menu-item @click="handleDelete" key="2">删除</a-menu-item>
                      <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
                    </a-menu> -->
                  </a-dropdown>
                </template>
              </a-col>
            </a-spin>
          </div>
        </a-card>
        <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
        <!-- <div class="drawer-bootom-button">
          <a-dropdown :trigger="['click']" placement="topCenter">
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
              <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
              <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
              <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
              <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
              <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
            </a-menu>
            <a-button>
              树操作 <a-icon type="up" />
            </a-button>
          </a-dropdown>
        </div> -->
        <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
      </a-col>
      <a-col :md="18" :sm="24" class="tableArea aTable" style="width: calc(100% - 260px); height: 100%" ref="tableArea">
        <div v-if="isChooseGov">
          <a-card :bordered="false">
            <!-- 查询区域 -->
            <!-- <div class="table-page-search-wrapper" ref="searchArea" v-has="'user:search'">
             
              <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">
                  <a-col :md="8" :sm="8">
                    <a-form-item label="登录账号">
                      <a-input placeholder="请输入登录账号" v-model="queryParam.username"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="8">
                    <a-form-item label="姓名">
                    
                      <a-input placeholder="请输入姓名" v-model="queryParam.realname"></a-input>
                    </a-form-item>
                  </a-col>
                  <template v-if="toggleSearchStatus">
                    <a-col :md="8" :sm="8">
                      <a-form-item label="手机号码">
                        <a-input placeholder="请输入手机号码查询" v-model="queryParam.phone"></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                      <a-form-item label="身份证号码">
                        <a-input placeholder="请输入身份证号码" v-model="queryParam.idCard"></a-input>
                      </a-form-item>
                    </a-col>
                  </template>
                  <a-col :md="8" :sm="8">
                    <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                      <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                      <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px"
                        >重置</a-button
                      >
                      <a @click="handleToggleSearch" style="margin-left: 8px">
                        {{ toggleSearchStatus ? '收起' : '展开' }}
                        <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                      </a>
                    </span>
                  </a-col>
                </a-row>
              </a-form>
            </div> -->

            <!-- 查询区域 -->
            <div class="table-page-search-wrapper search_box">
              <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">
                  <a-col :span="5">
                    <a-form-item label="登录账号">
                      <a-input placeholder="请输入登录账号" v-model="queryParam.username"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="4">
                    <a-form-item label="姓名">
                      <a-input placeholder="请输入姓名" v-model="queryParam.realname"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="5">
                    <a-form-item label="手机号码">
                      <a-input placeholder="请输入手机号码查询" v-model="queryParam.phone"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="6">
                    <a-form-item label="身份证号码">
                      <a-input placeholder="请输入身份证号码" v-model="queryParam.idCard"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="4">
                    <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                      <a-button type="primary" @click="searchQuery" slot="enterButton" class="searchBut">查询</a-button>
                      <a-button @click="searchReset" class="resetBut">重置</a-button>
                    </span>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <!-- 查询区域-END -->

            <!-- 操作按钮区域 -->
            <a-row :gutter="15" type="flex" justify="space-between" align="middle">
              <a-col> </a-col>
              <a-col>
                <!-- 操作按钮区域 -->
                <div class="table-operator" style="border-top: 5px" ref="tableOperator">
                  <a-button @click="addNewUser(selectTreeRow)" type="primary" icon="plus" v-has="'user:config:add'"
                    >添加用户</a-button
                  >
                  <a-button
                    @click="currentPassword(selectTreeRow)"
                    type="primary"
                    icon="plus"
                    v-has="'user:yw:password'"
                    >运维密码</a-button
                  >
                  <a-button
                    @click="resetPassword(selectTreeRow)"
                    type="primary"
                    icon="plus"
                    v-has="'user:reset:password'"
                    >重置密码</a-button
                  >
                  <a-button
                    @click="handleChangePassword(selectedTableRow[0])"
                    type="primary"
                    icon="plus"
                    v-has="'user:edit:password'"
                    >修改密码</a-button
                  >
                  <!-- <a-button type="primary" icon="download" @click="handleExportXls('用户信息')">导出</a-button> -->
                  <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
                <a-button type="primary" icon="import">导入</a-button>
              </a-upload> -->
                  <!-- <a-button type="primary" icon="hdd" @click="recycleBinVisible=true">回收站</a-button> -->
                  <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
                <a-menu slot="overlay" @click="handleMenuClick">
                  <a-menu-item key="1">
                    <a-icon type="delete" @click="batchDel"/>
                    删除
                  </a-menu-item>
                  <a-menu-item key="2">
                    <a-icon type="lock" @click="batchFrozen('2')"/>
                    冻结
                  </a-menu-item>
                  <a-menu-item key="3">
                    <a-icon type="unlock" @click="batchFrozen('1')"/>
                    解冻
                  </a-menu-item>
                </a-menu>
                <a-button style="margin-left: 8px">
                  批量操作
                  <a-icon type="down"/>
                </a-button>
              </a-dropdown>
              <j-super-query :fieldList="superQueryFieldList" @handleSuperQuery="handleSuperQuery"/> -->
                </div>
              </a-col>
            </a-row>

            <!-- table区域-begin -->
            <div>
              <!-- <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
                <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项&nbsp;&nbsp;
                <a style="margin-left: 24px" @click="onClearSelected">清空</a>
              </div> -->
              <a-table
                ref="table"
                bordered
                size="middle"
                rowKey="id"
                :columns="tableColumns"
                :dataSource="tableData"
                :pagination="false"
                :loading="loadingTable"
                class="table"
                @change="handleTableChange"
                :row-selection="{ type: 'radio', onChange: rowSelectionChange, selectedRowKeys: selectedRowKeys }"
                :scroll="{ y: scrollHeight }"
              >
                <template slot="avatarslot" slot-scope="text, record">
                  <div class="anty-img-wrap">
                    <a-avatar shape="square" :src="getAvatarView(record.avatar)" icon="user" />
                  </div>
                </template>
                <span slot="status" slot-scope="text, record">
                  <span v-if="record.status == 0" style="display: flex; align-items: center; justify-content: center">
                    <span
                      style="
                        width: 6px;
                        height: 6px;
                        border-radius: 50%;
                        background-color: #f56c6c;
                        display: inline-block;
                        margin-right: 3px;
                      "
                    ></span>
                    <span>无效</span>
                  </span>
                  <span v-if="record.status == 1" style="display: flex; align-items: center; justify-content: center">
                    <span
                      style="
                        width: 6px;
                        height: 6px;
                        border-radius: 50%;
                        background-color: #00a854;
                        display: inline-block;
                        margin-right: 3px;
                      "
                    ></span>
                    <span>有效</span>
                  </span>
                </span>
                <span slot="action" slot-scope="text, record" class="action">
                  <a @click="handleEditUser(record, selectTreeRow)" v-has="'user:config:edit'">编辑</a>
                </span>
              </a-table>

              <!-- table区域-end -->
              <div class="myPagination">
                <el-pagination
                  ref="elpagination"
                  @current-change="changeNum"
                  :current-page="ipagination.current"
                  background
                  :page-size="ipagination.pageSize"
                  layout="prev, pager, next,jumper, slot ,total "
                  :total="ipagination.total"
                >
                  <el-button class="btn-sure" size="mini">确定</el-button>
                </el-pagination>
              </div>
            </div>
            <user-modal
              ref="modalForm"
              @ok="modalFormOk"
              @recreateTableData="recreateTableData"
              @newUserPas="newUserPas"
            ></user-modal>

            <password-modal ref="passwordmodal" @ok="passwordModalOk"></password-modal>

            <!-- 用户回收站 -->
            <!-- <user-recycle-bin-modal :visible.sync="recycleBinVisible" @ok="modalFormOk"/> -->
            <!-- 生成临时密码 -->
            <create-current-password ref="createCurrentPassword"></create-current-password>
          </a-card>
        </div>
        <div v-else>
          <a-empty>
            <span slot="description"> 请先选择一个部门! </span>
          </a-empty>
        </div>
      </a-col>
    </a-row>
  </a-spin>
</template>
  
<script>
import UserModal from './modules/UserModal'
import PasswordModal from './modules/PasswordModal'
import { putAction, getFileAccessHttpUrl } from '@/api/manage'
import { frozenBatch, searchByKeywords, queryDepartTreeList, deleteByDepartId } from '@/api/api'
// import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import JInput from '@/components/jeecg/JInput'
import UserRecycleBinModal from './modules/UserRecycleBinModal'
import JSuperQuery from '@/components/jeecg/JSuperQuery'
import { getAction, postAction, httpAction, deleteAction } from '@/api/manage'
import createCurrentPassword from './modules/createCurrentPassword'
import { filterObj } from '@/utils/util'

export default {
  name: 'UserManagement',
  // mixins: [JeecgListMixin],
  components: {
    UserModal,
    PasswordModal,
    JInput,
    UserRecycleBinModal,
    createCurrentPassword,
    // JSuperQuery
  },
  data() {
    return {
      description: '这是用户管理页面',
      queryParam: {},
      recycleBinVisible: false,
      dropTrigger: '',
      treeData: [],
      selectedKeys: [],
      selectedKeysBefore: [],
      // 展开树数组
      expandedKeys: [],
      selectTreeRow: {},
      selectTreeId: '',
      selectedTableRow: [],
      selectedRowKeys: [],
      firstLoadTree: true,
      //初始化展开各省级单位、市级单位等
      initExpandTree: true,
      isChooseGov: false,
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      columns: [
        {
          title: '用户账号',
          align: 'center',
          dataIndex: 'username',
          width: 120,
          sorter: true,
        },
        {
          title: '用户姓名',
          align: 'center',
          width: 100,
          dataIndex: 'realname',
        },
        {
          title: '头像',
          align: 'center',
          width: 120,
          dataIndex: 'avatar',
          scopedSlots: { customRender: 'avatarslot' },
        },

        {
          title: '性别',
          align: 'center',
          width: 80,
          dataIndex: 'sex_dictText',
          sorter: true,
        },
        {
          title: '生日',
          align: 'center',
          width: 100,
          dataIndex: 'birthday',
        },
        {
          title: '手机号码',
          align: 'center',
          width: 100,
          dataIndex: 'phone',
        },
        {
          title: '部门',
          align: 'center',
          width: 180,
          dataIndex: 'orgCodeTxt',
        },
        {
          title: '负责部门',
          align: 'center',
          width: 180,
          dataIndex: 'departIds_dictText',
        },
        {
          title: '状态',
          align: 'center',
          width: 80,
          dataIndex: 'status_dictText',
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: 170,
        },
      ],
      superQueryFieldList: [
        { type: 'input', value: 'username', text: '用户账号' },
        { type: 'input', value: 'realname', text: '用户姓名' },
        { type: 'select', value: 'sex', text: '性别', dictCode: 'sex' },
      ],
      url: {
        syncUser: '/act/process/extActProcess/doSyncUser',
        list: '/sys/user/list',
        treeList: '/gtSysArea/rootList',
        treeNextList: '/sys/sysDepart/queryValidDeptByAreaId',
        delete: '/sys/user/delete',
        deleteBatch: '/sys/user/deleteBatch',
        exportXlsUrl: '/sys/user/exportXls',
        importExcelUrl: 'sys/user/importExcel',
        tableList: '/sys/user/queryListUserByDepId',
        currentPwd: '/sys/user/optPassword',
        resetPassword: '/sys/user/resetPassword',
        // 获取登录用户的信息
        loginUser: '/sys/sysDepart/getLoginUserDept',
        // 全搜索（树的部门搜索为空且未选中部门）
        checkAllList: '/sys/user/queryByNameAndReal',
        // 树的部门搜索不为空请求数据（未选中部门）
        govCheckTableList: 'sys/user/queryUserTreeUnchecked',
        // 树的部门搜索不为空（未选中部门）
        govCheckList: 'sys/sysDepart/queryDeptByName',
      },
      dataSource: [],
      tableData: [],
      tableColumns: [
        {
          title: '登录账号',
          align: 'left',
          dataIndex: 'username',
        },
        {
          title: '姓名',
          align: 'center',
          dataIndex: 'realname',
        },
        {
          title: '手机号码',
          align: 'center',
          dataIndex: 'phone',
        },
        {
          title: '所在组织',
          align: 'center',
          dataIndex: 'departName',
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          width: '150px',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      aSpinLoading: '',
      spinning: false,
      loadingTable: false,
      treeLoading: false,
      /* 查询折叠 */
      toggleSearchStatus: false,
      // qdId是前端新增的字段，用于生成唯一键
      replaceFields: { children: 'children', title: 'name', key: 'qdId' },
      // 表格高度
      scrollHeight: 200,
      // 查询表格,为1true表示全查询,false表示不是全查询
      isCheckAll: false,
      // 部门搜索为空时复原原始搜索
      treeDataRecover: [],
      // 树状搜索条件
      treeSearch: '',
      // 树状搜索条件的部门ID合集
      treeSearchGovArr: [],
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  mounted() {
    let _this = this
    _this.onLoadTreeData()
    // 根据浏览器大小确定表格大小
    window.onresize = () => {
      _this.tableHeightResize()
    }
    _this.ipagination.pageSize = 30
  },
  methods: {
    tableHeightResize() {
      /* let _this = this;
          if(_this.$refs.searchArea && _this.$refs.tableOperator){
            _this.scrollHeight = _this.$refs.tableArea.$el.offsetHeight - _this.$refs.searchArea.offsetHeight - _this.$refs.tableOperator.offsetHeight - 48 - 50 - 80;
          }else if(_this.$refs.searchArea){
            _this.scrollHeight = _this.$refs.tableArea.$el.offsetHeight - _this.$refs.searchArea.offsetHeight - 5  - 48 - 50 - 80;
          }else if(_this.$refs.tableOperator){
            _this.scrollHeight = _this.$refs.tableArea.offsetHeight - _this.$refs.tableOperator.offsetHeight  - 48 - 50 - 80;
          }else{
            _this.scrollHeight = _this.$refs.tableArea.$el.offsetHeight - 48;
          } */
    },
    getAvatarView: function (avatar) {
      return getFileAccessHttpUrl(avatar)
    },
    batchFrozen: function (status) {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return false
      } else {
        let ids = ''
        let that = this
        let isAdmin = false
        that.selectionRows.forEach(function (row) {
          if (row.username == 'admin') {
            isAdmin = true
          }
        })
        if (isAdmin) {
          that.$message.warning('管理员账号不允许此操作,请重新选择！')
          return
        }
        that.selectedRowKeys.forEach(function (val) {
          ids += val + ','
        })
        that.$confirm({
          class: 'delete_qx',
          title: '确认操作',

          content: '是否' + (status == 1 ? '解冻' : '冻结') + '选中账号?',
          onOk: function () {
            frozenBatch({ ids: ids, status: status }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          },
        })
      }
    },
    handleMenuClick(e) {
      if (e.key == 1) {
        this.batchDel()
      } else if (e.key == 2) {
        this.batchFrozen(2)
      } else if (e.key == 3) {
        this.batchFrozen(1)
      }
    },
    handleFrozen: function (id, status, username) {
      let that = this
      //TODO 后台校验管理员角色
      if ('admin' == username) {
        that.$message.warning('管理员账号不允许此操作！')
        return
      }
      frozenBatch({ ids: id, status: status }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleChangePassword(record) {
      let _this = this
      if (_this.selectedTableRow.length == 0) {
        _this.$message.warning('请选择一条用户数据')
      } else {
        this.$confirm({
          class: 'delete_qx',
          title: '提示',
          content: (
            <div>
              <div>
                <span style="color:red">此操作将修改密码，</span>
                <span>修改后原密码将会失效</span>
              </div>
            </div>
          ),
          okText: '继续',
          cancelText: '取消',
          onOk() {
            _this.createHandleChangePassword(record)
          },
          onCancel() {
            _this.$destroyAll()
          },
        })
      }
    },
    createHandleChangePassword(record) {
      this.$refs.passwordmodal.show(record.username)
    },
    passwordModalOk() {
      //TODO 密码修改完成 不需要刷新页面，可以把datasource中的数据更新一下
    },
    onSearch(value) {
      let that = this
      if (value) {
        searchByKeywords({ keyWord: value }).then((res) => {
          if (res.success) {
            that.treeData = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.treeData.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    onSearchDepart(value) {
      let _this = this
      _this.treeSearch = value.trim()
      if (value.trim() != '') {
        _this.treeLoading = true
        getAction(_this.url.govCheckList, { departSimpleName: value.trim() }).then((res) => {
          console.log(res)
          if (res.code == 200) {
            _this.tableData = []
            _this.queryParam = {}
            _this.selectedKeys = []
            _this.selectTreeRow = {}
            _this.selectedTableRow = []
            res.result.forEach((item) => {
              // item['name'] = item['departSimpleName'];
              if (item['departSimpleName']) {
                item['name'] = item['departSimpleName']
              } else {
                item['name'] = item['departName']
              }
              item['qdId'] = item['id'] + item['departName']
              item['canClick'] = true
              item['isLeaf'] = true
            })
            _this.treeData = res.result
            _this.loadDataTable('', 1)
          } else {
            _this.$message.error(res.message)
          }
          _this.treeLoading = false
        })
      } else {
        _this.tableData = []
        _this.queryParam = {}
        _this.selectedKeys = []
        _this.selectTreeRow = {}
        _this.selectedTableRow = []
        _this.treeData = _this.treeDataRecover
        _this.loadDataTable('', 1)
        _this.$forceUpdate()
      }
    },
    // 懒加载
    onLoadTreeData(treeNode) {
      var _this = this
      console.log(45665645645)
      _this.treeLoading = true
      if (_this.firstLoadTree) {
        console.log('1233213321')
        getAction(this.url.treeList, {}).then((res) => {
          if (res.code == 200) {
            let data = res.result
            data.forEach((item, index) => {
              item['qdId'] = item['id'] + item['departName']
            })
            // _this.treeData = data;
            // console.log(_this.treeData);
            let result = JSON.parse(JSON.stringify(data))
            // _this.onLoadTreeData();
            // let expandIdArr = [];
            // _this.expandedKeys = ['81','83'];
            console.log(result)
            _this.onLoadTreeDataLoad(result)
          } else {
            _this.$message.error('初始化区划树失败')
          }
          _this.treeLoading = false
          _this.firstLoadTree = false
        })
      } else {
        return new Promise((resolve) => {
          if (treeNode.dataRef.children) {
            _this.treeLoading = false
            resolve()
            return
          }
          if (treeNode.dataRef.areaCode) {
            getAction(this.url.treeList, { parentId: treeNode.dataRef.id }).then((res) => {
              if (res.code == 200) {
                treeNode.dataRef.children = res.result
                res.result.forEach((item) => {
                  if (item['areaCode']) {
                    if (item['areaShortName']) {
                      item['name'] = item['areaShortName']
                    } else {
                      item['name'] = item['areaName']
                    }
                  } else {
                    if (item['departSimpleName']) {
                      item['name'] = item['departSimpleName']
                    } else {
                      item['name'] = item['departName']
                    }
                  }
                })
                if (treeNode.dataRef.areaLevel == '2') {
                  treeNode.dataRef.children.unshift({
                    name: '省级单位',
                    curAreaId: treeNode.dataRef.id,
                  })
                  if (_this.initExpandTree) {
                    treeNode.dataRef.children[0]['qdId'] = 'initProvince'
                  }
                } else if (treeNode.dataRef.areaLevel == '3') {
                  treeNode.dataRef.children.unshift({
                    name: '市级单位',
                    curAreaId: treeNode.dataRef.id,
                  })
                  if (_this.initExpandTree) {
                    treeNode.dataRef.children[0]['qdId'] = 'initCity'
                  }
                } else if (treeNode.dataRef.areaLevel == '4') {
                  treeNode.dataRef.children.unshift({
                    name: '区级单位',
                    curAreaId: treeNode.dataRef.id,
                  })
                  if (_this.initExpandTree) {
                    treeNode.dataRef.children[0]['qdId'] = 'initArea'
                  }
                } else if (treeNode.dataRef.areaLevel == '5') {
                  treeNode.dataRef.children.unshift({
                    name: '乡镇单位',
                    curAreaId: treeNode.dataRef.id,
                  })
                  if (_this.initExpandTree) {
                    treeNode.dataRef.children[0]['qdId'] = 'initTown'
                  }
                }
                _this.treeData = [..._this.treeData]
                resolve()
                if (_this.initExpandTree) {
                  _this.expandedKeys.push(treeNode.dataRef.children[0]['qdId'])
                }
              } else {
                _this.$message.error('请求失败')
              }
              _this.treeLoading = false
              _this.firstLoadTree = false
            })
          } else {
            getAction(this.url.treeNextList, { areaId: treeNode.dataRef.curAreaId }).then((res) => {
              if (res.code == 0) {
                res.result.forEach((item) => {
                  // item['areaNameCurrent'] = item['departName'];
                  // if(item['isLeaf'] == 'true'){
                  item['isLeaf'] = false
                  item['qdId'] = item['id'] + item['departName']
                  // }
                })
                treeNode.dataRef.children = res.result
                treeNode.dataRef.children.forEach((item) => {
                  if (item.children && item.children.length != 0) {
                    item.children.forEach((itemChild) => {
                      itemChild['curAreaId'] = treeNode.dataRef.curAreaId
                      itemChild['isLeaf'] = true
                      itemChild['canClick'] = true
                      itemChild['qdId'] = itemChild['id'] + itemChild['departName']
                      if (itemChild['departSimpleName']) {
                        itemChild['name'] = itemChild['departSimpleName']
                      } else {
                        itemChild['name'] = itemChild['departName']
                      }
                    })
                  } else {
                    item['isLeaf'] = true
                  }
                  item['canClick'] = true
                  if (item['departSimpleName']) {
                    item['name'] = item['departSimpleName']
                  } else {
                    item['name'] = item['departName']
                  }
                })
                let userInfo = {}
                if (_this.initExpandTree) {
                  // 初始化获取用户信息
                  getAction(_this.url.loginUser, {}).then((res) => {
                    if (res.code == 0) {
                      let userInfo = res.result
                      if (userInfo['status'] == '1') {
                        userInfo['qdId'] = res.result['id'] + res.result['departName']
                        _this.selectedKeys = [userInfo['qdId']]
                        _this.selectedKeysBefore = _this.selectedKeys
                        _this.selectTreeRow = userInfo
                        _this.selectAreaId = userInfo['id']
                        // 判断是不是二级部门的数据，如果是，则展开其一级部门
                        treeNode.dataRef.children.forEach((item) => {
                          if (item.children && item.children.length != 0) {
                            item.children.forEach((itemChild) => {
                              if (itemChild['qdId'] == userInfo['qdId']) {
                                _this.expandedKeys.push(item['qdId'])
                              }
                            })
                          }
                        })
                        _this.loadDataTable(userInfo['id'])
                      } else {
                        _this.$message.error('该用户已失效')
                      }
                    } else {
                      _this.$message.error('获取用户信息失败')
                    }
                    _this.treeData = [..._this.treeData]
                    _this.initExpandTree = false
                    _this.treeLoading = false
                    resolve()
                  })
                } else {
                  _this.treeData = [..._this.treeData]
                  _this.treeLoading = false
                  resolve()
                }
              } else {
                _this.$message.error('请求失败')
              }
              _this.firstLoadTree = false
            })
          }
        })
      }
    },
    // 初始化展开树
    onLoadTreeDataLoad(data1) {
      let _this = this
      let expandIdArr = []
      let data = JSON.parse(JSON.stringify(data1))
      for (let x = 0; x < data.length; x++) {
        if (data[x]['children'] && data[x]['children'].length != 0) {
          cycChildren(data[x]['children'])
        }
        data[x]['qdId'] = data[x]['id'] + data[x]['departName']
        if (data[x]['areaCode']) {
          if (data[x]['areaShortName']) {
            data[x]['name'] = data[x]['areaShortName']
          } else {
            data[x]['name'] = data[x]['areaName']
          }
        } else {
          if (data[x]['departSimpleName']) {
            data[x]['name'] = data[x]['departSimpleName']
          } else {
            data[x]['name'] = data[x]['departName']
          }
        }
        expandIdArr.push(data[x]['qdId'])
      }
      function cycChildren(childData) {
        for (let x = 0; x < childData.length; x++) {
          if (childData[x]['children'] && childData[x]['children'].length != 0) {
            cycChildren(childData[x]['children'])
          }
          childData[x]['qdId'] = childData[x]['id'] + childData[x]['departName']
          expandIdArr.push(childData[x]['qdId'])
          if (childData[x]['areaCode']) {
            if (childData[x]['areaShortName']) {
              childData[x]['name'] = childData[x]['areaShortName']
            } else {
              childData[x]['name'] = childData[x]['areaName']
            }
          } else {
            if (childData[x]['departSimpleName']) {
              childData[x]['name'] = childData[x]['departSimpleName']
            } else {
              childData[x]['name'] = childData[x]['departName']
            }
          }
        }
      }
      _this.expandedKeys = expandIdArr
      _this.treeData = data
      _this.treeDataRecover = data
    },
    // 点击文本触发
    selectTree(selectedKeys, treeNode) {
      let _this = this
      if (treeNode.node.dataRef['canClick']) {
        if (selectedKeys.length == 0) {
          // _this.selectedKeys = treeNode.node;
          _this.selectedKeys = _this.selectedKeysBefore
        } else {
          _this.isChooseGov = true
          _this.selectTreeRow = treeNode.node.dataRef
          _this.selectAreaId = treeNode.node.dataRef.id
          _this.selectedKeys = selectedKeys
          _this.selectedKeysBefore = selectedKeys
          _this.selectedTableRow = []
          _this.selectedRowKeys = []
          // treeNode.node.dataRef.id,
          // var params = this.getQueryParams();
          // params.depId = treeNode.node.dataRef.id;
          // console.log(params);
          _this.queryParam = {}
          // _this.isCheckAll = false;
          this.loadDataTable(treeNode.node.dataRef.id, 1)
        }
      }
    },
    loadDataTable(id, arg) {
      let _this = this
      // if(_this.url.list){
      //   this.$message.error("请设置url.list属性!")
      //   return
      // }else{
      _this.loadingTable = true
      if (arg == 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      params.depId = id
      _this.isChooseGov = true
      // 树是否选中
      // 未选中
      if (JSON.stringify(_this.selectTreeRow) == '{}') {
        // 树有搜索条件
        if (_this.treeSearch != '') {
          params['departSimpleName'] = _this.treeSearch
          getAction(_this.url.govCheckTableList, params).then((res) => {
            if (res.code == 200) {
              this.tableData = res.result.records || res.result
              if (res.result.total) {
                this.ipagination.total = res.result.total
              } else {
                this.ipagination.total = 0
              }
              // this.dataSource(item => {
              //   item['departName'] = _this.selectTreeRow['departName']
              // })
              this.tableHeightResize()
            } else {
              _this.$message.error('获取部门失败')
            }
            _this.loadingTable = false
          })
        } else {
          getAction(_this.url.checkAllList, params).then((res) => {
            if (res.code == 200) {
              this.tableData = res.result.records || res.result
              if (res.result.total) {
                this.ipagination.total = res.result.total
              } else {
                this.ipagination.total = 0
              }
              // this.dataSource(item => {
              //   item['departName'] = _this.selectTreeRow['departName']
              // })
              this.tableHeightResize()
            } else {
              _this.$message.error('获取部门失败')
            }
            _this.loadingTable = false
          })
        }
      } else {
        //选中
        postAction(_this.url.tableList, params).then((res) => {
          if (res.code == 0) {
            this.tableData = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // this.dataSource(item => {
            //   item['departName'] = _this.selectTreeRow['departName']
            // })
            this.tableHeightResize()
          } else {
            _this.$message.error('获取部门失败')
          }
          _this.loadingTable = false
        })
      }

      // if(_this.isCheckAll){
      //   getAction(_this.url.checkAllList,params).then(res => {
      //     if(res.code == 200){
      //       this.tableData = res.result.records||res.result;
      //       if(res.result.total)
      //       {
      //         this.ipagination.total = res.result.total;
      //       }else{
      //         this.ipagination.total = 0;
      //       }
      //       // this.dataSource(item => {
      //       //   item['departName'] = _this.selectTreeRow['departName']
      //       // })
      //       this.tableHeightResize();
      //     }else{
      //       _this.$message.error('获取部门失败')
      //     };
      //     _this.loadingTable = false;
      //   })
      // }else{
      //   getAction(_this.url.tableList,params).then(res => {
      //     if(res.code == 0){
      //       this.tableData = res.result.records||res.result;
      //       if(res.result.total)
      //       {
      //         this.ipagination.total = res.result.total;
      //       }else{
      //         this.ipagination.total = 0;
      //       }
      //       // this.dataSource(item => {
      //       //   item['departName'] = _this.selectTreeRow['departName']
      //       // })
      //       this.tableHeightResize();
      //     }else{
      //       _this.$message.error('获取部门失败')
      //     };
      //     _this.loadingTable = false;
      //   })
      // }

      // }
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      if (JSON.stringify(this.selectTreeRow) == '{}') {
        this.loadDataTable('')
      } else {
        this.loadDataTable(this.selectAreaId)
      }
    },
    handleEditUser(record, selectTreeRow) {
      this.$refs.modalForm.edit(record, selectTreeRow)
      this.$refs.modalForm.title = '编辑用户信息'
      this.$refs.modalForm.disableSubmit = false
    },
    addNewUser(record) {
      // console.log(record)
      if (this.selectedKeys.length == 0) {
        this.$message.warning('请选择一个部门')
      } else if (record['parentId']) {
        this.$message.warning('二级部门暂不支持添加用户，用户可新增在一级部门')
      } else {
        this.$refs.modalForm.add(record, this.selectTreeRow)
        this.$refs.modalForm.title = '新增用户信息'
        this.$refs.modalForm.disableSubmit = false
      }
    },
    currentPassword(record) {
      let _this = this
      if (_this.selectedTableRow.length == 0) {
        _this.$message.warning('请选择一条用户数据')
      } else {
        this.$confirm({
          class: 'delete_qx',
          title: '提示',
          content: (
            <div>
              <div>
                <span style="color:red">此操作将生成临时密码，</span>
                <span>一小时后失效</span>
              </div>
            </div>
          ),
          okText: '继续',
          cancelText: '取消',
          onOk() {
            _this.createCurrentPassword()
          },
          onCancel() {
            _this.$destroyAll()
          },
        })
      }
    },
    createCurrentPassword() {
      let _this = this
      _this.spinning = true
      _this.aSpinLoading = '运维密码生成中'
      postAction(_this.url.currentPwd, _this.selectedTableRow[0]).then((res) => {
        if (res.code == '0') {
          let username = _this.selectedTableRow['0']['username']
          _this.$destroyAll()
          this.$confirm({
            class: 'delete_qx',
            title: '运维密码生成成功！',
            content: (
              <div>
                <div>{username}</div>
                <div>{res.result}</div>
              </div>
            ),
            okText: '确定',
            type: 'success',
            icon: 'check-circle',
          })
        } else {
          _this.$message.error(res.message)
          _this.$destroyAll()
        }
        _this.spinning = false
      })
    },
    resetPassword(record) {
      let _this = this
      if (_this.selectedTableRow.length == 0) {
        _this.$message.warning('请选择一条用户数据')
      } else {
        this.$confirm({
          class: 'delete_qx',
          title: '提示',
          content: (
            <div>
              <div>
                <span style="color:red">此操作将重置密码，</span>
                <span>重置后原密码将会失效</span>
              </div>
            </div>
          ),
          okText: '继续',
          cancelText: '取消',
          onOk() {
            _this.createResetPassword()
          },
          onCancel() {
            _this.$destroyAll()
          },
        })
      }
    },
    createResetPassword() {
      let _this = this
      _this.spinning = true
      _this.aSpinLoading = '密码重置中'
      putAction(this.url.resetPassword, _this.selectedTableRow[0]).then((res) => {
        this.$confirm({
          class: 'delete_qx',
          title: '密码重置成功！',
          content: (
            <div>
              <div>重置密码为:</div>
              <div>{res.result}</div>
            </div>
          ),
          okText: '确定',
          type: 'success',
          icon: 'check-circle',
        })
        _this.spinning = false
      })
    },
    loadTree() {
      let _this = this
      _this.treeLoading = true
      getAction(this.url.treeList, {}).then((res) => {
        if (res.code == 0) {
          _this.treeData = res.result
        } else {
          _this.$message.error('初始化区划树失败')
        }
        _this.treeLoading = false
      })
    },
    rowSelectionChange(selectedRowKeys, selectedRows) {
      let _this = this
      _this.selectedTableRow = selectedRows
      _this.selectedRowKeys = selectedRowKeys
    },
    recreateTableData() {
      let _this = this
      // this.ipagination.current = 1;
      _this.loadingTable = true
      if (_this.selectTreeRow.id) {
        var params = this.getQueryParams() //查询条件
        params.depId = _this.selectTreeRow.id
        // console.log(params)
        if (_this.isCheckAll) {
          getAction(_this.url.checkAllList, params).then((res) => {
            if (res.code == 200) {
              this.tableData = res.result.records || res.result
              if (res.result.total) {
                this.ipagination.total = res.result.total
              } else {
                this.ipagination.total = 0
              }
              // this.dataSource(item => {
              //   item['departName'] = _this.selectTreeRow['departName']
              // })
              this.tableHeightResize()
            } else {
              _this.$message.error('获取部门失败')
            }
            _this.loadingTable = false
          })
        } else {
          postAction(_this.url.tableList, params).then((res) => {
            if (res.code == 0) {
              this.tableData = res.result.records || res.result
              if (res.result.total) {
                this.ipagination.total = res.result.total
              } else {
                this.ipagination.total = 0
              }
            } else {
              _this.$message.error('表格加载失败')
            }
            _this.loadingTable = false
          })
        }
      }
    },
    newUserPas(val) {
      let _this = this
      this.$confirm({
        class: 'delete_qx',
        title: '用户创建成功！',
        content: (
          <div>
            <div>
              <span>姓名:</span>
              <span>{val['姓名']}</span>
            </div>
            <div>
              <span>账号:</span>
              <span>{val['账号']}</span>
            </div>
            <div>
              <span>默认密码:</span>
              <span>{val['密码']}</span>
            </div>
            <div style="color:red">*为数据安全，请尽快登录变更密码</div>
          </div>
        ),
        okText: '确定',
        type: 'success',
        icon: 'check-circle',
      })
    },
    searchQuery() {
      // this.isCheckAll = true;
      if (JSON.stringify(this.selectTreeRow) == '{}') {
        this.loadDataTable('', 1)
      } else {
        this.loadDataTable(this.selectAreaId, 1)
      }
    },
    searchReset() {
      this.queryParam = {}
      this.selectedTableRow = []
      this.selectedRowKeys = []
      // this.isCheckAll = false;
      if (JSON.stringify(this.selectTreeRow) == '{}') {
        this.loadDataTable('', 1)
      } else {
        this.loadDataTable(this.selectAreaId, 1)
      }
    },
    getQueryField() {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function (value) {
        str += ',' + value.dataIndex
      })
      return str
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.loadDataTable(this.selectAreaId, 1)
      //清空列表选中
      this.onClearSelected()
    },
    changeNum(val) {
      // console.log('2');
      this.ipagination.current = val
      this.loadDataTable(this.selectAreaId, 1)
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/common.less';
@import '~@assets/less/shaDow.less';
@import '~@assets/less/tableCommon.less';

// 搜索框
.search_box {
  ::v-deep .ant-input-group .ant-input {
    height: 38px;
    line-height: 38px;
    font-size: 14px;
    border-radius: 2px;
  }

  .searchBut {
    
    border-radius: 0px 2px 2px 0px;
    opacity: 1;
    

    height: 38px;
    line-height: 38px;
    font-size: 14px;
  }

  .resetBut {
    width: 60px;
    height: 38px;
    line-height: 38px;
    background: #dbdbdb;
    border-radius: 2px;
    color: #000;
    opacity: 1;
    padding: 0;
    border: 1px solid #b6b6b6;
  }
}

.ant-row > .ant-col:last-child {
  .table-page-search-submitButtons {
    & > button:first-child {
      margin-right: 20px;
    }
  }
}

// 按钮
.table-operator {
  .ant-btn {
    // width: 68px;
    height: 38px;

    line-height: 38px;
    
    border-radius: 2px;
    opacity: 1;
    
    font-size: 14px;
    font-family: Source Han Sans CN-Regular, Source Han Sans CN;
    font-weight: 400;
    
    margin: 0 16px 8px 0;
    padding: 0 10px;
  }
  .ant-btn:last-child{
     margin: 0 0 8px 0;
  }
}

// 分页器
.myPagination {
  margin-top: 40px;
  display: flex;
  justify-content: end;

  ::v-deep .el-pagination {
    font-weight: 600;

    .btn-sure {
      background: #dbdbdb;
      border-radius: 2px;
      opacity: 1;
      border: 1px solid #b6b6b6;
      padding: 0;
      color: #000;
      margin: 0 20px 0 10px;
      width: 50px;
    }

    .el-select .el-input .el-input__inner {
      color: #000;
      font-size: 14px;
      padding-right: 17px;
      font-weight: 400;
      border-radius: 2px;
    }

    .el-pager li {
      font-size: 16px;
      color: #888888;
      width: 34px;

      &:hover {
        opacity: 0.9;
      }
    }

    .el-pagination span:not([class*='suffix']) {
      font-size: 14px;
      color: #888888;
    }

    .el-pager li:not(.disabled).active {
      color: #fff;
    }
  }

  .ant-pagination {
    color: #888888;
  }

  ::v-deep .ant-select-selection--single {
    height: 28px !important;
  }

  ::v-deep .ant-select-selection__rendered {
    line-height: 28px !important;
  }

  ::v-deep .ant-pagination.mini .ant-pagination-options-quick-jumper input {
    height: 28px;
  }

  ::v-deep .ant-pagination.mini .ant-pagination-item {
    font-size: 16px;
    height: 28px;
    line-height: 28px;
    width: 34px;
  }
}

::v-deep ::-webkit-scrollbar-thumb {
  
  border-radius: 9px 9px 9px 9px;
}

.action a {
  
}

/deep/.ant-tree li .ant-tree-node-content-wrapper.ant-tree-node-selected {
  
}

/deep/ .ant-tree li .ant-tree-node-content-wrapper:hover {
  
}

::v-deep .ant-table-tbody > tr:hover > td {
  background: #f2f5f965 !important;
}
</style>

<style scoped>
@import '~@assets/less/modal.less';
@import '~@assets/less/common.less';

/* .treeArea {
  min-height: 680px;
} */
.tableArea {
  background-color: #ffffff;
  padding: 24px !important;
}

.aCardTree {
  height: 100%;
  /* height: 910px; */
  /* overflow-y: auto; */
  /* overflow-x: hidden; */
}

.spinOuter {
  height: 100%;
}

.spinOuter >>> .ant-spin-container {
  height: 100%;
}

.aCardTree >>> .ant-card-body {
  padding: 15px;
  height: 100%;
  overflow: hidden;
}

.aTable >>> .ant-card-body {
  padding: 0;
}
</style>