<template>
  <div class="select-com">
    <div class="draw __box-shadow">
      <div class="tools">
        <div class="label">空间选择：</div>
        <div class="right">
          <div class="item __hover" :class="{active: cusTransfer.selectParams.type === 'circle'}" @click="mapDraw('circle')">
            <img src="@/assets/images/gis-layout/gis-layout-tools_select-circle.png" alt=""/>圆形
          </div>
          <div class="line"/>
          <div class="item __hover" :class="{active: cusTransfer.selectParams.type === 'rectangle'}" @click="mapDraw('rectangle')">
            <img src="@/assets/images/gis-layout/gis-layout-tools_select-rectangle.png" alt=""/>矩形
          </div>
          <div class="line"/>
          <div class="item __hover" :class="{active: cusTransfer.selectParams.type === 'polygon'}" @click="mapDraw('polygon')">
            <img src="@/assets/images/gis-layout/gis-layout-tools_select-polygon.png" alt=""/>多边形
          </div>
          <div class="line"/>
          <div class="item __hover" @click="mapClear">
            <img src="@/assets/images/gis-layout/gis-layout-tools_select-clear.png" alt=""/>清除
          </div>
        </div>
      </div>
    </div>
    <div class="result __box-shadow" v-if="cusTransfer.selectParams.wkt" v-loading="cusTransfer.result.table.loading">
      <div class="head">查询结果</div>
      <div class="chart">
        <SelectChartCom :data="hasTypeCpt"/>
      </div>
      <div class="data">
        <div class="form">
          <CusFormColumn
              labelWidth="50"
              :span="24"
              link="select"
              label="类型:"
              v-model:param="cusTransfer.result.tempForm.type"
              :options="hasTypeCpt"
              static
              multiple
              collapse-tags
          />
          <div class="two">
            <CusFormColumn
                labelWidth="50"
                :span="24"
                label="搜索:"
                v-model:param="cusTransfer.result.tempForm.name"
            />
            <div class="__cus-buttons-2">
              <div class="__cus-button-submit __hover" @click="onSearch">搜索</div>
              <div class="__cus-button-cancel __hover" @click="onReset">重置</div>
            </div>
          </div>
        </div>
        <div class="table">
          <CusTable
              ref="ref_cusTable"
              :tableData="resultTableDataCpt"
              :tableHead="cusTransfer.result.table.head"
              :total="resultTableFilterCpt.length"
              :page="cusTransfer.result.table.pageNum"
              :pageSize="cusTransfer.result.table.pageSize"
              @handlePage="handlePage"
              :row-class-name="tableRowClassName"
              @row-click="handleRowClick"
          >
          </CusTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  computed,
  onMounted,
  ref,
  reactive,
  watch,
  getCurrentInstance,
  ComponentInternalInstance,
  toRefs,
  nextTick, onUnmounted
} from 'vue'
import {useStore} from 'vuex'
import {useRouter, useRoute} from 'vue-router'
import {ElMessage, ElMessageBox} from "element-plus";
import SelectChartCom from './select-chart.vue'
import axios from "axios";
import SelectDraw, {SelectDrawClear} from "./select-draw";

export default defineComponent({
  name: '',
  components: {
    SelectChartCom
  },
  props: {
    map: {
      required: true
    },
    mapFunc: <any>{
      required: true
    },
    transfer: {}
  },
  setup(props, {emit}) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const that = (getCurrentInstance() as ComponentInternalInstance).appContext.config.globalProperties
    const state = reactive({
      transfer: <any>props.transfer,
      cusTransfer: <any>{
        selectParams: {
          type: '',
          wkt: ''
        },
        result: {
          form: {},
          tempForm: {
            type: [],
            name: ''
          },
          table: {
            head: [
              {value: "typeName", label: "类型", show: true, align: 'left', width: 100},
              {value: "name", label: "名称", show: true, align: 'left'},
            ],
            data: <any>[],
            pageNum: 1,
            pageSize: 10,
            loading: false
          }
        }
      }
    })
    const mapClear = () => {
      SelectDrawClear(props.map)
      state.cusTransfer.selectParams = {
        type: '',
        wkt: ''
      }
      state.cusTransfer.result.table.data = []
      state.cusTransfer.result.table.pageNum = 1
      state.cusTransfer.result.form = {
        type: [],
        name: ''
      }
    }
    const mapDraw = (type) => {
      SelectDraw(props.map, type).then(({feature, wkt}) => {
        state.cusTransfer.selectParams.type = type
        state.cusTransfer.selectParams.wkt = wkt
        initData()
      }).catch(() => {})
    }
    const initData = () => {
      state.cusTransfer.result.table.data = []
      if (store.getters['gis/elementActiveArr'].length > 0) {
        state.cusTransfer.result.table.loading = true
        axios({
          url: store.state.gis.element.layer.getSource().getUrls()[0],
          method: 'get',
          params: {
            service: 'WFS',
            version: '1.0.0',
            request: 'GetFeature',
            typename: store.getters['gis/elementActiveArr'].map(v => store.getters['dictionary/elementTypeMapObj'].get(v.value).geoType).join(','),
            srsName: 'EPSG:4326',
            outputFormat: 'application/json',
            CQL_FILTER: `INTERSECTS(location, ${state.cusTransfer.selectParams.wkt})`
          }
        }).then(res => {
          state.cusTransfer.result.table.data = res.data.features.map(v => {
            const obj = {
              name: v.properties.name,
              typeName: store.getters['dictionary/elementTypeMap'].get(v.properties.typeValue),
              type: v.properties.typeValue,
              info: v.properties,
              id: v.properties.dataId,
              typeValue: v.properties.typeValue,
              wkt: `POINT(${v.geometry.coordinates.join(' ')})`,
              featureType: '',
            }
            if (['lgszyjkscsb', 'jgzzmgs', 'lgsjkyfl'].includes(v.properties.typeValue)) {
              obj.featureType = 'qy'
            } else if (['gal', 'shl', 'myl'].includes(v.properties.typeValue)) {
              obj.featureType = 'sb'
            }
            return obj
          })
          state.cusTransfer.result.table.loading = false
        }).catch(() => {
          state.cusTransfer.result.table.loading = false
        })
      }
    }
    const resultTableFilterCpt = computed(() => {
      return state.cusTransfer.result.table.data.filter(v => (state.cusTransfer.result.form.type.length === 0 || state.cusTransfer.result.form.type.includes(v.type)) && v.name.includes(state.cusTransfer.result.form.name))
    })
    const resultTableDataCpt = computed(() => {
      return resultTableFilterCpt.value.slice((state.cusTransfer.result.table.pageNum - 1) * state.cusTransfer.result.table.pageSize, state.cusTransfer.result.table.pageNum * state.cusTransfer.result.table.pageSize)
    })
    const handlePage = ({page, pageSize}: any) => {
      state.cusTransfer.result.table.pageNum = page
      state.cusTransfer.result.table.pageSize = pageSize
    }
    const hasTypeCpt = computed(() => {
      const m = new Map()
      state.cusTransfer.result.table.data.forEach(v => {
        if (m.has(v.typeName)) {
          m.set(v.typeName, m.get(v.typeName) + 1)
        } else {
          m.set(v.typeName, 1)
        }
      })
      const arr: any = []
      m.forEach((v, k) => {
        arr.push({
          dictValue: k,
          dictLabel: k,
          num: v
        })
      })
      return arr
    })
    const onSearch = () => {
      state.cusTransfer.result.table.pageNum = 1
      state.cusTransfer.result.form = JSON.parse(JSON.stringify(state.cusTransfer.result.tempForm))
    }
    const onReset = () => {
      state.cusTransfer.result.tempForm = {
        name: '',
        type: []
      }
      onSearch()
    }
    const tableRowClassName = ({row}) => {
      if (
        (row.featureType === 'qy' && row.id === store.state.gis.gisParams.qy.feature?.getId()) ||
        (row.featureType === 'sb' && row.id === store.state.gis.gisParams.default.feature?.getId())
      ) {
        return 'row-active'
      }
      return ''
    }
    const handleRowClick = (row) => {
      switch (row.featureType) {
        case 'qy': {
          if (row.id === store.state.gis.gisParams.qy.feature?.getId()) {
            store.dispatch('gis/LOAD_GIS_PARAMS_QY_RESET')
          } else {
            store.dispatch('gis/LOAD_GIS_PARAMS_QY', {
              wkt: row.wkt,
              id: row.id,
              info: row.info
            })
          }
        } break
        case 'sb': {
          if (row.id === store.state.gis.gisParams.default.feature?.getId()) {
            store.dispatch('gis/LOAD_GIS_PARAMS_DEFAULT_RESET')
          } else {
            store.dispatch('gis/LOAD_GIS_PARAMS_DEFAULT_SB', {
              wkt: row.wkt,
              id: row.id,
              info: row.info
            })
          }
        } break
      }
    }
    watch(() => state.cusTransfer, () => {
      emit('update:transfer', state.cusTransfer)
    }, { deep: true })
    onMounted(() => {
      if (props.transfer) {
        state.cusTransfer = props.transfer
      } else {
        emit('update:transfer', state.cusTransfer)
      }
      state.cusTransfer.result.form = JSON.parse(JSON.stringify(state.cusTransfer.result.tempForm))
      const realLayer = props.map?.getLayers().getArray().filter(v => v.get('layerName') === 'selectDrawLayer')?.[0]
      if (realLayer) {
        realLayer.setVisible(true)
      }
    })
    onUnmounted(() => {
      const realLayer = props.map?.getLayers().getArray().filter(v => v.get('layerName') === 'selectDrawLayer')?.[0]
      if (realLayer) {
        realLayer.setVisible(false)
      }
    })
    return {
      ...toRefs(state),
      mapDraw,
      mapClear,
      resultTableFilterCpt,
      resultTableDataCpt,
      handlePage,
      hasTypeCpt,
      onSearch,
      onReset,
      tableRowClassName,
      handleRowClick
    }
  },
})
</script>

<style scoped lang="scss">
.select-com {
  position: fixed;
  width: 404px;
  display: flex;
  flex-direction: column;
  .draw {
    width: 100%;
    height: 60px;
    background-color: #FFFFFF;
    display: flex;
    align-items: center;
    padding: 0 14px;
    .tools {
      width: 100%;
      display: flex;
      align-items: center;
      .label {
        width: 72px;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #4C4C4C;
        display: flex;
        align-items: center;
      }
      .right {
        flex: 1;
        height: 36px;
        background-color: rgba(170, 198, 238, 0.2);
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 10px;
        .item {
          display: flex;
          align-items: center;
          font-size: 14px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #4C4C4C;
          >img {
            margin-right: 8px;
          }
          &.active {
            color: #1174DB;
          }
        }
        .line {
          width: 1px;
          height: 16px;
          background: linear-gradient(0deg, rgba(17,116,219,0) 0%, rgba(17,116,219,0.99) 50%, rgba(17,116,219,0) 100%);
        }
      }
    }
  }
  .result {
    width: 404px;
    position: fixed;
    height: calc(100% - 100px - 60px - 2px);
    bottom: 10px;
    background-color: #FFFFFF;
    flex: 1;
    display: flex;
    flex-direction: column;
    .head {
      height: 40px;
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #0096FF;
      display: flex;
      align-items: center;
      padding-left: 14px;
      border-bottom: 1px solid #EEEEEE;
    }
    .chart {
      height: 212px;
      width: 100%;
    }
    .data {
      flex: 1;
      padding: 0 12px 12px 12px;
      display: flex;
      flex-direction: column;
      .form {
        :deep(.el-form-item) {
          margin-bottom: 7px;
        }
        .two {
          display: flex;
          align-items: flex-start;
          .cus-form-column {
            flex: 1;
            margin-right: 8px;
          }
        }
      }
      .table {
        flex: 1;
        :deep(.row-active) {
          >td {
            background: rgba(16,140,243,0.1);
          }
        }
      }
    }
  }
}
</style>
