<template>
  <div>
    <div :class="`analysis`" style="display: flex;" v-drag="`.analysis .ant-card-head`">
      <a-card v-show="value" :title="title" style=" max-height: 90vh; width: 335px;  box-shadow: 0 0 5px #357ee5;">
        <a-icon slot="extra" type="close" style="cursor: pointer; color: #FFFFFF;" @click="$emit('input',false)" />
        <div>
          <h4 >选择分析源图层：</h4><!--v-if="isMore"-->
          <a-radio-group  v-model="tableType" button-style="solid" @change="onChange">
            <a-radio v-for="(item,index) in activeItemList "  :key="item.id" :value="index" v-show="!item.isHidden">
              {{ item.sourceName }}
            </a-radio>
          </a-radio-group>
          <div style="margin: 20px auto;">
            <a-radio-group v-model="typeSelected" button-style="solid" @change="getTypeSelected">
              <a-tooltip>
                <template slot="title">
                  针对图斑分析
                </template>
                <a-radio-button value="point">
                  点选分析
                </a-radio-button>
              </a-tooltip>
              <a-tooltip>
                <template slot="title">
                  自由绘制分析
                </template>
                <a-radio-button value="polygon">
                  绘制分析
                </a-radio-button>
              </a-tooltip>
            </a-radio-group>
            <a-button style="margin-left: 20px" @click="clear" type="danger">清空</a-button>
          </div>
        </div>
        <div>
        </div>
      </a-card>
    </div>
    <a-drawer
      title="分析结果"
      placement="right"
      :closable="true"
      :visible="basicMap.drawerVisible&&result[0].type!==''"
      @close="handleCancel"
      width="700"
      :mask="false"
      class="analysis"
    >
      <div style=" ">
        <a-tabs v-model="key" tab-position="left" @change="tabsCallback" size="small">
          <a-tab-pane v-if="gdXx" style="position: relative" key="项目信息" tab="项目信息">
            <div class="info">
              <div class="content">
                <div v-for="dk in gdXxList" :key="dk.title">
                  <div v-show="dk.content!=null" class="caseother"><span class="title">【{{ dk.title }}】</span><span
                    class="text">{{ dk.content }}</span></div>
                </div>
              </div>
            </div>
          </a-tab-pane>
          <a-tab-pane v-for="(item,index) in result" style="position: relative" :key="item.type" :tab="item.type"
                      v-if="item.data.length>0">
            <div>
              <div v-if="isTotal[index]" style="">
                <a-table style="" :columns="item.columns" :data-source="item.data" :pagination="false"
                         :scroll="{y: 300 }">
                  <template slot="types" slot-scope="text,record">
                    <a >{{ text }}</a>
                  </template>
                  <template slot="area" slot-scope="text,record">
                    <a @click="handleLocate(record)">{{ text }}</a>
                  </template>
                </a-table>
                <Pie style=" margin-top: 80px; " :height="300"  :dataSource="item.pieData"></Pie>
              </div>
              <div v-else>
                <a-icon type="rollback" style="position: absolute; right: 10px;top:-10px;font-size: 16px;z-index: 100"
                        @click="handleBack(index)" />
                <div v-if="item.type=='案件'" class="info" style="overflow: unset;user-select: auto;">
                  <a-timeline style="">
                    <template v-for="(item) in data">
                      <a-timeline-item color="green" v-if="item.TYPE=='sb'">
                        <div slot="dot"
                             style="font-size: 14px;background-color: #336699;border-radius: 50%;text-align: center;width: 30px;height: 30px;position: relative">
              <span
                style="font-weight: bold;color: #FFF;background-color: #46A4DA;border-radius: 50%;width:75%;height:75%;display: inline-block;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);line-height: initial;">
                报
              </span>
                        </div>
                        <div class="content">
                          <div class="ant-popover-arrow" style=" left: -5px;top: 12px;color: #AFDCF8;"></div>
                          <div class="casedate"><span class="title">【上报日期】</span><span>{{ item.RQ }}</span></div>
                          <div class="caseother"><span class="title">【巡查员】</span><span>{{ item.REALNAME }}</span>
                          </div>
                          <div class="caseother"><span
                            class="title">【描述】</span><span>{{ item.MS }}</span></div>
                          <div class="caseother" v-show="item.ZPNAME">
                            <span class="title">【媒体信息】</span>
                            <div class="images" v-viewer>
                              <img v-for="src in item.ZPNAME" :key="src" :src="src">
                            </div>
                          </div>
                          <div class="caseother" v-show="item.SPNAME">
                            <span class="title">【视频信息】</span>
                            <div>
                              <img src="@/assets/caseVideoNew.png" @click="handleVideo(item.SPNAME)">
                            </div>
                          </div>
                        </div>
                      </a-timeline-item>
                      <a-timeline-item color="green" v-else-if="item.TYPE=='zp'">
                        <div slot="dot"
                             style="font-size: 14px;background-color: #336699;border-radius: 50%;text-align: center;width: 30px;height: 30px;position: relative">
              <span
                style="font-weight: bold;color: #FFF;background-color: #46A4DA;border-radius: 50%;width:75%;height:75%;display: inline-block;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);line-height: initial;">
                派
              </span>
                        </div>
                        <div class="content">
                          <div class="ant-popover-arrow" style=" left: -5px;top: 12px;color: #AFDCF8;"></div>
                          <div class="casedate"><span class="title">【派发日期】</span><span>{{ item.RQ }}</span></div>
                          <div class="caseother"><span class="title">【处理员】</span><span>{{ item.REALNAME }}</span>
                          </div>
                          <div class="caseother"><span
                            class="title">【描述】</span><span>{{ item.MS }}</span></div>
                          <div class="caseother" v-show="item.ZPNAME">
                            <span class="title">【媒体信息】</span>
                            <div class="images" v-viewer>
                              <img v-for="src in item.ZPNAME" :key="src" :src="src">
                            </div>
                          </div>
                          <div class="caseother" v-show="item.SPNAME">
                            <span class="title">【视频信息】</span>
                            <div>
                              <img src="@/assets/caseVideoNew.png" @click="handleVideo(item.SPNAME)">
                            </div>
                          </div>
                        </div>
                      </a-timeline-item>
                      <a-timeline-item color="green" v-else-if="item.TYPE=='db'">
                        <div slot="dot"
                             style="font-size: 14px;background-color: #336699;border-radius: 50%;text-align: center;width: 30px;height: 30px;position: relative">
              <span
                style="font-weight: bold;color: #FFF;background-color: #46A4DA;border-radius: 50%;width:75%;height:75%;display: inline-block;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);line-height: initial;">
                督
              </span>
                        </div>
                        <div class="content">
                          <div class="ant-popover-arrow" style=" left: -5px;top: 12px;color: #AFDCF8;"></div>
                          <div class="casedate"><span class="title">【督办日期】</span><span>{{ item.RQ }}</span></div>
                          <div class="caseother"><span class="title">【督办员】</span><span>{{ item.REALNAME }}</span>
                          </div>
                          <div class="caseother"><span
                            class="title">【描述】</span><span>{{ item.MS }}</span></div>
                          <div class="caseother" v-show="item.ZPNAME">
                            <span class="title">【媒体信息】</span>
                            <div class="images" v-viewer>
                              <img v-for="src in item.ZPNAME" :key="src" :src="src">
                            </div>
                          </div>
                          <div class="caseother" v-show="item.SPNAME">
                            <span class="title">【视频信息】</span>
                            <div>
                              <img src="@/assets/caseVideoNew.png" @click="handleVideo(item.SPNAME)">
                            </div>
                          </div>
                        </div>
                      </a-timeline-item>
                      <a-timeline-item color="green" v-else-if="item.TYPE=='cl'">
                        <div slot="dot"
                             style="font-size: 14px;background-color: #336699;border-radius: 50%;text-align: center;width: 30px;height: 30px;position: relative">
              <span
                style="font-weight: bold;color: #FFF;background-color: #46A4DA;border-radius: 50%;width:75%;height:75%;display: inline-block;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);line-height: initial;">
                处
              </span>
                        </div>
                        <div class="content">
                          <div class="ant-popover-arrow" style=" left: -5px;top: 12px;color: #AFDCF8;"></div>
                          <div class="casedate"><span class="title">【处理日期】</span><span>{{ item.RQ }}</span></div>
                          <div class="caseother"><span class="title">【处理员】</span><span>{{ item.REALNAME }}</span>
                          </div>
                          <div class="caseother"><span
                            class="title">【描述】</span><span>{{ item.MS }}</span></div>
                          <div class="caseother" v-show="item.ZPNAME">
                            <span class="title">【媒体信息】</span>
                            <div class="images" v-viewer>
                              <img v-for="src in item.ZPNAME" :key="src" :src="src">
                            </div>
                          </div>
                          <div class="caseother" v-show="item.SPNAME">
                            <span class="title">【视频信息】</span>
                            <div>
                              <img src="@/assets/caseVideoNew.png" @click="handleVideo(item.SPNAME)">
                            </div>
                          </div>
                        </div>
                      </a-timeline-item>
                      <a-timeline-item color="green" v-else-if="item.TYPE=='ff'">
                        <div slot="dot"
                             style="font-size: 14px;background-color: #336699;border-radius: 50%;text-align: center;width: 30px;height: 30px;position: relative">
              <span
                style="font-weight: bold;color: #FFF;background-color: #46A4DA;border-radius: 50%;width:75%;height:75%;display: inline-block;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);line-height: initial;">
                飞
              </span>
                        </div>
                        <div class="content">
                          <div class="ant-popover-arrow" style=" left: -5px;top: 12px;color: #AFDCF8;"></div>
                          <div class="casedate"><span class="title">【复飞日期】</span><span>{{ item.RQ }}</span></div>
                          <div class="caseother"><span class="title">【复飞员】</span><span>{{ item.REALNAME }}</span>
                          </div>
                          <div class="caseother"><span
                            class="title">【描述】</span><span>{{ item.MS }}</span></div>
                          <div class="caseother" v-show="item.ZPNAME">
                            <span class="title">【媒体信息】</span>
                            <div class="images" v-viewer>
                              <img v-for="src in item.ZPNAME" :key="src" :src="src">
                            </div>
                          </div>
                          <div class="caseother" v-show="item.SPNAME">
                            <span class="title">【视频信息】</span>
                            <div>
                              <img src="@/assets/caseVideoNew.png" @click="handleVideo(item.SPNAME)">
                            </div>
                          </div>
                        </div>
                      </a-timeline-item>
                      <a-timeline-item color="green" v-else-if="item.TYPE=='sh'">
                        <div slot="dot"
                             style="font-size: 14px;background-color: #336699;border-radius: 50%;text-align: center;width: 30px;height: 30px;position: relative">
              <span
                style="font-weight: bold;color: #FFF;background-color: #46A4DA;border-radius: 50%;width:75%;height:75%;display: inline-block;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);line-height: initial;">
                审
              </span>
                        </div>
                        <div class="content">
                          <div class="ant-popover-arrow" style=" left: -5px;top: 12px;color: #AFDCF8;"></div>
                          <div class="casedate"><span class="title">【审核日期】</span><span>{{ item.RQ }}</span></div>
                          <div class="caseother"><span class="title">【审核员】</span><span>{{ item.REALNAME }}</span>
                          </div>
                          <div class="caseother"><span
                            class="title">【描述】</span><span>{{ item.MS }}</span></div>
                          <div class="caseother" v-show="item.ZPNAME">
                            <span class="title">【媒体信息】</span>
                            <div class="images" v-viewer>
                              <img v-for="src in item.ZPNAME" :key="src" :src="src">
                            </div>
                          </div>
                          <div class="caseother" v-show="item.SPNAME">
                            <span class="title">【视频信息】</span>
                            <div>
                              <img src="@/assets/caseVideoNew.png" @click="handleVideo(item.SPNAME)">
                            </div>
                          </div>
                        </div>
                      </a-timeline-item>
                    </template>
                    <!--                          <a-timeline-item color="green" v-if="ajzt.includes('结案')">
                                                <a-icon slot="dot" type="check-circle" style="font-size: 16px;" />
                                                <div class="content">
                                                  <div class="ant-popover-arrow" style=" left: -5px;top: 12px;color: #AFDCF8;"></div>
                                                  <div class="caseother"><span class="title">【案件已结案】</span></div>
                                                </div>
                                              </a-timeline-item>
                                              <a-timeline-item color="red" v-else>
                                                <a-icon slot="dot" type="clock-circle-o" style="font-size: 16px;" />
                                                <div class="content">
                                                  <div class="ant-popover-arrow" style=" left: -5px;top: 12px;color: #AFDCF8;"></div>
                                                  <div class="caseother"><span class="title">【等待】</span>
                                                    <span v-if="ajzt.includes('未派发')">派发</span>
                                                    <span v-else-if="ajzt.includes('审核待处理')">重新处理</span>
                                                    <span v-else-if="ajzt.includes('待处理')">处理</span>
                                                    <span v-else-if="ajzt.includes('审核待复飞')">重新复飞</span>
                                                    <span v-else-if="ajzt.includes('待复飞')">复飞</span>
                                                    <span v-else-if="ajzt.includes('待审核')">审核</span>
                                                  </div>
                                                </div>
                                              </a-timeline-item>-->
                  </a-timeline>
                </div>
                <div v-else class="info" style="width: 100%">
                  <div class="content" v-for="(dks,ind) in item.list" :key="ind" >
                    <div v-for="dk in dks" :key="dk.name">
                        <div v-show="dk.content!=null" class="caseother"><span class="title">【{{ dk.name }}】</span><span
                          class="text">{{ dk.content }}</span></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>


          </a-tab-pane>
        </a-tabs>
      </div>
    </a-drawer>
    <locate-by-geoinfo ref="locateByGeoinfo"></locate-by-geoinfo>

  </div>

</template>

<script>
import { getAction } from '../../../api/manage';
import Draw from '@arcgis/core/views/draw/Draw';
import Graphic from '@arcgis/core/Graphic';
import Point from '@arcgis/core/geometry/Point';
import Polygon from '@arcgis/core/geometry/Polygon';
import Pie from '@/components/chart/Pie';
import LocateByGeoinfo from './LocateByGeoinfo';
import wktParser from 'terraformer-wkt-parser';
import Extent from '@arcgis/core/geometry/Extent';

export default {
  name: 'SpatialAnalysis',
  components: { Pie, LocateByGeoinfo },

  data() {
    return {
      map: '',
      draw: '',
      visible: false,
      tableType: '',
      id: '',
      coords: [],
      table: '',
      result: [{ type: '', data: [], pieData: [] }],
      checkedList: [],
      indeterminate: true,
      checkAll: true,
      plainOptions: [],
      orderTable: '',
      orderTableList: [],
      allOrderTable: [],
      typeSelected: '',
      title: '空间分析',
      zShow: false,
      isMore: true,
      isTotal: [],
      key: '',
      keys: [],
      list: [],
      gdXx: false,
      gdXxList: [],
      lng: [],
      lat: [],
      url: {
        list: '/geoAnalysis/Analysis/SelectByTb',
        detail: '/geoAnalysis/Analysis/SelectDetails',
        ajdetail: '/ajgl.ajxx/tinXjglSglistPolygon/ajxxlist',
        polygon: '/geoAnalysis/Analysis/DrawMap',
        point: '/geoAnalysis/Analysis/DrawMapByid',
      },
      baseUrl:'',
      data:'',
    };
  },
  props: {
    value: {
      type: Boolean,
      default: false,
      required: true,
    },
  },
  computed: {
    activeItemList: {
      get: function() {
        let list = [];
        console.log(666,this.basicMap.layerList)
        if (this.basicMap.layerList.length > 0) {
          this.basicMap.layerList.map((item) => {
            item.layers.map((layer) => {
              if (layer.analyzable) {
                list.push(layer);
              }
            });
          });
        }
        return list;
      },
    },
  },
  inject: ['basicMap'],
  created() {
    this.baseUrl=window._CONFIG['staticDomainURL'];
  },
  watch: {
    activeItemList(nVal) {
      if (this.activeItemList.length > 0) {
        let table;
        if (nVal.length >= 1) {
          this.isMore = false;
          table = nVal[0];
          if (!table) {
            this.$message.error('暂无权限');
            return;
          }
          if (nVal.length > 1) {
            this.isMore = true;
            this.typeSelected = '';
          } else {
            this.isMore = false;
            this.table = table.tablename;
          /*  this.typeSelected = 'point';*/
            this.loadList();
            this.getTypeSelected();
          }
        } else {
          this.$message.error('暂无权限');
        }
      }
    },
    value(nVal) {
      if (nVal === false) {
        this.stopDraw();
      }
    },
  },
  methods: {
    async handleDetail(record, index, type) {
      console.log(record, type);
      this.result[index].list = [];
      if (type === '案件') {
        let {success, message, result} = await getAction(this.url.ajdetail, {
          ajh:record.key,
        });
        if (success) {
          if (result.length === 0 || result === '') {
            this.$message.error('没有查询到信息');
            this.data = [];
            return;
          }
          this.data = result;
        } else {
          this.$message.info(message);
        }
        // 修改图片数组格式
        this.data.forEach((item,index)=>{
          if(item.TYPE=='zp'){
            this.zpxx=item;
          }
          if(item.ZPNAME){
            this.data[index].ZPNAME=this.data[index].ZPNAME.split(';');
            if(!this.data[index].ZPNAME[this.data[index].length-1]||this.data[index].ZPNAME[this.data[index].length-1]===''){
              this.data[index].ZPNAME.pop();
            }
            this.data[index].ZPNAME.forEach((itemA,ind)=>{
              this.data[index].ZPNAME[ind]=this.baseUrl+"/uploading/"+itemA;
            });
          }
        })
      } else {

      }
      let { success, message, result } = await getAction(this.url.detail, {
        table: this.key,
        objectid: record.objectids.toString(),
      });
      if (success) {
        if (result.records) {
          if (result.total === 0 || result.records === '') {
            this.$message.error('没有查询到信息');
            return;
          }
          result = result.records;
        } else {
          if (result.length === 0 || result === '') {
            this.$message.error('没有查询到信息');
            return;
          }
        }
        result.forEach((item) => {
          let list = [];
          for (var key in item.fldalia) {
            list.push({ name: item.fldalia[key], content: item.result[key], wkt: item.result.WKT });
          }
          this.result[index].list.push(list);
        });
        this.$set(this.isTotal, index, false);
      } else {
        if (message.includes('null')) {
          message = '没有查询到数据';
        }
        this.$message.info(message);
      }
    },
    handleLocate(record, isOwn) {

      if (!isOwn) {
        this.basicMap.analysis_Drew_GraphicsLayer.removeAll();
        this.lng = [];
        this.lat = [];
      }
      if (record.wkt.length == 0) {
        this.$message.warn('没有空间信息');
        return;
      }

      record.wkt.forEach((item, ind) => {
        if (item == null || item == undefined || item == '') return;
        let geomInfo = item;
        let type;
        let geojson;
        let bsIndex = geomInfo.indexOf('(');

        if (item.includes('GEOMETRYCOLLECTION')) {
          let dex = geomInfo.indexOf('GEOMETRYCOLLECTION') + 20;
          let newI = item.substr(dex, item.length - 21).split('), ');
          newI.forEach((itemN, inde) => {
            if (inde !== newI.length - 1) {
              newI[inde] = itemN + ')';
            }
          });
          this.handleLocate({ wkt: newI }, true);
          return;
        } else if (item.includes('MULTIPOLYGON')) {
          if (bsIndex != -1) {
            type = geomInfo.slice(0, bsIndex).trim().toUpperCase();
            geojson = new wktParser.parse(geomInfo);
          } else {
            type = JSON.parse(item.geoinfo).type.toUpperCase();
            geojson = JSON.parse(item.geoinfo);
          }
          geojson.coordinates.forEach((coords) => {
            let rings = [];
            for (let i = 0; i < coords.length; i++) {
              let ring = [];
              let vertexes = coords[i];
              for (let j = 0; j < vertexes.length; j++) {
                let vertex = vertexes[j];
                ring.push(vertex);
              }
              rings.push(ring);
            }
            rings.forEach((coords) => {
              coords.forEach((itemC, index) => {
                if (rings.length > 1) {
                  if (!Array.isArray(itemC)) {
                    this.lng.push(coords[0]);
                    this.lat.push(coords[1]);
                  } else {
                    itemC.forEach((it) => {
                      this.lng.push(it[0]);
                      this.lat.push(it[1]);
                    });
                  }
                } else {
                  if (itemC[0] != undefined && itemC[1] != undefined) {
                    this.lng.push(itemC[0]);
                    this.lat.push(itemC[1]);
                  }
                }
              });
            });
            let polygon = new Polygon({
              rings: rings,
              spatialReference: this.spatialReference,
            });
            let r = Math.floor(Math.random() * 255);
            let g = Math.floor(Math.random() * 255);
            let b = Math.floor(Math.random() * 255);
            const polygonSymbol = {
              type: 'simple-fill',  // autocasts as new SimpleFillSymbol()
              // color: [128, 128, 128, 0.5],
              color: [r, g, b, 0.5],
              outline: {  // autocasts as new SimpleLineSymbol()
                color: [r, g, b],
                width: '6px',
                style: 'short-dot',
              },
            };
            let graphic = new Graphic({
              geometry: polygon,
              symbol: polygonSymbol,
            });
            this.basicMap.analysis_Drew_GraphicsLayer.add(graphic);
          });
        } else {

          if (bsIndex != -1) {
            type = geomInfo.slice(0, bsIndex).trim().toUpperCase();
            geojson = new wktParser.parse(geomInfo);
          } else {
            type = JSON.parse(item.geoinfo).type.toUpperCase();
            geojson = JSON.parse(item.geoinfo);
          }
          let rings = [];
          let ring = [];
          let coords = geojson.coordinates;
          for (let i = 0; i < coords.length; i++) {
            ring = [];
            let vertexes = coords[i];
            for (let j = 0; j < vertexes.length; j++) {
              let vertex = vertexes[j];
              ring.push(vertex);
            }
            rings.push(ring);
          }
          rings.forEach((coords) => {
            coords.forEach((itemC, index) => {
              if (rings.length > 1) {
                if (!Array.isArray(itemC)) {
                  this.lng.push(coords[0]);
                  this.lat.push(coords[1]);
                } else {
                  itemC.forEach((it) => {
                    this.lng.push(it[0]);
                    this.lat.push(it[1]);
                  });
                }
              } else {
                if (itemC[0] != undefined && itemC[1] != undefined) {
                  this.lng.push(itemC[0]);
                  this.lat.push(itemC[1]);
                }
              }
            });
          });
          let polygon = new Polygon({
            rings: rings,
            spatialReference: this.spatialReference,
          });
          let r = Math.floor(Math.random() * 255);
          let g = Math.floor(Math.random() * 255);
          let b = Math.floor(Math.random() * 255);
          const polygonSymbol = {
            type: 'simple-fill',  // autocasts as new SimpleFillSymbol()
            // color: [128, 128, 128, 0.5],
            color: [g, r, b, 0.5],
            outline: {  // autocasts as new SimpleLineSymbol()
              color: [r, g, b],
              width: '3px',
              style: 'solid',
            },
          };
          let graphic = new Graphic({
            geometry: polygon,
            symbol: polygonSymbol,
          });
          this.basicMap.analysis_Drew_GraphicsLayer.add(graphic);
        }
      });
      if (isOwn) {
        return;
      }
      ;
      if (this.lng.length < 1) {
        this.$message.info('暂无空间信息');
        return;
      }
      this.lng.sort();
      this.lat.sort();
      let extent = new Extent(
        this.lng[0], this.lat[0], this.lng[this.lat.length - 1], this.lat[this.lat.length - 1],
      );
      this.basicMap.mapView.extent = extent;
      let cur_scale = this.basicMap.mapView.scale;
      this.basicMap.mapView.goTo({
          scale: cur_scale * 1.2,
        }, {
          duration: 500,
        },
      );
      this.basicMap.mapView2.extent = this.basicMap.mapView.extent;

    },
    handleCancel() {
      this.basicMap.drawerVisible = false;
    },
    handleCoord(item) {
      let layer;
      this.keys.forEach((item, index) => {
        let checked;
        let m_layer = this.basicMap.esriMap.findLayerById(item.id);
        if (item.alias === this.key || item.alias.includes(this.key) || this.key.includes(item.alias)) {
          layer = item;
          checked = true;
        } else {
          if (item.tablename === this.table) return;
          checked = false;
        }
        if (item.sublayerid || item.sublayerid === 0) {
          let sublayer = m_layer.findSublayerById(parseInt(item.sublayerid));
          sublayer.visible = checked;
        } else {
          m_layer.visible = checked;
        }
      });
      this.basicMap.layerList.map((item) => {
        item.layers.map((layerItem) => {
          if (layerItem === layer) {
            layerItem.visible = true;
          } else {
            if (this.keys.indexOf(layerItem)) {
              layerItem.visible = false;
            }
          }
        });
      });
      this.$refs.locateByGeoinfo.locate(item[0], this.basicMap.map);
    },
    handleBack(index) {
      // this.isTotal.splice(index, 1, true);
      this.$set(this.isTotal, index, true);
    },
    onChange(e) {
      let ind;
      if (!isNaN(e)) {
        ind = e;
      } else {
        ind = e.target.value;
      }
      this.clear();
      this.typeSelected = 'point';
      if (ind === -1) {
        this.table = 'zidingyi';
      } else {
        this.table = this.activeItemList[ind].tablename;
      }
      this.loadList();
      this.getTypeSelected();
      if (ind === -1) return;
      let layer;
      this.activeItemList.forEach((item, index) => {
        let checked;
        let m_layer = this.basicMap.esriMap.findLayerById(item.id);
        if (index === ind) {
          layer = item;
          checked = true;
        } else {
          checked = false;
        }
        if (!m_layer) {
          m_layer = this.basicMap._loadLayer(layer, this.basicMap.esriMap);
        } else {
          if (item.sublayerid || item.sublayerid === 0) {
            let sublayer = m_layer.findSublayerById(parseInt(item.sublayerid));
            sublayer.visible = checked;
          } else {
            m_layer.visible = checked;
          }
        }
      });
      this.basicMap.layerList.map((item) => {
        item.layers.map((layerItem) => {
          if (layerItem.analyzable) {
            if (layerItem === layer) {
              layerItem.visible = true;
            } else {
              layerItem.visible = false;
            }
          }
        });
      });
    },
    onCheckChange(checkedList) {
      this.indeterminate = !!checkedList.length && checkedList.length < this.plainOptions.length;
      this.checkAll = checkedList.length === this.plainOptions.length;
      this.orderTable = [];
      checkedList.forEach((item) => {
        this.orderTableList.forEach((itemTable, index) => {
          if (itemTable.atablecname === item) {
            this.orderTable.push(itemTable.atableename);
          }
        });
      });
      this.getTypeSelected();
    },
    onCheckAllChange(e) {
      Object.assign(this, {
        checkedList: e.target.checked ? this.plainOptions : [],
        indeterminate: false,
        checkAll: e.target.checked,
      });
      if (e.target.checked) {
        this.orderTable = this.allOrderTable;
        this.getTypeSelected();
      }
    },
    tabsCallback(key) {
      this.key = key;
    },
    onClose() {
      this.visible = false;
    },
    showCard() {
      this.basicMap.drawerVisible = true;
    },
    mercatorTolonlat(mercator) {
      var x = mercator[0] / 20037508.34 * 180;
      var y = mercator[1] / 20037508.34 * 180;
      y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);
      return [x, y];
    },
    stopDraw() {
      if (this.draw !== '') {
        this.draw.reset();
      }
      this.table = '';
      this.tableType = '';
    },
    initDrawLayer() {
      // this.map=this.basicMap.vecBasemap;
      let view = this.basicMap.mapView;
      this.view = view;
      this.draw = new Draw({
        view: view,
      });
    },
    getTypeSelected(e) {
      if (this.table === '') {
        this.$message.info('请选择分析源图层');
        return;
      }
      if (this.typeSelected === 'polygon') {
        this.loadList();
      } else {
        if (this.table === '') {
          this.$message.info('请选择分析源图层');
          return;
        }
      }
      if (this.draw === '') {
        this.initDrawLayer();
      }
      let view = this.basicMap.mapView;
      view.graphics.removeAll();
      this.basicMap.analysis_Drew_GraphicsLayer.removeAll();
      this.result = [{ type: '', data: [], pieData: [] }];
      this.basicMap.analysis_GraphicsLayer.removeAll();
      const action = this.draw.create(this.typeSelected, {
        mode: 'click',
      });
      view.focus();
      switch (this.typeSelected) {
        case 'point':
          action.on(
            [
              'vertex-add',
              'vertex-remove',
              'redo',
              'undo',
              'draw-complete',
            ], this.createPoint);
          break;
        case 'polygon':
          action.on(
            [
              'vertex-add',
              'vertex-remove',
              'redo',
              'undo',
              'draw-complete',
              'cursor-update',
            ], this.createPolygon);
          break;
        default:

          break;
      }

      action.on('draw-complete', (evt) => {
        let type = 'Polygon';
        evt.vertices.forEach((item, index) => {
          evt.vertices[index] = this.mercatorTolonlat(item);
        });
        let vertices = evt.vertices;
        if (this.typeSelected === 'point') {
          type = 'Point';
          vertices = vertices[0];
          let featureGeoJson = {
            type: 'Feature',
            geometry: {
              type: type,
              coordinates: vertices,
            },
            properties: null,
            crs: {
              'type': 'name',
              'properties': {
                'name': 'EPSG:4490',
              },
            },
          };
        } else {
          // debugger
          // let polygon = new Polygon({
          //   rings: evt.vertices ,// 定义闭合的多边形轮廓点集
          //   spatialReference: { wkid: 4490 }
          // });
          vertices = evt.vertices
          // evt.vertices.push(evt.vertices[0]);
          // vertices.push(evt.vertices);
         }
        this.coords = vertices;
        this.loadGeomAnalysis();
      });
    },
    createPoint(event) {
      //获取所有顶点
      var coordinates = event.coordinates;

      //生成绘制的图形
      var graphic = new Graphic({
        geometry: new Point({
          hasZ: false,
          hasM: false,
          x: coordinates[0],
          y: coordinates[1],
          spatialReference: this.view.spatialReference,
        }),
        symbol: {
          type: 'simple-marker',  // autocasts as new SimpleMarkerSymbol()
          style: 'square',
          color: 'blue',
          size: '8px',  // pixels
          outline: {  // autocasts as new SimpleLineSymbol()
            color: [255, 255, 0],
            width: 3,  // points
          },
        },
      });
      // 将绘制的图形添加到view
      this.basicMap.analysis_GraphicsLayer.add(graphic);
    },
    createPolygon(event) {
      //获取所有顶点
      var vertices = event.vertices;
      //清除之前绘制
      this.view.graphics.removeAll();
      this.basicMap.analysis_GraphicsLayer.removeAll();

      // 生成绘制的图形
      var graphic = new Graphic({
        geometry: new Polygon({
          hasZ: false,
          hasM: false,
          rings: [vertices],
          spatialReference: this.view.spatialReference,
        }),
        symbol: {
          type: 'simple-fill',  // autocasts as new SimpleFillSymbol()
          color: [51, 51, 204, 0.4],
          style: 'solid',
          outline: {  // autocasts as new SimpleLineSymbol()
            color: 'red',
            width: 1,
          },
        },
      });
      // 将绘制的图形添加到view
      this.basicMap.analysis_GraphicsLayer.add(graphic);
    },
    async loadList() {
      let { success, message, result } = await getAction(this.url.list, {
        table: this.table,
      });
      if (success) {
        if (result.records) {
          if (result.total === 0 || result.records === '') {
            this.$message.error('没有查询到信息');
            return;
          }
          result = result.records;
        } else {
          if (result.length === 0 || result === '') {
            this.$message.error('没有查询到信息');
            return;
          }
        }
        this.checkedList = [];
        this.plainOptions = [];
        this.allOrderTable = [];
        this.orderTableList = result;
        result.map((item, index) => {
          this.plainOptions.push(item.atablecname);
          this.allOrderTable.push(item.atableename);
        });
        this.checkedList = this.plainOptions;
        this.orderTable = this.allOrderTable;

      } else {
        if (message.includes('null')) {
          message = '没有查询到数据';
        }
        this.$message.info(message);
      }
    },
    async loadGeomAnalysis() {
      if (this.orderTable.length < 1) {
        this.$error('请选择分析目标！！');
        return;
      }
      let length = 1;
      this.gdXx = false;
      let url = this.url.polygon;
      if (this.typeSelected === 'point') {
        url = this.url.point;
        if (this.table === 'GD_DKXX') {
          length = 2;
        }
      }
      let key = 'query';
      this.$message.loading({ content: '正在分析中，请稍等...', key, duration: 20 });
      let { success, message, result } = await getAction(url, {
        table: this.table,
        geoJson: this.coords,
        atableename: this.orderTable.toString(),
      });
      if (success) {
        if (result.records) {
          if (result.total === 0 || result.records === '' || result.records === null) {
            this.$message.error({ content: '没有查询到信息!', key, duration: 1 });
            // this.getTypeSelected();
            this.typeSelected = '';
            return;
          }
        } else {
          if (result.length === 0 || result === '' || result === null) {
            this.$message.error({ content: '没有查询到信息!', key, duration: 1 });
            // this.getTypeSelected();
            this.typeSelected = '';
            return;
          }
          let type = '';
          let col = [];
          let col2 = [];
          this.result = [];
          let resInd = -1; //便于追加数据，需要索引
          let data = [];
          this.isTotal = [];
          this.keys = [];
          let isNull = false;

          result.forEach((item, index) => {
            if (item === null) {
              if (result.length === 1) {
                this.$message.error({ content: '没有查询到信息!', key: 'query', duration: 1 });
                isNull = true;
                this.typeSelected = '';
              }
              // this.$message.error({ content: '没有查询到项目信息!', key, duration: 1 });
              // this.getTypeSelected();
              return;
            }
            if (!item.result) {
              item.type = '项目信息';
              item.list = [];
              for (var key in item) {　　//遍历对象的所有属性，包括原型链上的所有属性
                if (item.hasOwnProperty(key) && key != 'type' && key != 'list') { //判断是否是对象自身的属性，而不包含继承自原型链上的属性，不是后加的属性
                  let val = { title: key, content: item[key] };
                  item.list.push(val);
                }
              }

              this.gdXxList = item.list;
              this.result.slice(index, 1);
              this.gdXx = true;
              return;
            }
            item.result.area = parseFloat(item.result.area).toFixed(4);
            if (item.type === type) {

            } else {
              if (item.result.area <= 0) {
                // return
              }
              resInd++;
              this.result.push({
                type: '',
                data: [],
                pieData: [],
                columns: [],
                list: [],
              });
              this.isTotal.push(true);
              this.result[resInd].type = item.type;
              type = item.type;
              this.basicMap.layerList.map((child) => {
                child.layers.map((layer) => {
                  if (layer.alias === item.type) {
                    this.keys.push(layer);
                  }
                });
              });
              data.push([]);
              col = { title: '用途', dataIndex: 'types', key: 'types', scopedSlots: { customRender: 'types' } };
              col2 = { title: '面积（公顷）', dataIndex: 'area', key: 'area', scopedSlots: { customRender: 'area' } };
              col.title = item.afieldcname;
              this.result[resInd].columns.push(col, col2);

            }
            data[resInd].push(item.result);
            /*let pie = { item: '示例一', count: 40 };
            pie.item = item.result.types;
            pie.count = parseFloat(item.result.area);
            this.result[resInd].pieData.push(pie);
            this.result[resInd].data.push(item.result);*/
            if (index == (result.length - length)) {
              data.forEach((arr, index) => {
                let pies = [];
                var map = {}, dest = [];
                for (var i = 0; i < arr.length; i++) {
                  var ai = arr[i];
                  if (!map[ai.types]) {
                    dest.push({
                      key: ai.types,
                      types: ai.types,
                      objectids: [ai.objectid],
                      wkt: [ai.info],
                      area: ai.area,
                    });
                    let pie = { item: '示例一', count: 40 };
                    pie.item = ai.types;
                    pie.count = parseFloat(ai.area);
                    pies.push(pie);
                    map[ai.types] = ai;
                  } else {
                    for (var j = 0; j < dest.length; j++) {
                      var dj = dest[j];
                      if (dj.types == ai.types) {
                        dj.area = parseFloat(parseFloat(dj.area) + parseFloat(ai.area)).toFixed(4);
                        dj.wkt.push(ai.info);
                        dj.objectids.push(ai.objectid);
                        pies[j].count = parseFloat(dj.area);
                        break;
                      }
                    }
                  }
                }
                dest.forEach((d, i) => {
                  if (d.area > 0) {
                    this.result[index].data.push(d);
                    this.result[index].pieData.push(pies[i]);
                  }
                });
                /*if(this.result[index].pieData.length===0){
                  this.result.splice(index,1)
                }*/
              });
            }
          });
          if (isNull) return;
          this.key = this.result[0].type;
          if (this.gdXx) {
            this.key = '项目信息';
          }
          this.$message.success({ content: '分析成功!', key, duration: 1 });
          this.showCard();
          this.basicMap.analysisResult = true;
// this.getTypeSelected();
        }
      } else {
        if (message.includes('null')) {
          message = '没有分析到数据';
        }
        this.$message.info({ content: message, key, duration: 1 });
// this.getTypeSelected();

      }
      this.typeSelected = '';

    },
    clear() {
      this.typeSelected = '';
      this.basicMap.analysisResult = false;
      this.result = [];
      this.basicMap.analysis_GraphicsLayer.removeAll();
      this.basicMap.analysis_Drew_GraphicsLayer.removeAll();
      this.basicMap.mapView.graphics.removeAll();
    },
  },

};
</script>
<style scoped>
.info .content {
  margin-top: 15px;
  width: 100%;
  height: auto;
  position: relative;
  /*cursor: pointer;*/
  /*display: flex;*/
  flex-wrap: wrap;
  align-items: center;

}

.info {
  height: calc(100vh - 100px);
  margin-top: 20px;
  overflow-y: auto;
}

.content div {
  /*display: inline-block;*/
}

/*.content div>.caseother{
  display: block;
}*/
.content > div {
  /*width: 30%;*/
}

.locate-button {
  position: absolute;
  right: 2%;
  width: auto;
  top: 50%;
  transform: translateY(-50%);
}

</style>
<style>
.analysis .ant-tabs .ant-tabs-left-content{
  overflow-y: auto;
}
.analysis .ant-tabs-tab-prev, .ant-tabs-tab-next {
  color: rgba(0, 0, 0, 0.55);
}

:root .analysis .ant-tabs-tab-prev-icon-target, :root .analysis .ant-tabs-tab-next-icon-target {
  font-size: 24px;
}

.analysis .ant-tabs-tab-btn-disabled, .analysis .ant-tabs-tab-btn-disabled:hover {
  color: rgba(0, 0, 0, 0.25);
}

.analysis a > .anticon {
  /* vertical-align: 0.2em; */
}

.analysis .ant-radio-wrapper {
  width: 110px;
}

.analysis .ant-modal-mask {
  background-color: rgba(0, 0, 0, 0.08);
}

.analysis .ant-modal-content {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.analysis .ant-avatar {
  /* background: url("https://img1.baidu.com/it/u=1159474645,508069395&fm=26&fmt=auto"); */
}

.analysis .ant-list-item {
  align-items: flex-start;
}

.analysis .ant-list-item-action {
  margin-left: 10px;
  position: absolute;
  bottom: 3px;
  right: 0;
}

.analysis .ant-spin-nested-loading {
  max-height: 50vh;
  overflow-y: auto;

}
</style>
