<template>
    <div class="fatherDiv">
        <div class="centerBox">
            <div style="width: 100%; height: 100%" id="cesiumContainer"></div>
            <div class="leftWra">
                <div class="leftTop">
                    <div class="title">
                        <span>作物长势等级面积统计</span>
                        <p @click="Deta()">
                            下载 &nbsp;

                            <img
                                src="@/assets/icons/svg/downloads.svg"
                                style="width: 14px; height: 14px; cursor: pointer"
                            />
                        </p>
                    </div>
                    <div ref="areaDiv" class="areaDiv"></div>
                    <div ref="leftProgressBarDiv" class="ProgressBar"></div>
                </div>
                <div class="leftbottom">
                    <div class="title">
                        <span>作物长势等级面积占比</span>
                        <p @click="Deta2()">
                            下载 &nbsp;
                            <img
                                src="@/assets/icons/svg/downloads.svg"
                                style="width: 14px; height: 14px; cursor: pointer"
                            />
                        </p>
                    </div>
                    <div ref="typesofDiv" class="typesofDiv"></div>
                    <div class="tableDiv">
                        <el-table :data="tableData" style="width: 100%">
                            <el-table-column prop="date" label="类型" />
                            <el-table-column prop="name" label="面积(亩)" />
                            <el-table-column prop="address" label="占比" />
                        </el-table>
                    </div>
                </div>
                <div class="leftFoldDiv" @click="leftFoldClick()">
                    <el-tooltip
                        class="box-item"
                        :show-arrow="false"
                        :disabled="leftWraFlag"
                        hide-after="0"
                        show-after="200"
                        effect="dark"
                        content="展开"
                        placement="top"
                    >
                        <img v-if="!leftWraFlag" src="@/assets/images/close1.png" alt="" />
                    </el-tooltip>
                    <el-tooltip
                        :disabled="!leftWraFlag"
                        :show-arrow="false"
                        class="box-item"
                        show-after="200"
                        hide-after="0"
                        effect="dark"
                        content="收起"
                        placement="top"
                    >
                        <img
                            class="imgrotate"
                            v-if="leftWraFlag"
                            src="@/assets/images/close1.png"
                            alt=""
                        />
                    </el-tooltip>
                </div>
            </div>
            <div class="rightWra">
                <div class="rightTop">
                    <div class="title">
                        <span>作物长势等级统计-高标准农田</span>
                        <p @click="Deta3()">
                            下载 &nbsp;
                            <img
                                src="@/assets/icons/svg/downloads.svg"
                                style="width: 14px; height: 14px; cursor: pointer"
                            />
                        </p>
                    </div>
                    <div ref="farmlandDiv" class="farmlandDiv"></div>
                    <!-- <div ref="ProgressBarDiv" class="ProgressBar"></div> -->
                </div>
                <div class="rightbottom">
                    <div class="title">
                        <span>作物长势等级统计-行政区划</span>
                        <p @click="Deta4()">
                            下载 &nbsp;
                            <img
                                src="@/assets/icons/svg/downloads.svg"
                                style="width: 14px; height: 14px; cursor: pointer"
                            />
                        </p>
                    </div>
                    <el-select
                        popper-class="select_city"
                        @change="selectTab(item)"
                        v-model="value"
                        placeholder="全部"
                    >
                        <el-option
                            v-for="item in Township.arr"
                            :key="item.subregion"
                            :label="item.subregionName"
                            :value="item.subregion"
                        />
                    </el-select>
                    <div ref="ASdivisionDiv" class="ASdivision"></div>
                </div>
                <div class="rightFoldDiv" @click="rightFoldClick()">
                    <el-tooltip
                        :disabled="!rightWraFlag"
                        :show-arrow="false"
                        hide-after="0"
                        show-after="200"
                        class="box-item"
                        effect="dark"
                        content="收起"
                        placement="top"
                    >
                        <img v-if="rightWraFlag" src="@/assets/images/close1.png" alt="" />
                    </el-tooltip>
                    <el-tooltip
                        :disabled="rightWraFlag"
                        :show-arrow="false"
                        hide-after="0"
                        show-after="200"
                        class="box-item"
                        effect="dark"
                        content="展开"
                        placement="top"
                    >
                        <img
                            class="imgrotate"
                            v-if="!rightWraFlag"
                            src="@/assets/images/close1.png"
                            alt=""
                        />
                    </el-tooltip>
                </div>
            </div>

            <div class="bottom_center">
                <TimeLine />
            </div>
            <div class="tool">
                <span><img src="@/assets/images/LAYER.png" alt="" /></span>
                <span><img src="@/assets/images/amplify.png" alt="" /></span>
                <span><img src="@/assets/images/reduce.png" alt="" /></span>
                <span><img src="@/assets/images/measure.png" alt="" /></span>
                <span><img src="@/assets/images/face.png" alt="" /></span>
                <span><img src="@/assets/images/position.png" alt="" /></span>
            </div>
            <div id="popup">
                <div>
                    等级：
                    <p>{{ clickInfoMap.grade }}</p>
                </div>
                <div>
                    经度：
                    <p>{{ clickInfoMap.lon }}</p>
                </div>
                <div>
                    纬度：
                    <p>{{ clickInfoMap.lat }}</p>
                </div>
                <div class="cancel" @click="hiddenOverlayChart">X</div>
            </div>
            <div id="pop">
                <div v-for="(item, index) in townZuowu.label" :key="index">
                    <div>{{ item.crop }}：</div>
                    <div>{{ item.Shape_Area.toFixed(2) }} 亩</div>
                </div>
                <div v-if="townZuowu.XZQMC">
                    <div>村名：</div>
                    <div>{{ townZuowu.XZQMC }}</div>
                </div>
                <div class="cancel" @click="hiddenOverlayChart">X</div>
            </div>
            <el-collapse class="legend" accordion>
                <el-collapse-item name="1">
                    <template #title>图例</template>
                    <div class="mt-4">
                        <el-checkbox-group v-model="checkList" @change="change">
                            <el-checkbox
                                v-for="(value, item, key) in dic"
                                :key="key"
                                :style="{
                                    backgroundColor: value.color,
                                    border: `1px solid value.color`,
                                    width: `100%`,
                                }"
                                :v-model="value.disabled"
                                :disabled="value.disabled"
                                :label="item"
                            />
                        </el-checkbox-group>
                    </div>
                </el-collapse-item>
            </el-collapse>
            <el-button v-if="flag" class="back_button" @click="back()">返回</el-button>
        </div>
        <div class="tabulation">
            <div class="searchDiv">
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="时间:">
                        <el-select
                            popper-class="selectCity"
                            v-model="formInline.time"
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="(item, index) in timeArr"
                                :key="index"
                                :label="Zitem"
                                :value="item"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="统计方式:">
                        <el-select
                            popper-class="selectCity"
                            v-model="formInline.statistical"
                            placeholder="请选择"
                        >
                            <el-option label="镇级" value="镇" />
                            <el-option label="村级" value="村" />
                            <el-option label="高标准农田" value="高标准农田" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="长势等级">
                        <el-select
                            v-model="formInline.droughtRating"
                            popper-class="selectCity"
                            placeholder="请选择"
                        >
                            <el-option label="全部" value="" />
                            <el-option label="好" value="好" />
                            <el-option label="较好" value="较好" />
                            <el-option label="适中" value="适中" />
                            <el-option label="较差" value="较差" />
                            <el-option label="差" value="差" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="面积(亩)>">
                        <el-input-number v-model="num" :min="0" @change="handleChange" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">查询</el-button>
                        <el-button plain @click="resetForm" :disabled="!SwitchFlag ? true : false">
                            重置
                        </el-button>
                        <el-button v-if="!operate" type="primary" text @click="dowcity">
                            <img src="@/assets/images/dow.png" alt="" />
                            下载
                        </el-button>
                    </el-form-item>
                </el-form>
                <div class="modeDiv" @click="SwitchMode">
                    <div :class="SwitchFlag ? 'Selected' : ''">表格模式</div>
                    <div :class="SwitchFlag ? '' : 'Selecteds'">图表模式</div>
                </div>
            </div>
            <div v-show="SwitchFlag" class="tableBox">
                <div class="tableBorder">
                    <el-table
                        :data="amount"
                        :header-cell-style="{ 'text-align': 'center' }"
                        :cell-style="{ 'text-align': 'center' }"
                        style="width: 100%"
                        highlight-current-row
                        header-row-class-name="tabth"
                        v-if="!operate"
                    >
                        <el-table-column prop="" width="80" />
                        <el-table-column
                            v-for="(item, index) in tableItem"
                            :key="index"
                            :prop="item.value"
                            :label="index == 0 ? item.lable : item.lable + '(亩)'"
                        />
                    </el-table>
                </div>
                <el-table
                    :data="tableNewData"
                    :header-cell-style="{ 'text-align': 'center' }"
                    :cell-style="{ 'text-align': 'center' }"
                    height="80%"
                    highlight-current-row
                    header-row-class-name="tabth"
                >
                    <el-table-column type="index" width="80" label="序号" :index="Nindex" />
                    <el-table-column prop="subName" label="区域名称" />
                    <el-table-column prop="good" label="好(亩)" />
                    <el-table-column prop="better" label="较好(亩)" />
                    <el-table-column prop="moderate" label="适中(亩)" />
                    <el-table-column prop="difference" label="较差(亩)" />
                    <el-table-column prop="poor" label="差(亩)" />
                </el-table>
                <div class="example-pagination-block">
                    共{{ insectarr.length }}条
                    <el-pagination
                        background
                        layout="prev, pager, next"
                        :total="insectarr.length"
                        :current-page="currentPage"
                        :page-size="pageSize"
                        @current-change="handleCurrentChange"
                    />
                </div>
            </div>
            <div v-show="!SwitchFlag" class="chartMode">
                <div ref="chartModeDiv" class="chartModeDiv"></div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, inject, reactive, watch } from 'vue';
import * as echarts from 'echarts';
import TimeLine from '@/components/TimeLine/TimeLine.vue';
import * as xlsx from 'xlsx'; // Vue3 版本
// import * as turf from '@turf/turf';
import { useEcharts } from '@/hooks/useEcharts';
import {
    getfarmland,
    getstatistics,
    gethighStandards,
    getgradeStatistics,
    getadministrativeDivisions,
    getgarrison,
    getgrowthTime,
    getgrowthList,
} from '@/api/crops/site.js';
import axios from 'axios';
import 'echarts-gl';
import { download } from '@/utils/request';
import { useRouter } from 'vue-router';

const router = useRouter();
let viewer = ref(null);
const areaDiv = ref(null);
const typesofDiv = ref(null);
const farmlandDiv = ref(null);
const ProgressBarDiv = ref(null);
const ASdivisionDiv = ref(null);
const value = ref('370211');
const leftProgressBarDiv = ref(null);
let Township = reactive({ arr: [], brr: [], crr: [] }); //街道
let OptionArr = reactive({ arr: [] });
const clickInfoMap = ref({});
const checkedCities = ref([]);
const formLandRef = ref([]);
const flag = ref(false);
let leftWraFlag = ref(true);
let rightWraFlag = ref(true);
let ff = ref('{x:765,y:191}');
let areacharLable = ref([]); //面积统计
let areacharPrice = ref([]);
let totalArea = ref(0); //总面积
let farmlandData = ref([]);
let checkList = ref(['false']);
let checkListdata = ref([]);
const num = ref(0);
let timeArr = ref([]); //年数组
let SwitchFlag = ref(true);
const chartModeDiv = ref(null);
let currentPage = ref(1); //当前页
let pageSize = ref(12); //每页条数
let tableNewData = ref([]);
let tableItem = ref([]);
let operate = ref(true);
let amount = ref([
    {
        好: 0,
        较好: 0,
        适中: 0,
        较差: 0,
        差: 0,
    },
]);
let dowArr = ref([]);
let highStandard = [
    '高标准农田1.0',
    '高标准农田2.0',
    '高标准农田3.0',
    '高标准农田4.0',
    '高标准农田5.0',
    '高标准农田6.0',
    '高标准农田7.0',
];
let highStandarditem = {
    good: [], //好的
    better: [], //较好的
    moderate: [], //适中
    poor: [], //较差
    difference: [], //差
};
const insectarr = ref([]);
//搜索
let formInline = ref({
    time: '',
    statistical: '镇',
    droughtRating: '',
    area: num.value,
});

let typesofData = ref([]);
let dic = {
    好: { color: 'rgba(50, 148, 1, 1)', disabled: false },
    较好: { color: 'rgba(154, 208, 0, 1)', disabled: false },
    适中: { color: 'rgba(234, 219, 0, 1)', disabled: false },
    较差: { color: 'rgba(239, 152, 0, 1)', disabled: false },
    差: { color: 'rgba(247, 85, 0, 1)', disabled: false },
};
watch(
    () => checkList.value,
    (val, oldVal) => {
        if (val.length > oldVal.length) {
            // 挑选出增多的数据
            const newData = val.filter(item => {
                const index = oldVal.findIndex(it => it === item);
                if (index < 0) {
                    return item;
                }
            });
            newData.forEach(item => {
                switch (item) {
                    case '好':
                        addvillages(5, item);
                        break;
                    case '较好':
                        addvillages(4, item);
                        break;
                    case '适中':
                        addvillages(3, item);
                        break;
                    case '较差':
                        addvillages(2, item);
                        break;
                    case '差':
                        addvillages(1, item);
                        break;
                    default:
                        break;
                }
            });
            addWms('shuzisannong:huangdaoqu_town', 'tl');
        } else if (val.length < oldVal.length) {
            // 挑选出减少的数据
            const newData = oldVal.filter(item => {
                const index = val.findIndex(it => it === item);
                if (index < 0) {
                    return item;
                }
            });
            newData.forEach(item => {
                console.log(item);
                removeWms([item]);
            });
        }
    }
);
//行政区划数据
var data = {
    title: [],
};
let dd = ref({
    good: [],
    better: [],
    difference: [],
    moderate: [],
    poor: [],
});

const change = () => {
    console.log(checkedCities.value);
};

//表格数据
let tableData = ref([]);

// 组件挂载完成后执行
onMounted(() => {
    initonMounted();
});

function initonMounted() {
    getfarmlands('370211'); //作物长势等级面积统计
    getstatisticss('370211'); //作物长势等级面积占比
    gethighStandardss(); //高标准农田
    getTownships('370211'); //镇
    getgrowthTimes(); //年

    //地图
    initMap();
    getFarmland();

    for (const key in dic) {
        if (dic[key].disabled !== true) {
            console.log(key);
            checkListdata.value.push(key);
        }
    }
    checkList.value = checkListdata.value;
    localStorage.setItem(router.currentRoute.value.path, true);
}

onUpdated(() => {
    if (localStorage.getItem(router.currentRoute.value.path) == 'false') {
        document.querySelector('.mode').innerText = '地图模式';
    } else {
        document.querySelector('.mode').innerText = '列表模式';
    }
});

/*-------------地图------------------------*/
const mapOption = {
    url:
        'http://{s}.tianditu.gov.cn/img_c/wmts?service=wmts&request=GetTile&version=1.0.0' +
        '&LAYER=img&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        '&style=default&format=tiles&tk=31091965e263284a501a723b8909f405',
    layer: 'tdtCva',
    style: 'default',
    format: 'tiles',
    tileMatrixSetID: 'c',
    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    tilingScheme: new Cesium.GeographicTilingScheme(),
    tileMatrixLabels: [
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        '10',
        '11',
        '12',
        '13',
        '14',
        '15',
        '16',
        '17',
        '18',
        '19',
    ],
    maximumLevel: 18,
};
Cesium.Ion.defaultAccessToken =
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiYzcwZmJmNi02MzQ5LTQ1MGEtODgzMy0yZTZiZGExY2MzMGMiLCJpZCI6MTAxOTgsInNjb3BlcyI6WyJhc2wiLCJhc3IiLCJnYyJdLCJpYXQiOjE1ODEzMDgxNTR9.NeJU4yfUi-SnLrNDOBYsQgmiSh3B4axCTi1m84Qw99c';
function initMap() {
    viewer = new Cesium.Viewer('cesiumContainer', {
        baseLayerPicker: false,
        shouldAnimate: true, //自动播放
        infoBox: false, //信息框
        animation: false, //“动画”窗口小部件提供用于播放，暂停和倒退的按钮，以及当前时间和日期，并由“飞梭环”包围，用于控制动画的速度。cesium示例地图左下角那个
        timeline: false, //时间轴是用于显示和控制当前场景时间的小部件。
        geocoder: false, //查找，用于查找地址和地标，以及将照相机悬挂到它们。使用铯离子进行地址解析。,cesium示例地图右上角的放大镜
        homeButton: false, //主页按钮
        navigationHelpButton: false, //导航帮助按钮
        selectionIndicator: false, //原生选择绿框
        fullscreenButton: false, //右下角的全屏按钮
        // terrainProvider:new Cesium.createWorldTerrain(),
        terrainProvider: new Cesium.EllipsoidTerrainProvider({}),
        sceneModePicker: false, //是否显示投影方式控件
        contextOptions: {
            webgl: {
                alpha: true,
            },
        },

        imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
            ...mapOption,
        }),
    });
    // 去除logo
    viewer.cesiumWidget.creditContainer.style.display = 'none';
    viewer.camera.flyTo({
        destination: Cesium.Rectangle.fromDegrees(119.5091, 35.5671, 120.3285, 36.1455),
        duration: 0,
    });

    // 图层点击事件
    layerClick();
    // 蒙版
    mbHandle();
}

// data数据数组
// name实体名称，方便以后删除
// color实体颜色
function addBoundaryHandle(data, name, color) {
    data.forEach(item => {
        let arr = [];
        item[0].forEach(mem => {
            arr.push(mem[0]);
            arr.push(mem[1]);
        });
        viewer.entities.add({
            name: name,
            polyline: {
                positions: Cesium.Cartesian3.fromDegreesArray(arr),
                width: 6,
                // material: new Cesium.PolylineDashMaterialProperty({//虚线
                material: new Cesium.PolylineGlowMaterialProperty({
                    //光晕
                    glowPower: 0.2,
                    color: color
                        ? Cesium.Color.fromCssColorString(color)
                        : Cesium.Color.fromBytes(250, 128, 114), //#FA8072
                }),
                // followSurface: false, //是否贴着地表
                clampToGround: true, //贴地
            },
        });
    });
}
function getLevel(height) {
    if (height > 48000000) {
        return 0;
    } else if (height > 24000000) {
        return 1;
    } else if (height > 12000000) {
        return 2;
    } else if (height > 6000000) {
        return 3;
    } else if (height > 3000000) {
        return 4;
    } else if (height > 1500000) {
        return 5;
    } else if (height > 750000) {
        return 6;
    } else if (height > 375000) {
        return 7;
    } else if (height > 187500) {
        return 8;
    } else if (height > 93750) {
        return 9;
    } else if (height > 46875) {
        return 10;
    } else if (height > 23437.5) {
        return 11;
    } else if (height > 11718.75) {
        return 12;
    } else if (height > 5859.38) {
        return 13;
    } else if (height > 2929.69) {
        return 14;
    } else if (height > 1464.84) {
        return 15;
    } else if (height > 732.42) {
        return 16;
    } else if (height > 366.21) {
        return 17;
    } else {
        return 18;
    }
}
function getFarmland() {
    axios({
        url:
            serverAPI.geoserverUrl +
            '/shuzisannong/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=shuzisannong%3Afarmland&maxFeatures=50&outputFormat=application%2Fjson',
        method: 'get',
    })
        .then(res => {
            console.log('农田：', res);
            formLandRef.value = res.data.features;
        })
        .catch(err => {});
}

let townZuowu = ref({ label: [] }); //镇的作物
let XZDM = '';
// 图层点击事件
function layerClick() {
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    handler.setInputAction(function (movement) {
        var ray = viewer.camera.getPickRay(movement.position);
        var cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        if (cartesian) {
            let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
            if (cartographic) {
                let xy = new Cesium.Cartesian2();
                let alti = viewer.camera.positionCartographic.height;
                let level = getLevel(alti);
                const layers = viewer.imageryLayers._layers;
                // 筛选出黄岛区服务
                const index = layers.findIndex(
                    item =>
                        item._imageryProvider._layers &&
                        item._imageryProvider._layers === 'shuzisannong:huangdaoqu_town'
                );
                if (index > -1) {
                    const providerPoint = layers[index];
                    // 拿取最后一个图层
                    let provider = providerPoint._imageryProvider;
                    if (
                        provider &&
                        provider.ready &&
                        provider._layers &&
                        providerPoint.show === true
                    ) {
                        xy = provider.tilingScheme.positionToTileXY(cartographic, level, xy);
                        let promise = provider.pickFeatures(
                            xy.x,
                            xy.y,
                            level,
                            cartographic.longitude,
                            cartographic.latitude
                        );
                        if (promise) {
                            promise.then(data => {
                                if (data.length > 0) {
                                    let newData = data['0'];
                                    if (newData.properties && newData.properties.XZDM) {
                                        console.log('XZDM:', XZDM);
                                        console.log(
                                            'newData.properties.XZDM:',
                                            newData.properties.XZDM
                                        );
                                        if (XZDM !== newData.properties.XZDM) {
                                            flag.value = true;
                                            //防止重复加载
                                            XZDM = newData.properties.XZDM;
                                            value.value = XZDM; //
                                            if (selectTab) {
                                                selectTab(); //
                                            }
                                            let item = newData.data;
                                            // 定位
                                            viewer.camera.flyTo({
                                                destination: Cesium.Rectangle.fromDegrees(
                                                    item.bbox[0],
                                                    item.bbox[1],
                                                    item.bbox[2],
                                                    item.bbox[3]
                                                ),
                                                duration: 2,
                                            });
                                            // 移除高亮
                                            deleteEntityByName('townLine');
                                            // 高亮边界
                                            addBoundaryHandle(
                                                item.geometry && item.geometry.coordinates,
                                                'townLine',
                                                'yellow'
                                            );
                                            // // 移除以前的
                                            removeWms(['village_CQL']);
                                            // 添加新的
                                            console.log(newData.properties.XZDM);
                                            addvillage(
                                                `XZDM=${newData.properties.XZDM}`,
                                                'village_CQL'
                                            );

                                            // 显示该镇的种植结构
                                            let entitys = viewer.entities._entities._array;
                                            for (var na = entitys.length - 1; na >= 0; na--) {
                                                if (
                                                    entitys[na]._name &&
                                                    entitys[na]._name ===
                                                        'point' + newData.properties.XZDM
                                                ) {
                                                    let info = entitys[na]._info;
                                                    // entitys[na].label.show = true
                                                    townZuowu.value = info; //保存数据
                                                    showOverlayChart(movement.position); // 添加地图移动监听：使地图移动弹窗跟着移动
                                                    viewer.scene.postRender.addEventListener(
                                                        infoWindowPostRender
                                                    );
                                                } else {
                                                    // if (entitys[na].label) {
                                                    //     entitys[na].label.show = false
                                                    // }
                                                }
                                            }
                                            // 移除村高亮
                                            deleteEntityByName('villageLine');
                                            XZQDM = '';
                                        } else {
                                            // // 已经有镇了，监听村点击
                                            villageClick(layers, xy, level, cartographic, movement);
                                        }
                                    } else {
                                        removeWms(['village_CQL']);
                                        // 移除框框
                                        hiddenOverlayChart(); // 清除监听事件
                                    }
                                }
                            });
                        }
                    }
                }
            }
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}
let XZQDM = '';
// 村点击高亮
function villageClick(layers, xy, level, cartographic, movement) {
    const index = layers.findIndex(
        item =>
            item._imageryProvider._layers &&
            item._imageryProvider._layers === 'shuzisannong:huangdaoqu_village'
    );
    if (index > -1) {
        const providerPoint = layers[index];
        // 拿取最后一个图层
        let provider = providerPoint._imageryProvider;
        if (provider && provider.ready && provider._layers && providerPoint.show === true) {
            xy = provider.tilingScheme.positionToTileXY(cartographic, level, xy);
            let promise = provider.pickFeatures(
                xy.x,
                xy.y,
                level,
                cartographic.longitude,
                cartographic.latitude
            );
            if (promise) {
                promise.then(data => {
                    if (data.length > 0) {
                        let newData = data['0'];
                        console.log(newData);
                        viewer.camera.flyTo({
                            destination: Cesium.Rectangle.fromDegrees(
                                newData.data.bbox[0],
                                newData.data.bbox[1],
                                newData.data.bbox[2],
                                newData.data.bbox[3]
                            ),
                            duration: 2,
                        });

                        if (newData.properties && newData.properties.XZQDM) {
                            if (XZQDM !== newData.properties.XZQDM) {
                                //防止
                                XZQDM = newData.properties.XZQDM;
                                let item = newData.data;
                                // 移除高亮
                                deleteEntityByName('villageLine');
                                // 高亮边界
                                addBoundaryHandle(
                                    item.geometry && item.geometry.coordinates,
                                    'villageLine',
                                    'yellow'
                                );
                            } else {
                                massif(layers, xy, level, cartographic, movement);
                            }
                        }
                    }
                });
            }
        }
    }
}
function massif(layers, xy, level, cartographic, movement) {
    console.log(layers);
    const index = layers.findIndex(
        item =>
            item._imageryProvider._layers && item._imageryProvider._layers === 'shuzisannong:growth'
    );
    if (index > -1) {
        const providerPoint = layers[index];
        // 拿取最后一个图层
        let provider = providerPoint._imageryProvider;
        if (provider && provider.ready && provider._layers && providerPoint.show === true) {
            xy = provider.tilingScheme.positionToTileXY(cartographic, level, xy);
            let promise = provider.pickFeatures(
                xy.x,
                xy.y,
                level,
                cartographic.longitude,
                cartographic.latitude
            );
            if (promise) {
                promise.then(data => {
                    if (data.length > 0) {
                        let newData = data['0'];
                        let grade = '';
                        switch (newData.properties.value) {
                            case 1:
                                grade = '差';
                                break;
                            case 2:
                                grade = '较差';
                                break;
                            case 3:
                                grade = '适中';
                                break;
                            case 4:
                                grade = '较好';
                                break;
                            case 5:
                                grade = '好';
                                break;
                            default:
                                break;
                        }
                        let longitudeString = Cesium.Math.toDegrees(cartographic.longitude).toFixed(
                            6
                        );
                        let latitudeString = Cesium.Math.toDegrees(cartographic.latitude).toFixed(
                            6
                        );
                        clickInfoMap.value = {
                            lon: longitudeString,
                            lat: latitudeString,
                            grade: grade,
                        };
                        console.log(clickInfoMap.value);
                        showOverlayChart(movement.position); // 添加地图移动监听：使地图移动弹窗跟着移动
                        viewer.scene.postRender.addEventListener(infoWindowPostRender);
                    }
                });
            }
        }
    }
}

//添加地图
function addvillages(value, customName) {
    let map2 = new Cesium.WebMapServiceImageryProvider({
        url: `${serverAPI.geoserverUrl}/shuzisannong/wms`,
        layers: 'shuzisannong:growth', //图层名
        parameters: {
            service: 'WMS',
            format: 'image/png',
            transparent: true, //是否透明
            // CQL_FILTER: `XZDM=${value.value}`,
            CQL_FILTER: `value in (${value})`,
        },
    });
    map2.customName = customName;
    viewer.imageryLayers.addImageryProvider(map2);
}
// 添加村
// CQL_FILTER:筛选的语句
// customName地图服务自定义属性名
function addvillage(CQL_FILTER, customName) {
    let map2 = new Cesium.WebMapServiceImageryProvider({
        url: `${serverAPI.geoserverUrl}/shuzisannong/wms`,
        layers: 'shuzisannong:huangdaoqu_village', //图层名
        parameters: {
            service: 'WMS',
            format: 'image/png',
            transparent: true, //是否透明
            // CQL_FILTER: `XZDM=${value.value}`,
            CQL_FILTER: CQL_FILTER,
        },
    });
    map2.customName = customName;
    viewer.imageryLayers.addImageryProvider(map2);
}
// 移除wms
// nameArry ：属性名数组（customName）
// isMohu ：是否模糊查询
function removeWms(nameArry, isMohu) {
    if (viewer) {
        // 倒叙遍历，customName是自定义的属性
        const layers = viewer.imageryLayers._layers;
        for (let f = layers.length - 1; f >= 0; f--) {
            nameArry.forEach(item => {
                if (layers[f]._imageryProvider && layers[f]._imageryProvider.customName) {
                    if (isMohu) {
                        if (layers[f]._imageryProvider.customName.indexOf(item) > -1) {
                            viewer.imageryLayers.remove(layers[f]);
                        }
                    } else {
                        if (layers[f]._imageryProvider.customName === item) {
                            viewer.imageryLayers.remove(layers[f]);
                        }
                    }
                }
            });
        }
    }
}

// 根据实体名字删除实体(模糊删除)
function deleteEntityByName(name) {
    if (viewer) {
        let entitys = viewer.entities._entities._array;
        for (var na = entitys.length - 1; na >= 0; na--) {
            if (entitys[na]._name && entitys[na]._name === name) {
                viewer.entities.remove(entitys[na]);
            }
        }
    }
}
//折叠

function leftFoldClick() {
    leftWraFlag.value = !leftWraFlag.value;
    if (leftWraFlag.value) {
        let leftWra = document.querySelector('.leftWra');
        leftWra ? (leftWra.style.transform = 'translate(0,0)') : '';
    } else {
        let leftWra = document.querySelector('.leftWra');
        leftWra ? (leftWra.style.transform = 'translate(-107%,0)') : '';
    }
    console.log(leftWraFlag.value);
}
function rightFoldClick() {
    rightWraFlag.value = !rightWraFlag.value;
    if (rightWraFlag.value) {
        let rightWra = document.querySelector('.rightWra');
        rightWra.style.transform = 'translate(0,0)';
    } else {
        let rightWra = document.querySelector('.rightWra');
        rightWra.style.transform = 'translate(107%,0)';
    }
}
const resetForm = () => {
    (formInline.value.time = timeArr.value[0]),
        (formInline.value.statistical = '镇'),
        (formInline.value.droughtRating = ''),
        (formInline.value.area = 1),
        (operate.value = true);
    onSubmit();
};
//列表模式模式切换
const SwitchMode = () => {
    SwitchFlag.value = !SwitchFlag.value;
    const statInfo = chartModeDiv.value; // 获取图表元素
    statInfo.style.width = window.innerWidth - 200 + 'px'; //初始化echarts图表宽度
    statInfo.style.height = window.innerHeight - 200 + 'px';
    const myChart = echarts.init(statInfo);
    // 设置宽度自适应
    window.addEventListener('resize', () => {
        statInfo.style.width = window.innerWidth - 200 + 'px';
        statInfo.style.height = window.innerHeight - 200 + 'px';
        myChart.resize();
    });
    chartModes();
};
const handleChange = value => {
    formInline.value.area = value;
};
//搜索
const onSubmit = () => {
    let arr = [];
    let brr = [];
    currentPage.value = 1;
    getgrowthList({
        time: formInline.value.time,
        statistical: formInline.value.statistical,
        droughtRating: formInline.value.droughtRating,
        area: formInline.value.area,
    }).then(res => {
        tableItem.value = [
            {
                lable: '',
                value: '区域名称',
            },
            {
                lable: '好',
                value: '好',
            },
            {
                lable: '较好',
                value: '较好',
            },
            {
                lable: '适中',
                value: '适中',
            },
            {
                lable: '较差',
                value: '较差',
            },
            {
                lable: '差',
                value: '差',
            },
        ];

        operate.value = false;
        insectarr.value = res.data;
        tableNewData.value = res.data.slice(
            (currentPage.value - 1) * pageSize.value,
            (currentPage.value - 1) * pageSize.value + pageSize.value
        );
        console.log(tableNewData.value);
        tableNewData.value.forEach(item => {
            dowArr.value.push({
                区域名称: item.subName,
                好: item.good,
                较好: item.better,
                适中: item.moderate,
                较差: item.difference,
                差: item.poor,
            });
        });

        amount.value[0]['好'] = 0;
        amount.value[0]['较好'] = 0;
        amount.value[0]['适中'] = 0;
        amount.value[0]['较差'] = 0;
        amount.value[0]['差'] = 0;
        amount.value[0]['区域名称'] = '合计';
        res.data.forEach(item => {
            item.good
                ? (amount.value[0]['好'] += Number(item.good) !== NaN ? Number(item.good) : 0)
                : 0;
            item.better
                ? (amount.value[0]['较好'] += Number(item.better) !== NaN ? Number(item.better) : 0)
                : 0;
            item.moderate
                ? (amount.value[0]['适中'] +=
                      Number(item.moderate) !== NaN ? Number(item.moderate) : 0)
                : 0;
            item.difference
                ? (amount.value[0]['较差'] +=
                      Number(item.difference) !== NaN ? Number(item.difference) : 0)
                : 0;
            item.poor
                ? (amount.value[0]['差'] += Number(item.poor) !== NaN ? Number(item.poor) : 0)
                : 0;
        });
        for (const key in amount.value[0]) {
            if (amount.value[0][key] !== '合计') {
                amount.value[0][key] = amount.value[0][key].toFixed(2);
            }
        }
        const statInfo = chartModeDiv.value; // 获取图表元素
        statInfo.style.width = window.innerWidth - 100 + 'px'; //初始化echarts图表宽度
        statInfo.style.height = window.innerHeight - 100 + 'px';
        const myChart = echarts.init(statInfo);
        // 设置宽度自适应
        window.addEventListener('resize', () => {
            statInfo.style.width = window.innerWidth - 200 + 'px';
            statInfo.style.height = window.innerHeight - 200 + 'px';
            myChart.resize();
        });
        chartModes();
    });
};
//每页条数
const handleCurrentChange = val => {
    currentPage.value = val;
    tableNewData.value = insectarr.value.slice(
        (currentPage.value - 1) * pageSize.value,
        (currentPage.value - 1) * pageSize.value + pageSize.value
    );
};
const Nindex = index => {
    // 当前页数 - 1 * 每页数据条数 + 1
    const page = currentPage.value; // 当前页码
    const pagesize = pageSize.value; // 每页条数
    return index + 1 + (page - 1) * pagesize;
};

/*------------------接口--------------------*/
//获取年
const getgrowthTimes = () => {
    getgrowthTime().then(res => {
        timeArr.value = res.data;
        formInline.value.time = res.data[0];
        onSubmit();
    });
};

//作物长势等级面积统计
const getfarmlands = city => {
    areacharLable = ref([]);
    areacharPrice = ref([]);
    getfarmland({ divisions: city }).then(res => {
        for (const key in res.data[0]) {
            if (res.data[0][key]) {
                areacharLable.value.push(key);
                areacharPrice.value.push(res.data[0][key]);
            }
        }
        areachar();
    });
};
//作物长势等级面积占比
const getstatisticss = city => {
    typesofData = ref([]);
    tableData.value = [];
    totalArea = ref(0);
    getstatistics({ divisions: city }).then(res => {
        console.log(res.data);
        res.data.forEach(item => {
            totalArea.value = Number(item.sum);
            console.log(item);
            for (const key in item) {
                if (key !== 'sum' && Number.isFinite(item[key])) {
                    typesofData.value.push({
                        name: key,
                        value: item[key],
                    });
                    tableData.value.push({
                        date: key,
                        name: item[key],
                    });
                }
                tableData.value.forEach(it => {
                    if (item[`${it.date}Zb`] !== undefined) {
                        it['address'] = (item[`${it.date}Zb`] * 100).toFixed(2) + '%';
                    }
                });
                let arr = JSON.parse(JSON.stringify(tableData.value));
                arr.forEach(it => {
                    switch (it.date) {
                        case 'good':
                            it.date = '好';
                            break;
                        case 'better':
                            it.date = '较好';
                            break;
                        case 'moderate':
                            it.date = '适中';
                            break;
                        case 'poor':
                            it.date = '较差';
                            break;
                        case 'difference':
                            it.date = '差';
                            break;

                        default:
                            break;
                    }
                });
                tableData.value = arr;
            }
        });
        typesof();
    });
};
//高标准农田统计

const gethighStandardss = () => {
    farmlandData = ref([]);
    gethighStandards().then(res => {
        highStandard.forEach((item, index) => {
            let town = res.data.map(i => {
                if (item === i.region) {
                    for (const key in i) {
                        if (highStandarditem[key]) {
                            highStandarditem[key].push(i[key]);
                        }
                    }
                }
            });
        });
        farmland();
    });
};

//镇
const getTownships = city => {
    dd.value['better'] = [];
    dd.value['difference'] = [];
    dd.value['good'] = [];
    dd.value['moderate'] = [];
    dd.value['poor'] = [];
    getgradeStatistics({ divisions: city, yearMonth: '2023-05' }).then(res => {
        console.log(res.data);
        Township.brr = res.data;
        Township.arr = res.data.sort((a, b) => {
            return a.subregionName.length - b.subregionName.length;
        });
        Township.arr.unshift({
            subregion: '370211',
            subregionName: '全部',
        });
        let arr = [...res.data];
        let brr = [];
        arr.splice(0, 1);
        arr.forEach(item => {
            if (brr.indexOf(item.subregionName) == -1) {
                brr.push(item.subregionName);
            }
        });
        data.title = [...Object.values(brr)];
        data.title.forEach((item, index) => {
            let town = res.data.map(i => {
                if (item === i.subregionName) {
                    dd.value['better'].push(i.better);
                    dd.value['difference'].push(i.difference);
                    dd.value['good'].push(i.good);
                    dd.value['moderate'].push(i.moderate);
                    dd.value['poor'].push(i.poor);
                    return i;
                }
            });
        });
        console.log(dd);
        ASdivision();
    });
};
//村
const getvillages = city => {
    let newdd = {
        good: [],
        better: [],
        difference: [],
        moderate: [],
        poor: [],
    };
    getadministrativeDivisions({ divisions: city }).then(res => {
        console.log(res.data);
        Township.brr = res.data;
        let arr = [...res.data];
        let brr = [];
        arr.forEach(item => {
            if (brr.indexOf(item.subregionName) == -1) {
                brr.push(item.subregionName);
            }
        });
        data.title = [...Object.values(brr)];
        data.title.forEach((item, index) => {
            let town = res.data.map(i => {
                if (item === i.subregionName) {
                    newdd['better'].push(i.better);
                    newdd['difference'].push(i.difference);
                    newdd['good'].push(i.good);
                    newdd['moderate'].push(i.moderate);
                    newdd['poor'].push(i.poor);
                    return i;
                }
            });
        });
        dd.value = newdd;
        ASdivision();
    });
};

const selectTab = () => {
    getgarrison().then(res => {
        console.log(res);
        res.features.forEach(item => {
            if (item.properties.XZDM == value.value) {
                deleteEntityByName('townLine');
                addBoundaryHandle(item.geometry.coordinates, 'townLine', 'yellow');
                viewer.camera.flyTo({
                    destination: Cesium.Rectangle.fromDegrees(
                        item.bbox[0],
                        item.bbox[1],
                        item.bbox[2],
                        item.bbox[3]
                    ),
                    duration: 0,
                });
            }
        });
    });
    viewer.camera.flyTo({
        destination: Cesium.Rectangle.fromDegrees(119.5091, 35.5671, 120.3285, 36.1455),
        duration: 2,
    });
    getfarmlands(value.value); //作物长势等级面积统计
    getstatisticss(value.value); //作物长势等级面积占比
    if (value.value !== '370211') {
        getvillages(value.value); //村
    }

    if (value.value == '370211') {
        removeWms(['village_CQL']);
        removeWms(['aaa']);
        getTownships();
        hiddenOverlayChart();
    }
    let arr = [...Township.arr];
    console.log('arr:', arr);
    // arr.forEach(item => {
    //     if (item.properties.XZDM == value.value) {
    //         viewer.camera.flyTo({
    //             destination: Cesium.Rectangle.fromDegrees(
    //                 item.bbox[0],
    //                 item.bbox[1],
    //                 item.bbox[2],
    //                 item.bbox[3]
    //             ),
    //             duration: 2,
    //         });
    //     }
    //     let arr = [...Township.brr];
    //     let brr = [];
    //     // console.log(Township.brr);
    //     arr.forEach(item => {
    //         if (item.properties.XZDM == value.value) {
    //             brr.push(item.properties.XZQMC);
    //         }
    //     });
    //     // console.log(brr);
    //     data.title = [...Object.values(brr)];
    // });
    let town = [...Township.arr];
    // const townData = town.find(item => item.properties.XZDM === value.value);
    // if (townData) {
    //     // 移除镇高亮
    //     deleteEntityByName('townLine');
    //     // 高亮镇边界
    //     addBoundaryHandle(townData.geometry.coordinates, 'townLine', 'yellow');
    // }
    // 移除以前村
    removeWms(['aaa']);
    // 添加村
    addvillage(`XZDM=${value.value}`, 'aaa');
    // getarea({ time: '2023-04-26', subregion: '1', parent: '黄岛区' }).then(res => {
    //     let arr = [];
    //     res.data.map((item, index) => {
    //         if (item.region == townData.properties.XZMC) {
    //             arr.push({
    //                 crop: item.type,
    //                 Shape_Area: item.area,
    //             });
    //         }
    //     });
    //     townZuowu.value = {
    //         label: arr,
    //     };
    //     console.log(arr);
    //     showOverlayChart({ x: 642, y: 312 });
    // });
};

//下载
/*---------------------------*/
const Deta = item => {
    let region = '';
    Township.arr.forEach(item => {
        if (item.subregion == value.value) {
            region = item.subregionName == '全部' ? '黄岛区' : item.subregionName;
        }
    });
    getfarmland({ divisions: value.value }).then(res => {
        let arr = [
            {
                region: region == '全部' ? '黄岛区' : region,
                good: res.data[0].good,
                better: res.data[0].better,
                moderate: res.data[0].moderate,
                poor: res.data[0].poor,
                difference: res.data[0].difference,
            },
        ];
        exportExcel(arr, `${arr[0].region}作物长势等级面积统计`, 'Sheet1');
    });
};
const Deta2 = item => {
    let region = '';
    Township.arr.forEach(item => {
        if (item.subregion == value.value) {
            region = item.subregionName == '全部' ? '黄岛区' : item.subregionName;
        }
    });
    console.log(tableData);
    exportExcels(tableData.value, `${region}作物长势等级面积占比`, 'Sheet1');
};
const Deta3 = item => {
    let arr = [];
    gethighStandards().then(res => {
        console.log(res.data);
        res.data.forEach(item => {
            arr.push({
                region: item.region,
                good: item.good,
                better: item.better,
                moderate: item.moderate,
                poor: item.poor,
                difference: item.difference,
            });
        });
        exportExcel(arr, '作物长势等级统计-高标准农田列表', 'Sheet1');
    });
};
const Deta4 = item => {
    let region = '';
    let arr = [];
    Township.arr.forEach(item => {
        if (item.subregion == value.value) {
            region = item.subregionName == '全部' ? '黄岛区' : item.subregionName;
        }
    });
    if (value.value === '370211') {
        getgradeStatistics({ divisions: value.value, whetherToDownload: false }).then(res => {
            res.data.forEach(item => {
                console.log(item);
                arr.push({
                    region: item.subregionName,
                    good: item.good,
                    better: item.better,
                    moderate: item.moderate,
                    poor: item.poor,
                    difference: item.difference,
                });
            });
            exportExcel(arr, `${region}作物长势等级统计-行政区划`, 'Sheet1');
        });
    } else {
        getadministrativeDivisions({ divisions: value.value, whetherToDownload: false }).then(
            res => {
                res.data.forEach(item => {
                    console.log(item)
                    arr.push({
                        region: item.subregionName,
                        good: item.good,
                        better: item.better,
                        moderate: item.moderate,
                        poor: item.poor,
                        difference: item.difference,
                    });
                });
                exportExcel(arr, `${region}作物长势等级统计-行政区划`, 'Sheet1');
            }
        );
    }
};

const dowcity = () => {
    console.log(insectarr);
    let arr = JSON.parse(JSON.stringify(amount.value[0]));
    arr.region = '合计';
    dowArr.value.push(arr);
    exportExcelss(dowArr.value, '长势面积统计表', 'Sheet1');
};

//表头数据切换  ----------前端生成excel
const changeTableHead = (tableData, fieldName) => {
    const list = tableData.map(item => {
        const obj = {};
        for (const k in item) {
            if (fieldName[k]) {
                obj[fieldName[k]] = item[k];
            }
        }
        return obj;
    });
    return list;
};
const exportExcel = (tableData, fileName = '用户列表', pageName = 'Sheet1') => {
    let fieldNameObj = {
        region: '区域名称',
        good: '好(亩)',
        better: '较好(亩)',
        moderate: '适中(亩)',
        difference: '较差(亩)',
        poor: '差(亩)',
    };
    const list = changeTableHead(tableData, fieldNameObj);
    // 创建工作表
    const data = xlsx.utils.json_to_sheet(list);
    // 创建工作簿
    const wb = xlsx.utils.book_new();
    // 将工作表放入工作簿中
    xlsx.utils.book_append_sheet(wb, data, pageName);
    // 生成文件并下载
    xlsx.writeFile(wb, `${fileName}.xlsx`);
};

const exportExcels = (tableData, fileName = '用户列表', pageName = 'Sheet1') => {
    let fieldNameObj = {
        date: '类型',
        name: '面积(亩)',
        address: '占比',
    };
    const list = changeTableHead(tableData, fieldNameObj);
    // 创建工作表
    const data = xlsx.utils.json_to_sheet(list);
    // 创建工作簿
    const wb = xlsx.utils.book_new();
    // 将工作表放入工作簿中
    xlsx.utils.book_append_sheet(wb, data, pageName);
    // 生成文件并下载
    xlsx.writeFile(wb, `${fileName}.xlsx`);
};
const exportExcelss = (tableData, fileName = '用户列表', pageName = 'Sheet1') => {
    let fieldNameObj = {
        区域名称: '区域名称',
        好: '好(亩)',
        较好: '较好(亩)',
        适中: '适中(亩)',
        较差: '较差(亩)',
        差: '差(亩)',
    };
    const list = changeTableHead(tableData, fieldNameObj);
    // 创建工作表
    const data = xlsx.utils.json_to_sheet(list);
    // 创建工作簿
    const wb = xlsx.utils.book_new();
    // 将工作表放入工作簿中
    xlsx.utils.book_append_sheet(wb, data, pageName);
    // 生成文件并下载
    xlsx.writeFile(wb, `${fileName}.xlsx`);
};

/*-------------echarts--------------*/
function areachar() {
    const areaDivIntance = echarts.init(areaDiv.value);
    // let dataX = areacharLable.value; //名称
    let dataX = ['好', '较好', '适中', '较差', '差']; //名称
    let dataY = areacharPrice.value; //数据
    let zoomShow = false;
    if (dataY.length > 14) {
        zoomShow = true;
    } else {
        zoomShow = false;
    }
    var option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
            },
        },
        grid: {
            top: '10%',
            right: '5%',
            left: '18%',
            bottom: '10%',
        },
        xAxis: [
            {
                type: 'category',
                data: dataX,
                axisLine: {
                    lineStyle: {
                        color: 'rgba(66, 192, 255, .3)',
                    },
                },
                axisLabel: {
                    interval: 0,
                    margin: 10,
                    color: 'rgba(255, 255, 255, 0.7)',
                    textStyle: {
                        fontSize: 14,
                    },
                    rotate: '0',
                },
                axisTick: {
                    //刻度
                    show: false,
                },
            },
        ],
        yAxis: {
            name: '面积(亩)',
            nameTextStyle: {
                color: 'rgba(255, 255, 255, 0.8)',
                fontSize: 14,
            },
            type: 'value',
            axisLabel: {
                color: 'rgba(255,255,255,0.7)',
            },
            splitLine: {
                // lineStyle: {
                //     type: 'dashed',
                // },
                show: false,
            },
            minInterval: 1,
            axisLine: {
                show: false,
            },
            axisTick: {
                show: false,
            },
        },
        dataZoom: [
            //滚动条
            {
                show: zoomShow,
                zoomLock: true, //禁止拉伸
                type: 'slider',
                realtime: true,
                startValue: 0,
                endValue: 14,
                xAxisIndex: [0],
                bottom: '10',
                left: '30',
                height: 10,
                borderColor: 'rgba(0,0,0,0)',
                textStyle: {
                    color: '#05D5FF',
                },
            },
        ],
        series: [
            {
                type: 'bar',
                data: dataY,
                barWidth: '15',
                itemStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(
                            0,
                            0,
                            0,
                            1,
                            [
                                {
                                    offset: 0,
                                    color: 'rgba(45, 204, 177, 1)', // 0% 处的颜色
                                },
                                {
                                    offset: 0.98,
                                    color: 'rgba(71, 179, 161, 0)', // 100% 处的颜色
                                },
                            ],
                            false
                        ),
                        shadowColor: 'rgba(5, 213, 255, 1)',
                        shadowBlur: 4,
                    },
                },
                label: {
                    normal: {
                        show: true,
                        lineHeight: 10,
                        formatter: '{c}',
                        position: 'top',
                        textStyle: {
                            color: '#fff',
                            fontSize: 10,
                        },
                    },
                },
            },
        ],
    };

    option && areaDivIntance.setOption(option);

    window.addEventListener('resize', function () {
        areaDivIntance.resize();
    });
}

function typesof() {
    const typesofDivIntance = echarts.init(typesofDiv.value);
    typesofData.value.forEach(item => {
        switch (item.name) {
            case 'good':
                item.name = '好';
                break;
            case 'better':
                item.name = '较好';
                break;
            case 'moderate':
                item.name = '适中';
                break;
            case 'poor':
                item.name = '较差';
                break;
            case 'difference':
                item.name = '差';
                break;

            default:
                break;
        }
    });
    var data = typesofData.value;

    let option = {
        color: [
            'rgba(50, 148, 1, 1)',
            'rgba(154, 208, 0, 1)',
            'rgba(234, 219, 0, 1)',
            'rgba(239, 152, 0, 1)',
            'rgba(247, 85, 0, 1)',
        ],
        title: {
            text: '总面积',
            subtext: `${totalArea.value}亩`,
            textStyle: {
                color: '#f2f2f2',
                fontSize: 14,
                // align: 'center'
            },
            subtextStyle: {
                fontSize: 14,
                color: ['#ff9d19'],
            },
            x: 'center',
            y: 'center',
        },
        grid: {
            top: 0,
        },
        legend: {
            orient: 'vertical',
            top: 'middle',
            right: '2%',
            textStyle: {
                color: '#f2f2f2',
                fontSize: 14,
            },
            icon: 'roundRect',
            data: data,
        },
        tooltip: {
            //提示框组件
            trigger: 'item', //item数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。
            axisPointer: {
                // 坐标轴指示器，坐标轴触发有效
                type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
            },
            formatter: '{a} <br/>{b} : {c}亩 <br/>百分比 : {d}%', //{a}（系列名称），{b}（数据项名称），{c}（数值）, {d}（百分比）
        },
        series: [
            // 主要展示层的
            {
                radius: ['50%', '71%'],
                center: ['50%', '50%'],
                type: 'pie',
                label: {
                    normal: {
                        show: false,
                    },
                },
                labelLine: {
                    normal: {
                        show: false,
                    },
                },
                name: '作物长势等级面积占比',
                data: data,
            },
            // 边框的设置
            {
                radius: ['50%', '54%'],
                center: ['50%', '50%'],
                type: 'pie',
                label: {
                    normal: {
                        show: false,
                    },
                    emphasis: {
                        show: false,
                    },
                },
                labelLine: {
                    normal: {
                        show: false,
                    },
                    emphasis: {
                        show: false,
                    },
                },
                animation: false,
                tooltip: {
                    show: false,
                },
                data: [
                    {
                        value: 1,
                        itemStyle: {
                            color: 'rgba(250,250,250,0.3)',
                        },
                    },
                ],
            },
            {
                name: '外边框',
                type: 'pie',
                clockWise: false, //顺时加载
                hoverAnimation: false, //鼠标移入变大
                center: ['50%', '50%'],
                radius: ['85%', '85%'],
                tooltip: { show: false },
                label: {
                    normal: {
                        show: false,
                    },
                },
                data: [
                    {
                        value: 9,
                        name: '',
                        itemStyle: {
                            normal: {
                                borderWidth: 2,
                                borderColor: '#0b5263',
                            },
                        },
                    },
                ],
            },
        ],
    };

    useEcharts(typesofDivIntance, option);
}

function farmland() {
    const farmlandDivIntance = echarts.init(farmlandDiv.value);
    let option = {
        title: {
            text: '',
            subtext: '',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
            },
        },
        // legend: {
        //     icon: 'circle',
        //     left: 'center',
        //     top: '5',
        //     show: true,
        // },

        grid: {
            top: '15%',
            left: '5%',
            right: '5%',
            bottom: '10%',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            data: highStandard,
            axisLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.7)',
                    width: 1,
                    type: 'solid',
                },
                axisLabel: {
                    color: 'rgba(255, 255, 255, 0.7)',
                    fontWeight: 400,
                    fontFamily: 'SourceHanSansCN-Regular, SourceHanSansCN',
                    fontSize: 14,
                },
            },
        },
        yAxis: {
            name: '面积(亩)',
            nameTextStyle: {
                color: 'rgba(255, 255, 255, 0.8)',
                fontSize: 14,
            },
            type: 'value',
            axisLabel: {
                color: 'rgba(255, 255, 255, 0.7)',
            },
            splitLine: {
                lineStyle: {
                    type: 'solid',
                    color: 'rgba(255, 255, 255, 0.3)',
                },
            },
            minInterval: 1,
            axisLine: {
                show: false,
            },
            axisTick: {
                show: false,
            },
        },
        series: [
            {
                name: '好',
                type: 'bar',
                barWidth: 14,
                stack: '数量',
                data: highStandarditem.good,
                itemStyle: {
                    normal: {
                        borderWidth: 1,
                        borderColor: 'rgba(50, 148, 1, 1)',
                        //颜色渐变
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: 'rgba(50, 148, 1, 1)',
                            },
                            {
                                offset: 1,
                                color: 'rgba(50, 148, 1, 1)',
                            },
                        ]),
                    },
                },
            },
            {
                name: '较好',
                type: 'bar',
                barWidth: 14,
                stack: '数量',
                data: highStandarditem.better,
                itemStyle: {
                    normal: {
                        borderWidth: 1,
                        borderColor: 'rgba(154, 208, 0, 1)',
                        //颜色渐变
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: 'rgba(154, 208, 0, 1)',
                            },
                            {
                                offset: 1,
                                color: 'rgba(154, 208, 0, 1)',
                            },
                        ]),
                    },
                },
            },
            {
                name: '适中',
                type: 'bar',
                barWidth: 14,
                stack: '数量',
                data: highStandarditem.moderate,
                itemStyle: {
                    normal: {
                        borderWidth: 1,
                        borderColor: 'rgba(234, 219, 0, 1)',
                        //颜色渐变
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: 'rgba(234, 219, 0, 1)',
                            },
                            {
                                offset: 1,
                                color: 'rgba(234, 219, 0, 1)',
                            },
                        ]),
                    },
                },
            },
            {
                name: '较差',
                type: 'bar',
                barWidth: 14,
                stack: '数量',
                data: highStandarditem.poor,
                itemStyle: {
                    normal: {
                        borderWidth: 1,
                        borderColor: 'rgba(239, 152, 0, 1)',
                        //颜色渐变
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: 'rgba(239, 152, 0, 1)',
                            },
                            {
                                offset: 1,
                                color: 'rgba(239, 152, 0, 1)',
                            },
                        ]),
                    },
                },
            },
            {
                name: '差',
                type: 'bar',
                barWidth: 14,
                stack: '数量',
                data: highStandarditem.difference,
                itemStyle: {
                    normal: {
                        borderWidth: 1,
                        borderColor: 'rgba(247, 85, 0, 1)',
                        //颜色渐变
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: 'rgba(247, 85, 0, 1)',
                            },
                            {
                                offset: 1,
                                color: 'rgba(247, 85, 0, 1)',
                            },
                        ]),
                    },
                },
            },
        ],
    };

    // farmlandDivIntance.on('click', function (params) {
    //     console.log(params.name);
    // });
    // farmlandDivIntance.on('click', param => ChartClick(param));
    option && farmlandDivIntance.setOption(option, { notMerge: true, grid: { bottom: 20 } });
    useEcharts(farmlandDivIntance, option);
}

// 添加wms
function addWms(layers, customName) {
    let map = new Cesium.WebMapServiceImageryProvider({
        url: serverAPI.geoserverUrl + `/shuzisannong/wms?`,
        layers: layers, //图层名
        parameters: {
            service: 'WMS',
            format: 'image/png',
            transparent: true, //是否透明
            // CQL_FILTER: `crop in (${name})`,
        },
    });
    map.customName = customName; //自己定义各种属性
    let dd = viewer.imageryLayers.addImageryProvider(map); //添加图层
    if (customName.indexOf('gbznt') > -1) {
        // viewer.imageryLayers.lower(dd);//将图层下移一层
        viewer.imageryLayers.lowerToBottom(dd); //将图层移到最底层
        viewer.imageryLayers.raise(dd); //将图层上移一层
    }
}
//返回
function back() {
    removeWms(['gbznt'], true);
    viewer.camera.flyTo({
        destination: Cesium.Rectangle.fromDegrees(119.5091, 35.5671, 120.3285, 36.1455),
        duration: 2,
    });
    flag.value = false;
}
// 图表点击事件
function ChartClick(item) {
    console.log('item:', item);
    // 移除作物
    removeWms(['huangdaoqu_town'], true);
    removeWms(['tl'], true);
    let layername = 'shuzisannong:farmland';

    // 判断是否存在避免重复添加
    let cz = false;
    const layers = viewer.imageryLayers._layers;
    for (let f = layers.length - 1; f >= 0; f--) {
        if (
            layers[f] &&
            layers[f]._imageryProvider.customName &&
            layers[f]._imageryProvider.customName === layername + 'gbznt'
        ) {
            cz = true;
        }
    }
    if (!cz) {
        // 添加高标准农田服务
        addWms(layername, layername + 'gbznt');
    }
    // 定位到地块
    let features = formLandRef.value;
    features.forEach(it => {
        console.log('it.properties.name:', it.properties.name);
        console.log('item.name:', item.name);
        if (it.properties.name === item.name) {
            console.log('dingwei');
            viewer.camera.flyTo({
                destination: Cesium.Rectangle.fromDegrees(
                    it.bbox[0],
                    it.bbox[1],
                    it.bbox[2],
                    it.bbox[3]
                ),
                duration: 2,
            });
        }
    });
    flag.value = true;

    townZuowu.value = {
        label: [
            { crop: '小麦', Shape_Area: '53000' },
            { crop: '地瓜', Shape_Area: '50000' },
        ],
    };
    console.log(townZuowu.label);
    showOverlayChart({ x: 642, y: 312 });
}
function ASdivision() {
    const ASdivisionDivIntance = echarts.init(ASdivisionDiv.value);
    console.log(dd);
    console.log(data);
    var option = {
        // 设置图表的位置
        grid: {
            bottom: '8%',
            left: '10%',
            right: '6%',
            top: '12%',
            containLabel: true,
        },
        // legend: {
        //     // data: ["已完成", "进行中"],
        //     top: '5%',
        //     left: '10%',
        //     icon: 'rect',
        //     textStyle: {
        //         color: '#fff',
        //     },
        // },
        tooltip: {
            formatter: function (params) {
                // 自定义悬浮文字的格式，params.value 为当前柱状图的数值
                return (
                    params.seriesName +
                    '<span style="font-size: 14px; color: #f00;">' +
                    params.value.toFixed(2) +
                    '</span>' +
                    '亩'
                );
            },
        },
        dataZoom: [
            {
                type: 'slider',
                show: false,
                zoomLock: true, //禁止拉伸
                width: 8,
                yAxisIndex: [0],
                bottom: 30,
                top: 20,
                right: 10,
                startValue: 0,
                endValue: 4,
                handleIcon:
                    'M-292,322.2c-3.2,0-6.4-0.6-9.3-1.9c-2.9-1.2-5.4-2.9-7.6-5.1s-3.9-4.8-5.1-7.6c-1.3-3-1.9-6.1-1.9-9.3c0-3.2,0.6-6.4,1.9-9.3c1.2-2.9,2.9-5.4,5.1-7.6s4.8-3.9,7.6-5.1c3-1.3,6.1-1.9,9.3-1.9c3.2,0,6.4,0.6,9.3,1.9c2.9,1.2,5.4,2.9,7.6,5.1s3.9,4.8,5.1,7.6c1.3,3,1.9,6.1,1.9,9.3c0,3.2-0.6,6.4-1.9,9.3c-1.2,2.9-2.9,5.4-5.1,7.6s-4.8,3.9-7.6,5.1C-285.6,321.5-288.8,322.2-292,322.2z',
                handleSize: '100%',
                handleStyle: {
                    color: '#DBDBDB',
                    height: '100%',
                },
                backgroundColor: 'transparent',
                fillerColor: '#DBDBDB',
                textStyle: {
                    color: 'transparent',
                },
                dataBackground: {
                    lineStyle: {
                        color: 'transparent',
                    },
                    areaStyle: {
                        color: 'transparent',
                    },
                },
                borderColor: 'transparent',
            },
            {
                type: 'inside',
                id: 'insideY',
                yAxisIndex: 0,
                start: 0,
                end: 50,
                zoomOnMouseWheel: false,
                moveOnMouseMove: true,
                moveOnMouseWheel: true,
            },
        ],
        // X轴
        xAxis: {
            type: 'value', // 坐标轴类型,   'value' 数值轴，适用于连续数据
            // 坐标轴刻度
            axisTick: {
                show: false, // 是否显示坐标轴刻度 默认显示
            },
            // 坐标轴轴线
            axisLine: {
                // 是否显示坐标轴轴线 默认显示
                show: false, // 是否显示坐标轴轴线 默认显示
            },
            // 坐标轴在图表区域中的分隔线
            splitLine: {
                show: false, // 是否显示分隔线。默认数值轴显示
            },
            // 坐标轴刻度标签
            axisLabel: {
                show: false, // 是否显示刻度标签 默认显示
            },
        },
        // Y轴
        yAxis: [
            // 左侧Y轴
            {
                // 坐标轴类型,  'category' 类目轴，适用于离散的类目数据
                // 为该类型时必须通过 data 设置类目数据
                type: 'category',
                // 坐标轴刻度
                axisTick: {
                    show: false, // 是否显示坐标轴刻度 默认显示
                },
                // 坐标轴轴线
                axisLine: {
                    // 是否显示坐标轴轴线 默认显示
                    show: false, // 是否显示坐标轴轴线 默认显示
                    lineStyle: {
                        // 坐标轴线线的颜色
                        color: '#cdd3ee',
                    },
                },
                // 坐标轴在图表区域中的分隔线
                splitLine: {
                    show: false, // 是否显示分隔线。默认数值轴显示
                },
                // 坐标轴刻度标签
                axisLabel: {
                    show: true, // 是否显示刻度标签 默认显示
                    fontSize: 12, // 文字的字体大小
                    color: 'rgba(255, 255, 255, 1)', // 刻度标签文字的颜色
                    // 使用字符串模板，模板变量为刻度默认标签 {value}
                    formatter: '{value}',
                },
                // 类目数据，在类目轴（type: 'category'）中有效
                data: data.title,
                inverse: true,
            },
        ],
        // 系列列表
        series: [
            {
                type: 'bar', // 系列类型
                name: '好', // 系列名称, 用于tooltip的显示, legend 的图例筛选
                // 数据堆叠，同个类目轴上系列配置相同的stack值后，后一个系列的值会在前一个系列的值上相加
                stack: '总量',
                barMaxWidth: 30, // 柱条的最大宽度，不设时自适应
                // 图形上的文本标签
                label: {
                    show: false,
                    position: '好',
                    textStyle: {
                        fontSize: 12,
                        fontWeight: 'bolder',
                        color: 'rgba(255,255,255,1)',
                    },
                },
                // 图形样式
                itemStyle: {
                    barBorderRadius: [0, 0, 0, 0],
                    barBorderRadius: [0, 0, 0, 0], //
                    // borderWidth: 1, // 设置边框宽度
                    // borderColor: 'rgba(4, 247, 227, 0.8)', // 设置边框颜色
                    color: {
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(50, 148, 1, 1)', // 0% 处的颜色
                            },
                            {
                                offset: 1,
                                color: 'rgba(50, 148, 1, 1)', // 100% 处的颜色
                            },
                        ],
                    },
                },
                data: dd.value.good, // 系列中的数据内容数组
            },
            {
                type: 'bar', // 系列类型
                name: '较好', // 系列名称, 用于tooltip的显示, legend 的图例筛选
                // 数据堆叠，同个类目轴上系列配置相同的stack值后，后一个系列的值会在前一个系列的值上相加
                stack: '总量',
                barMaxWidth: 30, // 柱条的最大宽度，不设时自适应
                // 图形上的文本标签
                label: {
                    show: false,
                    position: 'inside',
                    formatter: '较好',
                    textStyle: {
                        fontSize: 12,
                        fontWeight: 'bolder',
                        color: 'rgba(255,255,255,1)',
                    },
                },
                // 图形样式
                itemStyle: {
                    barBorderRadius: [0, 0, 0, 0], //
                    // borderWidth: 1, // 设置边框宽度
                    // borderColor: 'rgba(143, 186, 243, 0.8)', // 设置边框颜色
                    color: {
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(154, 208, 0, 1)', // 0% 处的颜色
                            },
                            {
                                offset: 1,
                                color: 'rgba(154, 208, 0, 1)', // 100% 处的颜色
                            },
                        ],
                    },
                },
                data: dd.value.better, // 系列中的数据内容数组
            },
            {
                type: 'bar', // 系列类型
                name: '适中', // 系列名称, 用于tooltip的显示, legend 的图例筛选
                // 数据堆叠，同个类目轴上系列配置相同的stack值后，后一个系列的值会在前一个系列的值上相加
                stack: '总量',
                barMaxWidth: 30, // 柱条的最大宽度，不设时自适应
                // 图形上的文本标签
                label: {
                    show: false,
                    position: 'inside',
                    formatter: '适中',
                    textStyle: {
                        fontSize: 12,
                        fontWeight: 'bolder',
                        color: 'rgba(255,255,255,1)',
                    },
                },
                // 图形样式
                itemStyle: {
                    barBorderRadius: [0, 0, 0, 0],
                    barBorderRadius: [0, 0, 0, 0], //
                    // borderWidth: 1, // 设置边框宽度
                    // borderColor: 'rgba(4, 247, 227, 0.9)', // 设置边框颜色
                    color: {
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(234, 219, 0, 1)', // 0% 处的颜色
                            },
                            {
                                offset: 1,
                                color: 'rgba(234, 219, 0, 1)', // 100% 处的颜色
                            },
                        ],
                    },
                },
                data: dd.value.moderate, // 系列中的数据内容数组
            },
            {
                type: 'bar', // 系列类型
                name: '较差', // 系列名称, 用于tooltip的显示, legend 的图例筛选
                // 数据堆叠，同个类目轴上系列配置相同的stack值后，后一个系列的值会在前一个系列的值上相加
                stack: '总量',
                barMaxWidth: 30, // 柱条的最大宽度，不设时自适应
                // 图形上的文本标签
                label: {
                    show: false,
                    position: 'inside',
                    formatter: '较差',
                    textStyle: {
                        fontSize: 12,
                        fontWeight: 'bolder',
                        color: 'rgba(255,255,255,1)',
                    },
                },
                // 图形样式
                itemStyle: {
                    barBorderRadius: [0, 0, 0, 0],
                    barBorderRadius: [0, 0, 0, 0], //
                    // borderWidth: 1, // 设置边框宽度
                    // borderColor: 'rgba(33, 187, 251, 0.8)', // 设置边框颜色
                    color: {
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(239, 152, 0, 1)', // 0% 处的颜色
                            },
                            {
                                offset: 1,
                                color: 'rgba(239, 152, 0, 1)', // 100% 处的颜色
                            },
                        ],
                    },
                },
                data: dd.value.difference, // 系列中的数据内容数组
            },
            {
                type: 'bar', // 系列类型
                name: '差', // 系列名称, 用于tooltip的显示, legend 的图例筛选
                // 数据堆叠，同个类目轴上系列配置相同的stack值后，后一个系列的值会在前一个系列的值上相加
                stack: '总量',
                barMaxWidth: 30, // 柱条的最大宽度，不设时自适应
                // 图形上的文本标签
                label: {
                    show: false,
                    position: 'inside',
                    formatter: '差',
                    textStyle: {
                        fontSize: 12,
                        fontWeight: 'bolder',
                        color: 'rgba(255,255,255,1)',
                    },
                },
                // 图形样式
                itemStyle: {
                    barBorderRadius: [0, 0, 0, 0],
                    barBorderRadius: [0, 0, 0, 0], //
                    // borderWidth: 1, // 设置边框宽度
                    // borderColor: 'rgba(14, 223, 255, 0.8)', // 设置边框颜色
                    color: {
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(247, 85, 0, 1)', // 0% 处的颜色
                            },
                            {
                                offset: 1,
                                color: 'rgba(247, 85, 0, 1)', // 100% 处的颜色
                            },
                        ],
                    },
                },
                data: dd.value.poor, // 系列中的数据内容数组
            },
        ],
    };
    // option && ASdivisionDivIntance.setOption(option, true);
    useEcharts(ASdivisionDivIntance, option);
}
function chartModes() {
    const ASdivisionDivIntance = echarts.init(chartModeDiv.value);
    let arr = [];
    let 好 = [];
    let 较好 = [];
    let 适中 = [];
    let 较差 = [];
    let 差 = [];
    insectarr.value.forEach(item => {
        arr.push(item.subName);
        item.good !== null ? 好.push(item.good) : 好.push(0);
        item.better !== null ? 较好.push(item.better) : 较好.push(0);
        item.moderate !== null ? 适中.push(item.moderate) : 适中.push(0);
        item.difference !== null ? 较差.push(item.difference) : 较差.push(0);
        item.poor !== null ? 差.push(item.poor) : 差.push(0);
    });
    let ends = (10 / arr.length) * 100;
    let option = {
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                let tipStr = params[0].axisValueLabel + '</br>';
                let totalNum = 0;
                for (let i = 0; i < params.length; i++) {
                    totalNum += params[i].value;
                    if (params[i].seriesName !== '合计') {
                        tipStr += params[i].seriesName + '：' + params[i].value + '</br>';
                    }
                }
                for (let i = 0; i < params.length; i++) {
                    totalNum += Number(params[i].value);
                    if (params[i].seriesName === '合计') {
                        tipStr += '合计：' + totalNum;
                    }
                }
                return tipStr;
            },
            axisPointer: {
                // 坐标轴指示器，坐标轴触发有效
                type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
            },
        },
        legend: {
            top: 5,
            left: 10,
            icon: 'rect',
            itemWidth: 4, // 图例图表宽度
            itemHeight: 12, // 图例图标高度
            data: [],
        },
        dataZoom: [
            {
                type: 'slider',
                width: '40%',
                top: '90%',
                zoomLock: true, //禁止拉伸
                start: 0,
                end: ends,
                showDataShadow: false,
                showDetail: false,
                fillerColor: 'rgba(64, 158, 255)',
                borderRadius: '50%',
                moveHandleSize: 0,
                moveHandleStyle: {},
                left: '30%',
                height: 12,
                handleSize: '80%',
                handleIcon: 'path://M512,512m-448,0a448,448,0,1,0,896,0a448,448,0,1,0,-896,0Z',
                handleStyle: {
                    borderWidth: 0,
                    color: 'rgba(64, 158, 255)',
                },
            },
            {
                type: 'inside',
            },
        ],
        grid: {
            left: '3%',
            right: '10%',
            bottom: '15%',
            top: '5%',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            name: '区域',
            axisLabel: {
                fontSize: 12,
                interval: 0,
                rotate: 0,
            },
            axisLine: {
                lineStyle: {
                    // color: '#cbeaf6', // x坐标轴线颜色
                },
            },
            data: arr,
        },
        yAxis: [
            {
                type: 'value',
                name: '面积（亩）',
                axisLabel: {
                    // color: '#cbeaf6', // 坐标轴label文字颜色
                },
                axisLine: {
                    lineStyle: {
                        // color: '#cbeaf6', // y坐标轴线颜色
                    },
                },
                splitLine: {
                    // 网格线
                    lineStyle: {
                        // type: 'dashed', // 设置网格线类型 dotted：虚线   solid:实线
                        // color: '#395367',
                    },
                    show: true, // 隐藏或显示
                },
            },
        ],
        series: [
            {
                name: '好',
                type: 'bar',
                barWidth: 13,
                stack: '分类',
                itemStyle: {
                    color: 'rgba(255, 141, 26, 1)',
                },
                data: 好,
            },
            {
                name: '较好',
                type: 'bar',
                barWidth: 13,
                stack: '分类',
                itemStyle: {
                    color: 'rgba(255, 255, 26, 1)',
                },
                data: 较好,
            },
            {
                name: '适中',
                type: 'bar',
                barWidth: 13,
                stack: '分类',
                itemStyle: {
                    color: 'rgba(255, 201, 148, 1)',
                },
                data: 适中,
            },
            {
                name: '较差',
                type: 'bar',
                barWidth: 13,
                stack: '分类',
                itemStyle: {
                    color: 'rgba(255, 84, 84, 1)',
                },
                data: 较差,
            },
            {
                name: '差',
                type: 'bar',
                barWidth: 13,
                stack: '分类',
                itemStyle: {
                    color: 'rgba(255, 140, 255, 1)',
                },
                data: 差,
            },
        ],
    };

    var series = option.series;
    var tooltip = option.tooltip;
    // 提示框自定义内容包括总合及文字
    function formatFun(params) {
        // console.log('params====>', params)
        let tipStr = params[0].axisValueLabel + '</br>'; // 初始化提示框文字默认当前轴名称并换行
        let totalNum = 0; // 用于存储当前列总数
        // params为当前柱状图数组数量 遍历求和并添加类目label：value
        for (let i = 0; i < params.length; i++) {
            if (params[i].seriesName !== '合计') {
                const dotHtml = `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params[i].color}"></span>`;
                totalNum += params[i].value;
                tipStr += dotHtml + params[i].seriesName + '：' + params[i].value + '</br>';
            }
        }
        // 添加最后的合计行 数据为每列总合
        for (let i = 0; i < params.length; i++) {
            if (params[i].seriesName === '合计') {
                tipStr += '合计：' + totalNum;
            }
        }
        return tipStr;
    }
    tooltip.formatter = formatFun;
    // 指定函数计算总合
    function fun(params) {
        var dataSum = 0;
        for (var i = 0; i < series.length; i++) {
            dataSum += series[i].data[params.dataIndex];
        }
        return dataSum;
    }
    // 加载页面时候替换最后一个series的formatter
    // series[series.length - 1].label.normal.formatter = fun;
    useEcharts(ASdivisionDivIntance, option);
}

/*--------------------------------------------------------------------------------------------*/
function getAreaFenlei() {
    let fl = fenleiRef.value;
    console.log('fl:', fl);
    axios({
        url:
            serverAPI.geoserverUrl +
            '/shuzisannong/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=shuzisannong%3Ahuangdaoqu_town&maxFeatures=50&outputFormat=application%2Fjson',
    })
        .then(res => {
            console.log('res1111:', res);
            let data = res.data.features;
            data.forEach((item, index) => {
                const rectangle = Cesium.Rectangle.fromDegrees(
                    item.bbox[0],
                    item.bbox[1],
                    item.bbox[2],
                    item.bbox[3]
                );
                const center = Cesium.Rectangle.center(rectangle); //获取视角范围中心点(得到的结果为弧度Cartographic)
                let longitude = Cesium.Math.toDegrees(center.longitude); //将弧度转为度
                let latitude = Cesium.Math.toDegrees(center.latitude);

                if (item.properties.XZDM === '370211011') {
                    //灵山卫街道
                    longitude = 120.0863;
                    latitude = 35.941;
                } else if (item.properties.XZDM === '370211003') {
                    //薛家岛街道
                    longitude = 120.243682;
                    latitude = 35.97123201;
                }
                const townData = fl[item.properties.XZMC];
                let label = [];
                if (townData) {
                    label = townData.map((it, inex) => {
                        // let dd = `${it.properties.crop} ：${(it.properties.Shape_Area / 666.67).toFixed(2)} 亩`
                        // return dd
                        return it.properties;
                    });
                }
                // label = label.join(' ')
                // console.log('label:', index, label,fl[item.properties.XZMC],item.properties.XZMC)
            });
        })
        .catch(err => {});
}
let fenleiRef = ref({});
function mbHandle() {
    axios({
        url:
            serverAPI.geoserverUrl +
            '/shuzisannong/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=shuzisannong%3Afenlei&maxFeatures=137&outputFormat=application%2Fjson',
    })
        .then(res => {
            let features = res.data.features;
            let town = {};
            // 按镇分类
            features.forEach(item => {
                let key = item.properties.town;
                if (town[key]) {
                    town[key].push(item);
                } else {
                    town[key] = [item];
                }
            });
            fenleiRef.value = town;
            getAreaFenlei();
        })
        .catch(err => {});
}

// 地图移动时弹窗跟随
function infoWindowPostRender() {
    // let viewer = viewers.value;
    if (clickInfoMap.value.lon && clickInfoMap.value.lat) {
        //经纬度转为世界坐标
        const gisPosition = Cesium.Cartesian3.fromDegrees(
            Number(clickInfoMap.value.lon),
            Number(clickInfoMap.value.lat),
            0
        ); //转化为屏幕坐标
        var windowPosition = Cesium.SceneTransforms.wgs84ToWindowCoordinates(
            viewer.scene,
            gisPosition
        );

        if (Cesium.defined(windowPosition)) {
            const pop = document.getElementById('popup');
            if (pop) {
                pop.style.top = windowPosition.y - 10 + 'px';
                pop.style.left = windowPosition.x + 10 + 'px';
            }
        }
    }
}

// 隐藏弹窗
function hiddenOverlayChart() {
    const pop = document.getElementById('popup');
    if (pop) {
        pop.style.display = 'none'; // 清除监听事件
    }
    viewer.scene.postRender.removeEventListener(infoWindowPostRender);
}
//显示弹窗
function showOverlayChart(position) {
    const pop = document.getElementById('popup');
    if (pop) {
        pop.style.display = 'block';
        pop.style.position = 'absolute';
        pop.style.top = position.y - 10 + 'px';
        pop.style.left = position.x + 10 + 'px';
        pop.style.zIndex = 99;
    }
}
</script>

<style lang="scss" scoped>
$height: calc(100vh - 100px);
.fatherDiv,
.tabulation,
.centerBox {
    width: 100%;
    height: 100%;
    .imgrotate {
        transform: rotate(180deg);
    }
    .title {
        width: 100%;
        height: 45px;
        background: url('@/assets/images/title.png');
        background-repeat: no-repeat;
        background-size: 110% 100%;
        color: #fff;
        font-size: 18px;
        font-weight: 700;
        line-height: 45px;
        padding-left: 46px;
        display: flex;
        cursor: pointer;
        align-items: center;
        justify-content: space-between;

        span {
            width: 80%;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            background: linear-gradient(
                180deg,
                rgba(255, 255, 255, 1) 33.33%,
                rgba(41, 255, 219, 1) 100%
            );
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        p {
            width: 79px;
            height: 25px;
            border-radius: 20px;
            font-size: 14px;
            background: linear-gradient(
                180deg,
                rgba(16, 111, 111, 1) 0%,
                rgba(47, 214, 214, 1) 100%
            );
            border: 1.5px solid rgba(23, 194, 180, 1);
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
}
.tabulation {
    display: none;
    padding: 20px;
    .tableBox {
        padding: 0 10px;
        .tableBorder {
            border-radius: 8px;
            margin-bottom: 10px;
            .el-table--fit {
                border-radius: 8px;
                border: 2px solid rgba(100, 195, 164, 0.8);
                box-shadow: 0px 3px 9px 0px rgba(100, 195, 164, 0.25),
                    0px 1px 2px 0px rgba(100, 195, 164, 0.8);
            }
        }
        :deep(
                .el-table .el-table__header-wrapper th,
                .el-table .el-table__fixed-header-wrapper th
            ) {
            color: rgba(0, 0, 0, 1);
        }
        height: 84%;
        :deep(.el-table__inner-wrapper) {
            height: 96% !important;
        }
        .example-pagination-block {
            display: flex;
            align-items: center;
            justify-content: flex-end;
        }
        :deep(.tabth) {
            background-color: rgba(247, 247, 247, 1);
        }
    }
    .chartMode {
        width: 100%;
        height: 85%;
        .chartModeDiv {
            width: 100%;
            height: 100%;
            padding: 10px;
        }
    }
    .searchDiv {
        display: flex;
        .dow {
            float: right;
            margin-right: 10px;
        }
        :deep(.el-input__wrapper) {
            width: 100px;
        }
        .modeDiv {
            width: 234px;
            height: 26px;
            opacity: 1;
            border-radius: 8px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            text-align: center;
            font-size: 14px;
            // font-weight: 400;
            border: 1px solid #ccc;
            cursor: pointer;
            div {
                flex: 1;
                height: 100%;
                border-radius: 8px;
                line-height: 26px;
            }
            .Selected {
                background: rgba(100, 195, 164, 1);
                border-radius: 8px 0px 0px 8px;
                color: rgba(255, 255, 255, 1);
            }
            .Selecteds {
                background: rgba(100, 195, 164, 1);
                border-radius: 0px 8px 8px 0px;
                color: rgba(255, 255, 255, 1);
            }
        }
    }
}

.leftWra {
    position: absolute;
    top: 10px;
    left: 20px;
    height: $height;
    width: 23%;
    background: rgba(2, 31, 26, 0.85);
    box-shadow: inset 0px 0px 15px 6px rgba(41, 255, 255, 0.5);
    transition: transform 1s;
    .leftFoldDiv {
        width: 30px;
        height: 30px;
        position: absolute;
        right: -14%;
        top: 50%;
        transform: translate(-50%, -50%);
        font-size: 30px;
        color: #ccc;
    }
    .leftTop {
        width: 100%;
        display: flex;
        flex-direction: column;
        height: 42%;
        .areaDiv {
            width: 100%;
            height: 327px;
            opacity: 1;
            display: flex;
            padding: 1px;
            justify-content: center;
        }

        .ProgressBar {
            width: 100%;
            height: 9px;
            opacity: 1;
        }
    }

    .leftbottom {
        width: 100%;
        height: 57%;
        opacity: 1;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: center;
        padding-top: 13px;

        .typesofDiv {
            width: 100%;
            height: 50%;
            opacity: 1;
            display: flex;
            padding: 1px;
            justify-content: center;
        }

        .tableDiv {
            // background: rgba(255, 255, 255, 0.05);
            display: flex;
            justify-content: center;
            width: 85%;
            flex-direction: column;
            margin-bottom: 10px;
            color: rgba(255, 255, 255, 1);
            height: 50%;
            padding-bottom: 30px;
            :deep(.el-table tr) {
                background-color: transparent;
            }
            :deep(.el-table) {
                --el-table-border-color: none;
                color: rgba(255, 255, 255, 1);
            }
            :deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
                background-color: revert;
            }

            .Crops {
                display: flex;
                width: 100%;
                margin-bottom: 10px;
                font-size: 14px;
                font-weight: 400;
                height: 31px;
                flex-direction: row;
                align-items: center;
                justify-content: space-around;
                opacity: 1;
                background: linear-gradient(
                    90deg,
                    rgba(21, 173, 148, 0.1) 0%,
                    rgba(21, 173, 148, 0) 100%
                );

                div {
                    display: flex;
                    align-items: center;
                }
            }

            .el-checkbox-group {
                display: flex;
                flex-direction: column;
            }

            :deep(.ones) {
                width: 100%;
                height: 171;
                display: flex;
                flex-direction: column;
                justify-content: flex-start;
                align-items: flex-start;
                --el-table-tr-bg-color: null;
                --el-table-border-color: null;
                font-size: 14px;
                font-weight: 400;
                letter-spacing: 0px;
                line-height: 0px;
                color: rgba(255, 255, 255, 1);
            }
        }
    }
}

.rightWra {
    position: absolute;
    top: 10px;
    right: 20px;
    width: 23%;
    height: $height;
    opacity: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: rgba(2, 31, 26, 0.85);
    box-shadow: inset 0px 0px 15px 6px rgba(41, 255, 255, 0.5);
    transition: transform 1s;
    .rightFoldDiv {
        width: 30px;
        height: 30px;
        position: absolute;
        left: -8%;
        top: 50%;
        transform: translate(0, -50%);
        font-size: 30px;
        color: #ccc;
    }
    .rightTop {
        width: 100%;
        height: 40%;
        opacity: 1;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: center;

        .farmlandDiv {
            width: 100%;
            height: 340px;
            opacity: 1;
            display: flex;
            justify-content: center;
        }

        .ProgressBar {
            width: 100%;
            height: 9px;
            opacity: 1;
        }
    }

    .rightbottom {
        width: 100%;
        height: 54%;
        opacity: 1;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: center;

        .el-select {
            width: 80%;
            font-size: 14px;
            color: #333;
            background: rgba(22, 94, 102, 1);
            border: 1px solid rgba(4, 153, 153, 1) !important;
            margin-top: 20px;

            :deep(.el-input__wrapper) {
                background-color: transparent;
                box-shadow: none;
            }

            :deep(.el-input__inner) {
                color: rgba(255, 255, 255, 0.7);
            }
        }

        .ASdivision {
            width: 100%;
            height: 368px;
            opacity: 1;
            display: flex;
            justify-content: center;
        }
    }
}

.legend {
    position: absolute;
    right: 25%;
    bottom: 7%;
    width: 129px;
    border: 1px solid rgba(4, 153, 153, 1);

    // height: 50px;
    :deep(.el-collapse-item__header) {
        background: rgba(2, 31, 26, 0.6);
        color: rgba(255, 255, 255, 1);
        text-align: center;
        padding: 0 30px;
        font-size: 14px;
    }

    --el-collapse-content-bg-color {
        background: rgba(2, 31, 26, 0.6);
    }

    :deep(.el-collapse-item__content) {
        background: rgba(2, 31, 26, 0.6);
        padding: 0 10px;
        padding-bottom: 10px;
    }

    --el-collapse-border-color: none;
    --el-collapse-content-bg-color: none;

    // opacity: 1;
    // border-radius: 4px;
    // background: rgba(2, 31, 26, 0.6);
    // display: flex;
    // flex-direction: column;
    // justify-content: flex-start;
    // align-items: center;
    // padding: 10px 10px 10px 10px;
    p {
        margin: 10px;
        font-size: 14px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 0px;
        color: rgba(255, 255, 255, 1);
        text-align: center;
    }

    .mt-4 {
        .el-checkbox {
            height: 30px;
            width: 100%;
            margin-bottom: 2px;
            padding-left: 10px;
            font-size: 14px;
            font-weight: 400;
            letter-spacing: 0px;
            line-height: 0px;
            color: rgba(255, 255, 255, 1);
            text-align: left;
        }
    }

    :deep(.el-checkbox__label) {
        color: rgba(255, 255, 255, 1);
    }
}

.bottom_center {
    position: absolute;
    // left: calc(400px + 20px + 8vw);
    left: -2%;
    right: 0;
    margin: auto;
    width: calc(100% - (400px * 2) - (10vw * 2));
    min-width: 380px;
    bottom: 5%;
    height: 75px;
    opacity: 1;
    border-radius: 5px;
    background: rgba(2, 31, 26, 0.6);
    border: 1px solid rgba(4, 153, 153, 1);
}

.tool {
    position: absolute;
    right: 30%;
    top: 8%;
    width: 30px;
    height: 280px;
    opacity: 1;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    display: none;
}

#popup {
    border-radius: 5px;
    background: rgba(2, 31, 26, 0.6);
    display: none;
    // justify-content: flex-start;
    // align-items: flex-end;
    padding: 30px 8px 20px 8px;

    & > div:nth-child(1) {
        font-weight: 400;
        letter-spacing: 0px;
        color: rgba(255, 255, 255, 1);
        display: flex;
        align-items: center;
        p {
            background: rgba(217, 231, 255, 0.2);
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 2px 10px 2px 10px;
            width: 140px;
        }
    }

    & > div:nth-child(2) {
        font-weight: 400;
        letter-spacing: 0px;
        color: rgba(255, 255, 255, 1);
        display: flex;
        align-items: center;
        p {
            background: rgba(217, 231, 255, 0.2);
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 2px 10px 2px 10px;
            width: 140px;
        }
    }
    & > div:nth-child(3) {
        font-weight: 400;
        letter-spacing: 0px;
        color: rgba(255, 255, 255, 1);
        display: flex;
        align-items: center;
        p {
            background: rgba(217, 231, 255, 0.2);
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 2px 10px 2px 10px;
            width: 140px;
        }
    }
    .cancel {
        position: absolute;
        right: 10px;
        top: 5px;
        color: rgba(255, 255, 255, 1);
        cursor: pointer;
    }
}
#pop {
    border-radius: 5px;
    background: rgba(2, 31, 26, 1);
    display: none;
    // justify-content: flex-start;
    // align-items: flex-end;
    padding: 30px 8px 20px 8px;

    .cancel {
        position: absolute;
        right: 10px;
        top: 5px;
        color: rgba(255, 255, 255, 1);
        cursor: pointer;
    }

    & > div {
        display: flex;
        margin-bottom: 10px;

        & > div:nth-child(1) {
            font-weight: 400;
            letter-spacing: 0px;
            color: rgba(255, 255, 255, 1);
            // margin-top: 20px;
            line-height: 24px;
            margin-right: 10px;
        }

        & > div:nth-child(2) {
            color: rgba(255, 255, 255, 1);
            width: 129px;
            height: 24px;
            opacity: 1;
            border-radius: 2px;
            background: rgba(217, 231, 255, 0.2);
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 2px 10px 2px 10px;
            // margin-top: 20px;
        }
    }
}
.back_button {
    position: absolute;
    right: 30%;
    top: 20px;
}

:deep(.el-select__popper.el-popper) {
}
</style>
<style lang="scss">
.select_city {
    background: rgba(2, 31, 26, 0.85);
    box-shadow: inset 0px 0px 15px 6px rgba(41, 255, 255, 0.5);

    .el-select-dropdown__item.hover {
        background: rgba(2, 31, 26, 0.95);
        box-shadow: inset 0px 0px 15px 6px rgba(41, 255, 255, 0.7);
    }

    .el-select-dropdown__item {
        color: #fff;
    }
}

.el-select__popper {
    border: none !important;
    background: transparent !important;
}

.el-popper__arrow::before {
    display: none;
}
.selectCity {
    background: #fff;
}
</style>
