<template>
    <div class="box" id="box">
        <div class="btna">
            <!--  -->
            <el-button type="primary" :icon="collapsechange ? 'el-icon-remove-outline' : 'el-icon-circle-plus-outline '"
                @click="collapsechange = !collapsechange">
                {{ collapsechange ? '收起' : ' 展开' }}
            </el-button>
        </div>

        <div class="box1" v-show="collapsechange">
            <div class="titlestyle">生产地市统计</div>
            <div id="leafletMap" class="leafletMap"></div>
        </div>
        <div class="box2" id="box2" v-show="collapsechange">
            <div class="titlestyle">{{ echartstitle }}类型统计</div>
            <div class="echarts" id="echarts"></div>
        </div>
    </div>
</template>

<script>
import cityJson from "@/utils/mapJson/liaoning-city.json";
import cityCenter from "@/utils/mapJson/cityCenter.json";
import province from "@/utils/mapJson/liaoning-province.json";


import * as echarts from "echarts";
import elementResizeDetectorMaker from 'element-resize-detector'

export default {
    name: 'MapCars',
    components: {},
    data() {
        return {
            collapsechange: true,
            mygeojson: null,
            cityData: {
                沈阳市: 0,
                大连市: 0,
                鞍山市: 0,
                抚顺市: 0,
                本溪市: 0,
                丹东市: 0,
                锦州市: 0,
                营口市: 0,
                阜新市: 0,
                辽阳市: 0,
                盘锦市: 0,
                铁岭市: 0,
                朝阳市: 0,
                葫芦岛市: 0,
                沈抚示范区: 0,
            },
            cartData: ["沈阳市",
                "大连市",
                "鞍山市",
                "抚顺市",
                "本溪市",
                "丹东市",
                "锦州市",
                "营口市",
                "阜新市",
                "辽阳市",
                "铁岭市",
                "朝阳市",
                "盘锦市",
                "葫芦岛市",],
            allInspector: 0,
            //字典
            dict: {},
            legendList: [
                { color: "#28599C", text: ">=600" },
                { color: "#3477B2", text: "400-599" },
                { color: "#4499CE", text: "200-399" },
                { color: "#59BBEC", text: "100-199" },
                { color: "#9BD3F5", text: "1-99" },
                { color: "#C5F0FF", text: "0" },
            ],
            globalMap: null,
            latitude: "40.904726971438656",
            longitude: "122.80196410332945",
            zoom: 8,
            maxZoom: 18,
            minZoom: 7,
            layerObj: {
                provinceLayer: null,
                cityLayer: null,
                textLayer1: null,
            },
            mylayer: null,
            myChart: null,
            mygeojson: null,
            mystort: null,
            mystortTow: null,
            chartData: ["其他"],
            chartDatatow: [10],
            clickShow: true,
        };
    },
    props: {
        leafletitle: {
            type: String,
            default: '档案'
        },
        echartstitle: {
            type: String,
            default: '档案'
        },
        mytype: {
            type: String,
            default: ''
        },
        Leixtypes: {
            type: String,
            default: ''
        },
        form: {
            type: Object,
            default: () => {
                return {
                    cplx: "",//产品类型
                    cplb: "",//产品类别}
                }
            }
        },
    },
    created() { },

    mounted() {
        // 记录是否有身份
        this.mystort = this.$store.getters.usersort
        this.mystortTow = this.$store.getters.usersort
        this.$nextTick(() => {
            this.myChart = echarts.init(document.getElementById("echarts"));
            this.isEcharts()
            this.initMap()
        });
        // 监听窗口大小变化事件
    },

    methods: {
        async isEcharts() {
            this.chartDatatow = []
            this.chartData = []
            if (this.mytype == "healtson") {
                return
            }
            if (this.echartstitle == "医疗器械") {
                let msg1 = await this.$api.apparatus.typecount({ area: this.mystortTow });
                if (msg1.code == 200) {
                    msg1.data.forEach(item => {
                        this.chartDatatow.push(item.count)
                        this.chartData.push(item.cplb)
                    })
                    this.clickShow = true
                }
            } else if (this.echartstitle == "药品") {
                let msg1 = await this.$api.apparatus.vRdgYpwhGxwztypecount({ area: this.mystortTow });
                if (msg1.code == 200) {
                    msg1.data.forEach(item => {
                        if (item.ypfl && item.ypfl != 'null') {
                            this.chartDatatow.push(item.count)
                            this.chartData.push(item.ypfl)
                        }

                    })
                    this.clickShow = true

                }
            } else if (this.echartstitle == "化妆品/注册备案品种" || this.echartstitle == "化妆品/委托生产品种") {
                let msg1 = await this.$api.apparatus.gccptypecount({ area: this.mystortTow });
                if (msg1.code == 200) {
                    msg1.data.forEach(item => {
                        if (item.type && item.type != 'null') {
                            this.chartDatatow.push(item.count)
                            this.chartData.push(item.type)
                        }

                    })
                    this.clickShow = true

                }
            } else if (this.echartstitle == "传统中药") {

                let msg1 = await this.$api.apparatus.deasCorpTcmpFilingtypecount({ area: this.mystortTow });
                if (msg1.code == 200 && msg1.data.length != 0) {
                    msg1.data.forEach(item => {
                        if (item.jx && item.jx != 'null') {
                            this.chartDatatow.push(item.count)
                            this.chartData.push(item.jx)
                        }
                        this.clickShow = true

                    })
                } else {
                    this.chartDatatow = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    ]
                    this.chartData = ["散剂",
                        "片剂",
                        "颗粒剂",
                        "胶囊剂",
                        "溶液剂",
                        "乳剂",
                        "混悬剂",
                        "注射剂",
                        "喷雾剂",
                        "气雾剂",
                        "原料药"]
                    this.clickShow = true

                }
            }


            // if (this.leafletitle == "药品") {
            //     let msg1 = await this.$api.apparatus.vRdgYpwhGxwztypecount({ area: this.mystortTow });
            //     if (msg1.code == 200) {
            //         console.log(msg1.data);
            //         msg1.data.forEach(item => {
            //             let obj = {
            //                 value: item.count,
            //                 name: item.ypfl,
            //             }
            //             this.chartDatatow.push(obj)
            //             this.chartData.push(item.ypfl)
            //         })
            //     }


            // }
            this.mycharts()
        },
        async isLefleat(data) {
            console.log(data);
            this.cityData = {
                沈阳市: 0,
                大连市: 0,
                鞍山市: 0,
                抚顺市: 0,
                本溪市: 0,
                丹东市: 0,
                锦州市: 0,
                营口市: 0,
                阜新市: 0,
                辽阳市: 0,
                盘锦市: 0,
                铁岭市: 0,
                朝阳市: 0,
                葫芦岛市: 0,
                沈抚示范区: 0,
            }


            // "沈抚示范区",
            let _this = this
            var combinedData = [];
            if (this.echartstitle == "医疗器械") {
                jiekou("ylqxJnyelcpareacount")
            } else if (this.echartstitle == "药品") {
                jiekou("vRdgYpwhGxwztareacount")
            } else if (this.echartstitle == "传统中药") {
                jiekou("deasCorpTcmpFilingChangeHis")
            } else if (this.echartstitle == "化妆品/注册备案品种") {
                let msg2 = await this.$api.apparatus["gccpareacount"]({ area: data })
                if (msg2.code == 200) {
                    msg2.data.forEach(item => {
                        this.cityData[item.area] = item.count
                    })
                    // 按顺序给数据
                    this.cartData.forEach((item) => {
                        var foundItem = msg2.data.find(data => data.area == item);
                        if (foundItem) {
                            this.chartDatatow.push(foundItem.count)
                            this.chartData.push(foundItem.area)
                        } else {
                            this.chartDatatow.push(0)
                            this.chartData.push(item)
                        }
                    });
                    this.mycharts()
                }
                console.log(7987988, this.chartData);
                this.initPoitCenter(this.cityData);
            }
            async function jiekou(data) {
                let msg2 = await _this.$api.apparatus[data](_this.form)
                if (msg2.code == 200) {
                    msg2.data.forEach(item => {
                        _this.cityData[item.area] = item.count || item.countOne

                    })
                    if (_this.mytype == "healtson") {
                        _this.cartData.forEach((item) => {
                            var foundItem = msg2.data.find(data => data.area == item);
                            if (foundItem) {
                                _this.chartDatatow.push(foundItem.count || foundItem.countOne)
                                _this.chartData.push(foundItem.area)
                            } else {
                                _this.chartDatatow.push(0)
                                _this.chartData.push(item)
                            }
                        });
                    }
                }
                _this.initPoitCenter(_this.cityData);
                if (_this.mytype == "healtson") {
                    _this.mycharts()
                }

            }

        },
        mycharts() {
            let option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: function (params) {
                        if (params && params.length > 0) {
                            return params[0].name + ' : ' + params[0].value;
                        }
                        return '';
                    },
                },
                grid: {
                    left: '0%', // 增加左侧空间
                    right: '4%',
                    top: '6%',
                    bottom: '0%',

                    containLabel: true
                },
                xAxis: [{
                    type: 'category',
                    data: this.chartData,
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLabel: {
                        // 移除或减少旋转角度
                        interval: 0, // 设置为 0，每个刻度都显示
                        rotate: -50, // 将刻度文字旋转90度
                        formatter: function (value) {
                            return value.split('\n').join('\n');
                        },
                    },
                }],
                yAxis: [{
                    type: 'value',

                }],
                series: [{
                    name: 'Direct',
                    type: 'bar',
                    barWidth: '30%', // 调整柱子宽度为 20%
                    data: this.chartDatatow,
                    label: {
                        show: true,
                        position: 'top',
                    },
                }],
            };

            this.myChart.setOption(option, true);


        },
        initMap() {
            this.globalMap = L.map("leafletMap", {
                center: [this.latitude, this.longitude], // 地图中心[纬度，经度]
                // zoom: this.zoom,
                // maxZoom: this.maxZoom,
                // minZoom: this.minZoom,
                zoomControl: false, // 放大缩小按钮
                zoomSnap: 0,
                attributionControl: false, // 右下角leaflet图标
                scrollWheelZoom: false,
                dragging: false,
                doubleClickZoom: false,
                scrollWheelZoom: false,
                dragging: false,
            });
            // 省
            this.globalMap.createPane("provinceLayer");
            this.globalMap.getPane("provinceLayer").style.zIndex = 504;
            this.globalMap.getPane("provinceLayer").style.pointerEvents = "none";
            this.layerObj.provinceLayer = L.layerGroup().addTo(this.globalMap);
            //市
            this.globalMap.createPane("cityLayer");
            this.globalMap.getPane("cityLayer").style.zIndex = 505;
            this.globalMap.getPane("cityLayer").style.pointerEvents = "none";
            this.layerObj.cityLayer = L.layerGroup().addTo(this.globalMap);

            this.globalMap.createPane("textLayer1");
            this.globalMap.getPane("textLayer1").style.zIndex = 506;
            this.globalMap.getPane("textLayer1").style.pointerEvents = "none";
            this.layerObj.textLayer1 = L.layerGroup().addTo(this.globalMap);

            this.provinceLayer();
            this.initCityLayer(this.cityData);
            this.initPoitCenter(this.cityData);

            this.globalMap.on('click', () => {
                this.globalMap.fitBounds(this.mygeojson.getBounds());
            })
            this.isLefleat(this.Leixtypes)


        },
        //省级图层
        provinceLayer() {
            this.mygeojson = L.geoJSON(province, {
                style: function () {
                    return {
                        weight: 2,
                        color: "#36527D",
                        fillColor: "",
                        fillOpacity: 1,
                    };
                },
            }).addTo(this.layerObj.provinceLayer);
            this.globalMap.fitBounds(this.mygeojson.getBounds());


            let erd = elementResizeDetectorMaker();
            let that = this;
            erd.listenTo(document.getElementById("echarts"), function (element) {
                that.myChart.resize();
                that.globalMap.fitBounds(that.mygeojson.getBounds());

            })
        },
        showinitCityLayer() {
            this.initCityLayer(this.cityData)
            this.mystortTow = this.$store.getters.usersort
            this.isEcharts()
            // this.isLefleat()
        },
        // 市级图层
        initCityLayer(data) {
            let _this = this;
            let geojson = L.geoJSON(cityJson, {
                onEachFeature: function onEachFeature(feature, layer) {
                    //处理点击地图
                    layer.on({
                        click: function zoomToFeature(e) {
                            if (!_this.mystort && _this.clickShow && _this.mytype != "healtson") {
                                _this.mystortTow = feature.properties.name
                                _this.highlightFeature(e, geojson)
                                _this.clickShow = false
                            }

                        },
                    });
                },
                style: (geoJsonFeature) => {
                    let num = data[geoJsonFeature.properties.name];
                    let style = {
                        weight: 0.5,
                        color: "#fff",
                        fillColor: "#87CEEB",
                        fillOpacity: 1,
                    };
                    if (geoJsonFeature.properties.name == this.mystort) {
                        style.fillColor = "#FFFF00";
                    }
                    return style;
                },
            }).addTo(this.layerObj.cityLayer);

            // this.globalMap.fitBounds(geojson.getBounds());

            //   市中心点
        },

        initPoitCenter(data) {
            let ismyobj = {
                "沈阳市": "稽查一处",
                "大连市": "稽查二处",
                "鞍山市": "稽查三处",
                "抚顺市": "稽查四处",
                "本溪市": "稽查五处",
                "丹东市": "稽查六处",
                "锦州市": "稽查七处",
                "营口市": "稽查八处",
                "阜新市": "稽查九处",
                "辽阳市": "稽查十处",
                "铁岭市": "稽查十一处",
                "朝阳市": "稽查十二处",
                "盘锦市": "稽查十三处",
                "葫芦岛市": "稽查十四处"
            }

            // <div class="circle"></div>
            let geoJSON = L.geoJSON(cityCenter, {
                pointToLayer: (feature, latlng) => {
                    if (!this.mystort && feature.properties.fName != '沈抚示范区') {
                        return L.marker(latlng, {
                            icon: L.divIcon({
                                className: "city-marker",
                                html: `<div class="marker-data">
                        <div class="data-box">
                            ${data[feature.properties.fName]}
                        </div>
                        <div class="city-name">${ismyobj[feature.properties.fName]}</div>
                        <div class="city-name">（${feature.properties.fName}）</div>
                    </div>`,
                            }),
                        });
                    } else if (feature.properties.fName == this.mystort && feature.properties.fName != '沈抚示范区') {
                        return L.marker(latlng, {
                            icon: L.divIcon({
                                className: "city-marker",
                                html: `<div class="marker-data" >
                        <div class="data-box">
                            ${data[feature.properties.fName]}
                        </div>
                        <div class="city-name">${ismyobj[feature.properties.fName]}</div>
                        <div class="city-name">（${feature.properties.fName}）</div>
                    </div>`,
                            }),
                        });
                    } else if (feature.properties.fName != '沈抚示范区') {
                        return L.marker(latlng, {
                            icon: L.divIcon({
                                className: "city-marker",
                                html: `<div class="marker-data">
                        <div class="city-name">${feature.properties.fName}</div>
                    </div>`,
                            }),
                        });
                    }

                },
            }).addTo(this.layerObj.textLayer1);

            // this.globalMap.fitBounds(geoJSON.getBounds());
        },
        highlightFeature(e, geojson) {

            if (this.mylayer) {
                if (this.mylayer.feature.properties.name == e.target.feature.properties.name) {
                    this.mylayer.setStyle({
                        weight: 0.5,
                        color: "#fff",
                        fillColor: "#87CEEB",
                        fillOpacity: 1,
                    });

                    this.mylayer = null;
                    this.$emit('arealist', "")
                    this.mystortTow = null
                    this.isEcharts()
                    return
                } else {
                    geojson.resetStyle(this.mylayer);

                }
            }

            this.mylayer = e.target;
            this.mylayer.setStyle({
                weight: 0.3,
                color: "#000",
                dashArray: "",
                fillOpacity: 1,
                fillColor: "#FFFF00"
            });
            this.$emit('arealist', this.mylayer.feature.properties.name)
            this.isEcharts()
            this.mylayer.bringToFront();

        },
    },
    computed: {}
}
</script>

<style scoped lang='scss'>
.box {
    position: relative;
    padding: 15px;
    display: flex;

    .btna {
        position: absolute;
        right: 20px;
        top: -40px;
    }

    .echarts {
        width: 45vw;
        height: 60vh;
    }

    .box1 {
        width: 45vw;
        height: 60vh;

        .leafletMap {
            /* 水平居中 */
            background-color: #fff;
            min-width: 100%;
            min-height: 100%;
        }
    }

}

::v-deep .leaflet-map-pane {}

.titlestyle {
    padding: 0 0 0 10px;
    margin: 0 0 0 20px;
    border-left: 5px solid #1e80eb;
    color: #1e80eb;
    font-size: 18px;
    font-weight: 600;
}
</style>
