<template>
    <a-modal
    :title="title"
    :width="1100"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

        <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"
                          />
                        </span>
                      </a-dropdown>
                    </template>
                  </a-col>
                </a-spin>
              </div>
            </a-card>
          </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>
                <!-- 查询区域 -->
                <div style="background-color: rgba(230, 247, 255, 1) !important;border: 1px solid #e8e8e8 !important;padding: 2px !important;">
                  <a-form layout="inline" @keyup.enter.native="searchQuery">
                    <a-row :gutter="24">
                      <a-col :span="10" style="margin-left: 20px;">
                        <a-form-item label="事项类型">
                          <a-input  placeholder="请输入事项类型" v-model="queryParam.eventType"></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="10">
                        <a-form-item label="事项名称">
                          <a-input placeholder="请输入姓名" v-model="queryParam.eventName"></a-input>
                        </a-form-item>
                      </a-col>
                      <a-col :span="2">
                        <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                          <a-button style="margin-top: 2px;" type="primary" @click="searchQuery" slot="enterButton" class="searchBut">查询</a-button>
                        </span>
                      </a-col>
                    </a-row>
                  </a-form>
                </div>
                <!-- 查询区域-END -->

                <!-- 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"
				      size="middle"
				      bordered
				      rowKey="id"
				      :columns="columns"
				      :dataSource="tableData"
				      :pagination="ipagination"
				      :loading="loading"
				      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
				      @change="handleTableChange"
				    >
                    <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>
              </div>
              </a-card>
            </div>
            <div v-else>
              <a-empty>
                <span slot="description"> 请先选择一个部门! </span>
              </a-empty>
            </div>
          </a-col>
        </a-row>
      </a-spin>

    </a-modal>
</template>

<script>
  import pick from 'lodash.pick'
  import { httpAction, getAction} from '@/api/manage'
  import { duplicateCheck } from '@/api/api'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'

  let validatorCodeTimer = null

  export default {
    // name: 'SysPositionModal',
    mixins: [JeecgListMixin],
    components: { JDictSelectTag },
    data() {
      return {
            title: null,
            visible: false,
            confirmLoading: false,
            description: '这是用户管理页面',
            queryParam: {},
            recycleBinVisible: false,
            dropTrigger: '',
            treeData: [],
            selectedKeys: [],
            selectedKeysBefore: [],
            // 展开树数组
            expandedKeys: [],
            tableData: [],
            selectTreeRow: {},
            selectTreeId: '',
            selectedTableRow: [],
            firstLoadTree: true,
            //初始化展开各省级单位、市级单位等
            initExpandTree: true,
            isChooseGov: true,
            columns: [
              {
                title: '事项名称',
                align: 'center',
                dataIndex: 'eventName',
                sorter: true,
              },
              {
                title: '实施主体',
                align: 'center',
                dataIndex: 'departName',
              },
              {
                title: '事项类型',
                align: 'center',
                dataIndex: 'evtentType',
              },
              {
                title: '权利来源',
                align: 'center',
                width: 120,
                dataIndex: 'sourceOfRights',
              }
            ],
            url: {
              list: '/ai/ysDirectory/page',
              treeList: '/sys/sysDepart/queryTreeListTest',
            },
            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: [],
      }
    },
    created() {
    	
    },
    methods: {
      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.treeList, { departSimpleName: value.trim() }).then((res) => {
              console.log(res)
              if (res.code == 0) {
                _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.loadData('', 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.loadData('', 1)
            _this.$forceUpdate()
          }
        },
        getTreeData(){
        	getAction(this.url.treeList, {},"get").then((res) => {
                console.log("------res------->",res)
              if (res.code == 0) {
                let data = res.result
                console.log("------data------->",data)
                data.forEach((item, index) => {
                  item['qdId'] = item['id'] + item['departName']
                })
                let result = JSON.parse(JSON.stringify(data))
                console.log("------------->",result)
                this.treeData = result;
              } else {
                this.$message.error('初始化区划树失败')
              }
              this.treeLoading = false
              this.firstLoadTree = false
            })
        },
      // 懒加载
      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.loadData(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
                })
              }
            })
          }
        },
      selectTree(selectedKeys, treeNode) {
        let _this = this
        
        //if (treeNode.node.dataRef['canClick']) {
          if (selectedKeys.length == 0) {
            _this.selectedKeys = _this.selectedKeysBefore
          } else {
          	console.log(treeNode.node.dataRef.id);
            _this.isChooseGov = true
            _this.selectTreeRow = treeNode.node.dataRef
            _this.selectAreaId = treeNode.node.dataRef.id
            _this.selectedKeys = selectedKeys
            _this.selectedKeysBefore = selectedKeys
            _this.selectedTableRow = []
            _this.selectedRowKeys = []
            _this.queryParam = {"orgId":treeNode.node.dataRef.id,"delFlag":0}
            console.log("-----------dddd------",treeNode.node.dataRef.id);
            this.loadData(1);
          }
        //}
      },
      add() {
        this.edit({})
      },
      edit() {
        this.visible = true
        this.getTreeData();
        this.loadData(1);
      },
      close() {
        this.$emit('close')
        this.visible = false
        //this.$refs.form.resetFields();
      },
      handleOk() {
	      if(!this.selectedRowKeys.length){
	      	this.$message.warning("请至少选择一条数据");
	      	return;
	      }
        httpAction("/ai/preExaminationMatters/add", {ids:this.selectedRowKeys.join(",")}, "post").then((res) => {
              if (res.success) {
                this.$message.success(res.message)
                console.log(123)
                this.$emit('ok')
              } else {
                this.$message.warning(res.message)
              }
            }).finally(() => {
              this.confirmLoading = false
              this.close()
            })
      },
      handleCancel() {
        this.close()
      },


    }
  }
</script>

<style lang="less" scoped>
.ant-modal-footer  {
     text-align: center !important;
}
.ant-modal-confirm .ant-modal-confirm-btns {
  text-align: center !important;
}

div.ant-modal-footer {
  text-align: center !important;
}
</style>
