<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper search_box">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :span="5">
            <a-form-item label="行政区划名称">
              <j-input placeholder="请输入行政区划名称" v-model="queryParam.areaName"></j-input>
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="区划编码">
              <j-input placeholder="请输入区划编码" v-model="queryParam.areaCode"></j-input>
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="是否特殊区划">
              <j-dict-select-tag
                type="list"
                v-model="queryParam.isSpecial"
                placeholder="请选择是否特殊区划"
                dictCode="is_special"
              />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="状态">
              <j-dict-select-tag
                type="list"
                v-model="queryParam.status"
                placeholder="请选择行政区划状态"
                dictCode="area_status"
              />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button class="searchBut" type="primary" @click="searchQuery">查询</a-button>
               <a-button @click="searchReset" class="resetBut">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- table区域-begin -->
    <div
      :class="{ paginationShow: showPagination, showUpperSearchHeight: !toggleSearchStatus }"
      class="tableHeight"
      ref="tableHeight"
    >
      <!-- <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div> -->

      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        class="j-table-force-nowrap"
        :pagination="false"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :bordered="true"
        :expandedRowKeys="expandedRowKeys"
        @change="handleTableChange"
        @expand="handleExpand"
        v-bind="tableProps"
        :expandIcon="expandIcon"
        :scroll="{ x: 550, y: scrollHeight }"
      >
        <span slot="areaName" slot-scope="text, record">
          <span v-if="record.children">{{ record.areaName }}</span>
          <span v-else class="noChildNodes">{{ record.areaName }}</span>
        </span>
        <!-- <template slot="imgSlot" slot-scope="text" >
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template> -->
        <span slot="parentAreaName" slot-scope="text, record">
          <span v-if="record.areaCode == '510000000000'">-</span>
          <span v-else>{{ record.parentAreaName }}</span>
        </span>
        <span slot="action" slot-scope="text, record" v-show="record.areaCode != '510000000000'">
          <a @click="handleCheckRow(record)">查看</a>
          <a-divider type="vertical" />
          <a @click="handleEditRow(record)">编辑</a>
          <a-divider type="vertical" v-show="record.areaLevel < 5" />
          <a @click="handleAddChild(record)" v-show="record.areaLevel < 5">添加下级</a>
          <!-- <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item v-show="record.areaLevel < 5"> 
              </a-menu-item>
              <a-menu-item v-show="record.areaCode != '510000' || record.areaCode != '510000000000'">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteNode(record.id)" placement="topLeft">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown> -->
        </span>
        <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>
      </a-table>
      <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>

    <gtSysArea-modal ref="modalForm" @ok="modalFormOk"></gtSysArea-modal>
  </a-card>
</template>

<script>
import { getAction, deleteAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import GtSysAreaModal from './modules/GtSysAreaModal'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { filterObj } from '@/utils/util'

export default {
  name: 'GtSysAreaList',
  mixins: [JeecgListMixin],
  components: {
    GtSysAreaModal,
  },
  data() {
    return {
      description: 'gt_sys_area管理页面',
      // 表头
      columns: [
        {
          title: '行政区划名称',
          align: 'left',
          width: '35%',
          dataIndex: 'areaName',
          scopedSlots: { customRender: 'areaName' },
        },
        {
          title: '区划编码',
          align: 'center',
          // width:150,
          width: '15%',
          dataIndex: 'areaCode',
        },
        {
          title: '上级行政区划',
          align: 'center',
          // width:150,
          width: '20%',
          dataIndex: 'parentAreaName',
          scopedSlots: { customRender: 'parentAreaName' },
        },
        {
          title: '是否特殊区划',
          align: 'center',
          // width:150,
          width: '15%',
          dataIndex: 'isSpecial',
          customRender: function (text) {
            if (text == 0) {
              return '否'
            } else if (text == 1) {
              return '是'
            } else {
              return ''
            }
          },
        },
        {
          title: '状态',
          align: 'center',
          // width:150,
          width: '15%',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 230,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        // list: "/gtSysArea/rootList",
        list: '/gtSysArea/allList',
        searchList: '/gtSysArea/queryByNameAndCode',
        childList: '/gtSysArea/rootList',
        getChildListBatch: '/gtSysArea/getChildListBatch',
        delete: '/gtSysArea/delete',
        deleteBatch: '/gtSysArea/deleteBatch',
        exportXlsUrl: '/gtSysArea/exportXls',
        importExcelUrl: 'gtSysArea/importExcel',
      },
      expandedRowKeys: ['81'],
      hasChildrenField: 'hasChild',
      pidField: 'parentId',
      dictOptions: {},
      loadParent: false,
      superFieldList: [],
      defaultExpandedRowKeys: [],
      firstLoadTable: true,
      // 是否展示分页
      showPagination: true,
      // 滚动高度
      scrollHeight: 0,
    }
  },
  created() {
    this.getSuperFieldList()
    // this.loadData();
  },
  mounted() {
    let _this = this
    // 根据浏览器大小确定表格大小
    /* window.onresize = () => {
        _this.tableHeightResize();
      }; */
    _this.ipagination.pageSize = 30
  },
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        // rowSelection: {
        //   selectedRowKeys: _this.selectedRowKeys,
        //   onChange: (selectedRowKeys) => _this.selectedRowKeys = selectedRowKeys
        // }
      }
    },
  },
  methods: {
    /* tableHeightResize(){
        let _this = this;
        if(_this.$refs.searchArea){
          _this.scrollHeight = _this.$refs.tableHeight.offsetHeight - 47;
        }else{
          _this.scrollHeight = _this.$refs.tableHeight.offsetHeight
        }
      },
      tableHeightResizeHasPagination(){
        let _this = this;
        if(_this.$refs.searchArea){
          _this.scrollHeight = _this.$refs.tableHeight.offsetHeight - 88;
        }else{
          _this.scrollHeight = _this.$refs.tableHeight.offsetHeight - 41;
        }
      }, */
    loadData(arg) {
      console.log(this.queryParam)
      if (arg == 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let params = this.getQueryParams()
      console.log(params)
      params.hasQuery = 'true'
      if (JSON.stringify(this.queryParam) == '{}') {
        getAction(this.url.list, params)
          .then((res) => {
            if (res.success) {
              let result = res.result
              console.log(result)
              this.dataSource = result
              // if(this.firstLoadTable){
              //   this.defaultExpandedRowKeys = ["510000000000"];
              //   this.firstLoadTable = false;
              // };
              // if(Number(result.total)>0){
              //   this.ipagination.total = Number(result.total)
              //   this.dataSource = this.getDataByResult(res.result.records)
              //   console.log(this.dataSource);
              //   return this.loadDataByExpandedRows(this.dataSource)
              // }else{
              //   this.ipagination.total=0
              //   this.dataSource=[]
              // }
              this.ipagination.total = 1
              this.expandedRowKeys = ['81']
              this.showPagination = true
              this.tableHeightResize()
              this.$forceUpdate()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        let paramCopy = JSON.parse(JSON.stringify(params))
        if (params['areaName'] || params['areaName'] == '0') {
          paramCopy['areaName'] = params['areaName'].replace(/\*/g, '')
        }
        if (params['areaCode'] || params['areaCode'] == '0') {
          paramCopy['areaCode'] = params['areaCode'].replace(/\*/g, '')
        }
        console.log(paramCopy)
        getAction(this.url.searchList, paramCopy)
          .then((res) => {
            if (res.code == '200') {
              this.dataSource = res.result.records
              if (res.result.total) {
                this.ipagination.total = res.result.total
              } else {
                this.ipagination.total = 0
              }
              this.tableHeightResizeHasPagination()
              this.$forceUpdate()
              this.showPagination = false
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
    loadDataByExpandedRows(dataList) {
      if (this.expandedRowKeys.length > 0) {
        return getAction(this.url.getChildListBatch, { parentIds: this.expandedRowKeys.join(',') }).then((res) => {
          if (res.success && res.result.records.length > 0) {
            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map()
            for (let item of records) {
              let pid = item[this.pidField]
              if (this.expandedRowKeys.join(',').includes(pid)) {
                let mapList = listMap.get(pid)
                if (mapList == null) {
                  mapList = []
                }
                mapList.push(item)
                listMap.set(pid, mapList)
              }
            }
            let childrenMap = listMap
            let fn = (list) => {
              if (list) {
                list.forEach((data) => {
                  if (this.expandedRowKeys.includes(data.id)) {
                    data.children = this.getDataByResult(childrenMap.get(data.id))
                    fn(data.children)
                  }
                })
              }
            }
            fn(dataList)
          }
        })
      } else {
        return Promise.resolve()
      }
    },
    getQueryParams(arg) {
      //获取查询条件
      let sqp = {}
      let param = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      if (arg) {
        param = Object.assign(sqp, this.isorter, this.filters)
      } else {
        param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      }
      if (JSON.stringify(this.queryParam) === '{}' || arg) {
        param.hasQuery = 'false'
      } else {
        param.hasQuery = 'true'
      }
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    searchReset() {
      //重置
      this.expandedRowKeys = []
      this.queryParam = {}
      this.loadData(1)
    },
    getDataByResult(result) {
      if (result) {
        return result.map((item) => {
          //判断是否标记了带有子节点
          if (item[this.hasChildrenField] == '1') {
            let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      }
    },
    handleExpand(expanded, record) {
      // 判断是否是展开状态
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        if (record.children.length > 0 && record.children[0].isLoading === true) {
          this.loading = true
          let params = this.getQueryParams(1) //查询条件
          params[this.pidField] = record.id
          params.hasQuery = 'false'
          params.superQueryParams = ''
          getAction(this.url.childList, params).then((res) => {
            if (res.success) {
              if (res.result.records) {
                record.children = this.getDataByResult(res.result.records)
                this.dataSource = [...this.dataSource]
              } else {
                record.children = ''
                record.hasChildrenField = '0'
              }
            } else {
              this.$message.warning(res.message)
            }
            this.loading = false
          })
        }
      } else {
        let keyIndex = this.expandedRowKeys.indexOf(record.id)
        if (keyIndex >= 0) {
          this.expandedRowKeys.splice(keyIndex, 1)
        }
      }
    },
    handleAddChild(record) {
      this.loadParent = true
      let obj = {}
      obj[this.pidField] = record['id']
      this.$refs.modalForm.add(obj, record)
      this.$refs.modalForm.title = '新增行政区划'
      this.$refs.modalForm.disableSubmit = false
    },
    handleEditRow(record) {
      console.log(record)
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑行政区划'
      this.$refs.modalForm.disableSubmit = false
    },
    handleCheckRow(record) {
      console.log(record)
      this.$refs.modalForm.check(record)
      this.$refs.modalForm.title = '查看行政区划'
      this.$refs.modalForm.disableSubmit = true
    },
    handleDeleteNode(id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.loadData(1)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    batchDel() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return false
      } else {
        let ids = ''
        let that = this
        that.selectedRowKeys.forEach(function (val) {
          ids += val + ','
        })
        that.$confirm({
          title: '确认删除',
          class:"delete_qx",
          content: '是否删除选中数据?',
          onOk: function () {
            that.handleDeleteNode(ids)
            that.onClearSelected()
          },
        })
      }
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'int', value: 'parentId', text: '上级区划ID', dictCode: 'gt_sys_area,area_name,id' })
      fieldList.push({ type: 'string', value: 'areaName', text: '区划名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'areaCode', text: '区划编码', dictCode: '' })
      fieldList.push({ type: 'string', value: 'areaShortName', text: '区划简称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'status', text: '状态（1启动，0不启动）', dictCode: '' })
      fieldList.push({ type: 'string', value: 'delFlag', text: '删除状态（0正常，1已删除）', dictCode: '' })
      fieldList.push({ type: 'string', value: 'description', text: '区划描述', dictCode: '' })
      fieldList.push({ type: 'string', value: 'isSpecial', text: '是否特殊区域（0否，1是）', dictCode: '' })
      fieldList.push({ type: 'string', value: 'performLevel', text: '地区行使层级', dictCode: '' })
      fieldList.push({ type: 'string', value: 'areaLevel', text: '1省级，2市级，3区县级，4乡镇级，5村', dictCode: '' })
      fieldList.push({ type: 'string', value: 'areaOrder', text: '区划排序', dictCode: '' })
      fieldList.push({ type: 'string', value: 'province', text: '省级id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'city', text: '市级id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'county', text: '县级id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'town', text: '乡镇id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'pid', text: '父级节点', dictCode: '' })
      this.superFieldList = fieldList
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
      this.$nextTick(() => {
        this.tableHeightResize()
      })
    },
    // table收起展开图标
    expandIcon(props) {
      let _this = this
      if (props.record.children && props.record.children.length > 0) {
        if (props.expanded) {
          let childLen = props.record.children.length
          let childrenArr = props.record.children
          let isApart = false
          let isOtherApart = false
          let isTwoType = false
          let arr = []
          for (let x = 0; x < childLen; x++) {
            if (!childrenArr[x]['children'] || childrenArr[x]['children'].length == 0) {
              isApart = true
            } else if (childrenArr[x]['children'].length != 0) {
              isOtherApart = true
              arr.push(x)
            }
          }
          if (isOtherApart && isApart) {
            isTwoType = true
          }
          if (isTwoType) {
            return (
              <a
                style="color:'black'"
                class="isTwoType"
                onClick={(e) => {
                  props.onExpand(props.record, e)
                }}
              >
                <a-icon type="caret-down" class="tableIcon" />
              </a>
            )
          } else {
            return (
              <a
                style="color:'black'"
                onClick={(e) => {
                  props.onExpand(props.record, e)
                }}
              >
                <a-icon type="caret-down" class="tableIcon" />
              </a>
            )
          }
        } else {
          let childLen = props.record.children.length
          let childrenArr = props.record.children
          let isApart = false
          let isOtherApart = false
          let isTwoType = false

          for (let x = 0; x < childLen; x++) {
            if (!childrenArr[x]['children'] || childrenArr[x]['children'].length == 0) {
              isApart = true
            } else if (childrenArr[x]['children'].length != 0) {
              isOtherApart = true
            }
          }
          if (isOtherApart && isApart) {
            isTwoType = true
          }
          if (isTwoType) {
            return (
              <a
                style="color:'black'"
                class="isTwoType"
                onClick={(e) => {
                  props.onExpand(props.record, e)
                }}
              >
                <a-icon type="caret-right" class="tableIcon" />
              </a>
            )
          } else {
            return (
              <a
                style="color:'black'"
                onClick={(e) => {
                  props.onExpand(props.record, e)
                }}
              >
                <a-icon type="caret-right" class="tableIcon" />
              </a>
            )
          }
        }
      } else {
        return <span class="tableIcon"></span>
      }
    },
    changeNum() {
      this.loadData()
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
@import '~@assets/less/shaDow.less';
@import '~@assets/less/tableCommon.less';
/deep/.ant-table-row-cell-break-word a{
  
}
// 搜索框
.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;
  }
}
// 下拉框
::v-deep.ant-select {
  .ant-select-selection--single {
    height: 38px;
    .ant-select-selection__rendered {
      line-height: 38px;
    }
  }
  .ant-select-dropdown-menu-item-active:not(.ant-select-dropdown-menu-item-disabled) {
    
  }
}
::v-deep.table-page-search-wrapper {
  .ant-form-item,
  .table-page-search-submitButtons {
    margin-bottom: 12px;
    &>button:first-child{
      margin-right: 20px;
    }
  }
}
.table-page-search-wrapper ::v-deep.search_box .ant-form-item-children {
  display: flex;
  align-items: center;
}
.search_box .ant-form-inline .ant-form-item > .ant-form-item-label {
  padding-right: 8px;
}
.ant-alert-info {
  background-color: #fff;
  border: none;

  .clearBut {
    height: 38px;
    background: #ffffff;
    border-radius: 2px 2px 2px 2px;
    opacity: 1;
    
    letter-spacing: 0px;
    padding: 0 16px;
    margin-left: 6px;
  }
}

.ant-alert {
  padding: 0;
}

::v-deep .ant-dropdown-menu-item:hover {
  background: #f2f5f965;
}

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

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

    .btn-sure {
      background: #dbdbdb;
      border-radius: 2px 2px 2px 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;
}
</style>