<template>
  <div class="innerContainer leftPane" v-drag>
    <h2 class="Pangetitle darg-div el-col">
      <span class="pange_text">{{ pageType == 0 ? "耕地总览" : "永久基本农田" }}
      </span>
      <div class="region">
        <el-select v-model="nowunit" placeholder="请选择" size="mini" @change="unitChange">
          <el-option v-for="item in unitList" :key="item.code" :label="item.name" :value="item.code">
          </el-option>
        </el-select>
      </div>
    </h2>
    <div class="xz_box">
      <div class="gdzl">
        <div class="el-col headerSelect">
          <el-select v-model="nowyear" placeholder="请选择" size="mini" @change="yearChange()">
            <el-option v-for="item in yearList" :key="item.year" :label="item.year" :value="item.year">
            </el-option>
          </el-select>
          <!-- clearable -->
          <el-cascader v-model="region" :show-all-levels="false" :options="store.state.region_tree"
            @change="xzqhChange()" placeholder="行政区" size="mini" :props="{
              checkStrictly: true,
              expandTrigger: 'hover',
              emitPath: false,
            }"></el-cascader>
          <el-select v-model="dlbm" placeholder="请选择" size="mini" @change="dlbmChange">
            <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.id">
            </el-option>
          </el-select>
          <!-- <div class="region">
      </div> -->
        </div>
        <div class="echars">
          <div class="echartTitle">
            <div class="block-title">
              {{ gtype }}总量
            </div>
          </div>
          <div class="content gdzlc">
            <div class="item" v-for="zl in zllist[gtype]" :key="zl.name">
              <div class="icon">
                <div class="iicon"></div>
              </div>
              <div class="text">
                <p>{{ zl.name }}</p>
                <span class="cvalue">
                  {{ (zldata[zl.prop || ((zl.p || '') + uprops[nowunit])] || 0).toFixed(2) }}
                  {{ zl.unit || unitList[nowunit].unit }}</span>
              </div>
            </div>
          </div>
          <div class="content scontent" v-show="dlbm == '01'">
            <div class="item" v-for="(sd, index) in fldata" :key="index">
              <div class="text">
                <p>{{ sd.dlmc }}</p>
                <span class="cvalue">
                  {{ (sd[uprops[nowunit]] || 0).toFixed(2) }}
                </span>
                <span class="unit">{{ unitList[nowunit].unit }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="echars">
          <div class="echartTitle">
            <div class="block-title">
              {{ gtype }}增减变化情况
            </div>
            <div class="titlesel" v-show="dlbm == '01'">
              对比年份
              <div class="selectTab">
                <el-select v-model="tab" placeholder="请选择" :popper-append-to-body="false" @change="GetBhqk()">
                  <el-option v-for="item in yearList" :key="item.year" :label="item.year" :value="item.year">
                  </el-option>
                </el-select>
              </div>
              <div class="usable" @click="contrast">更多</div>
            </div>
          </div>
          <div class="content scontent" v-show="dlbm == '01'">
            <div class="item item50" v-for="(bh, index) in bhlist" :key="index">
              <div class="text">
                <p>{{ bh.name }}</p>
                <span class="cvalue" :class="bhdata.mjbh > 0 ? 'posNum' : 'negNum'">
                  {{ (bhdata[bh.prop || uprops[nowunit]] || 0).toFixed(2) }}
                </span>
                <span class="unit">{{ bh.unit || unitList[nowunit].unit }}</span>
              </div>
            </div>
          </div>
          <div class="pietitle" v-show="dlbm == '01'">历年变化情况</div>
          <bar class="pie_echart" ref="echartRef0"></bar>
        </div>
        <div class="echars gqgd">
          <Statistics :title="`各区${gtype}分布`" :cityList="cityList" :prop="uprops[nowunit]" :max="citymax"
            :unit="unitList[nowunit].unit" :height="dlbm == '01' ? 180 : 260" :text="`占全市${gtype}`" textunit="%">
          </Statistics>
          <!-- <sidebar v-if="!sidebar.hide" class="sidebar-container" /> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import bar from "@/components/echartsTemplate/bar.vue";
import Statistics from "../components/statistics.vue";
import { QueryOne, QueryList } from "@/api/cockpitNew";
import {
  GetGdDate,
  GetGdZl,
  GetGdFl,
  GetGdBhqk,
  GetGdLnbhqk,
  GetGdQxfl,
  GetYjjbntDate,
  GetYjjbntZl,
  GetYjjbntFl,
  GetYjjbntBhqk,
  GetYjjbntLnbhqk,
  GetYjjbntQxfl,
} from "@/api/ghss/gdbhadd.js";
import { legends } from "../config.js";
import {
  loadGeoJSON,
  Getlayers,
  addImagery,
  SetParameters,
} from "@/utils/MapHelper/help.js";
import { init_handler } from "@/utils/MapHelper/clickQuery.js";
export default {
  props: {
    pageType: {
      type: String,
    },
  },
  data() {
    return {
      region: "4602",
      dlbm: "01",
      gtype: "耕地",
      nowunit: 0,
      unitList: [
        { code: 0, name: "平方千米", unit: "km²" },
        { code: 1, name: "平方米", unit: "m²" },
        { code: 2, name: "亩", unit: "亩" },
        { code: 3, name: "公顷", unit: "公顷" },
      ],
      nowyear: "",
      uprops: ["mj_qm", "mj", "mj_m", "mj_gq"],
      // bhprops: ["d1_mj_qm", "d1_mj", "mj_m"],
      yearList: [],
      typeList: [],
      tab: "2023",
      zllist: {
        永久基本农田: [{ name: "永久基本农田" },
        { name: "占现状耕地比", prop: "zb", unit: "%", }],
        耕地: [
          { name: "耕地保有量", },
          { name: "耕地保护目标", p: "bh_" },
        ],
        水田: [
          { name: "水田现状" },
          { name: "占耕地比", prop: "zb", unit: "%" },
        ],
        水浇地: [
          { name: "水浇地现状" },
          { name: "占耕地比", prop: "zb", unit: "%" },
        ],
        旱地: [
          { name: "旱地现状" },
          { name: "占耕地比", prop: "zb", unit: "%" },
        ],
      },
      bhlist: [
        { name: "变化面积" },
        { name: "变化幅度", prop: "mjbh", unit: "%" },
      ],

      zldata: {},
      fldata: {},
      bhdata: {},
      lnbndata: [],
      eData: {
        xData: ["2020", "2021", "2022", "2023"],
        yData: [[-10, 10, 10, 10]],
        legend: [""],
      },
      citymax: 1,
      cityList: [],
      imagelayers: {},
      nowlayer: "",
      provider: null,
      layers: [],
    };
  },
  components: {
    bar,
    Statistics,
  },
  created() {
    // this.getYear();
    // this.GetDate();
    this.typeList = [...JSON.parse(JSON.stringify(legends))];
  },
  mounted() { },
  methods: {
    changeData(name, updata) {
      this[name] = updata;
    },
    getYear() {
      let date = new Date();
      let startYear = date.getFullYear() - 4; //起始年份
      let endYear = date.getFullYear(); //结束年份
      for (var i = startYear; i <= endYear; i++) {
        this.yearList.push({ value: i, label: i + "年" });
      }
    },
    unitChange() {
      this.setLnbh(this.lnbndata);
    },
    yearChange() {
      // let yobj = this.yearList.find((y) => y.year == this.nowyear);
      // this.setImager(yobj);
      this.yearList.forEach((yobj) => {
        this.setImager(yobj, yobj.year == this.nowyear);
        if (yobj.year == this.nowyear) {
          init_handler(yobj, this.showInfo);
        }
      });
      this.regionChange();
    },
    dlbmChange() {
      // let nowtype = this.typeList.find((x) => x.id == this.dlbm);
      this.gtype = this.typeList.find((x) => x.id == this.dlbm).label;
      if (this.pageType && this.dlbm == "01") this.gtype = "永久基本农田"
      this.xzqhChange();
      // this.regionChange();
      // if (this.dlbm == "01") {
      //   this.nowlayer = this.nowyear;
      // } else {
      //   if (nowtype.layerID) {
      //     this.nowlayer = this.nowyear + nowtype.layerID;
      //   } else if (this.layers.length) {
      //     let yobj = this.yearList.find((y) => y.year == this.nowyear);
      //     if (yobj) this.goLayer(yobj, nowtype);
      //   }
      // }
    },
    xzqhChange() {
      this.regionChange();
      if (this.layers.length) {
        let yobj = this.yearList.find((y) => y.year == this.nowyear);
        if (yobj) this.goLayer(yobj);
      }
    },
    goLayer(lobj, nowtype) {
      let lname = this.layers[0].name; // `dlbm like '${this.dlbm}%'`,
      let sql = `${this.pageType ? "xzqdm" : "qsdwdm"} LIKE '%${this.region}%'`;
      if (this.dlbm != '01') sql += ` and dlbm LIKE '${this.dlbm}%'`;
      SetParameters(lname, sql, this.provider, (lid) => {
        // this.typeList[nowtype.index].layerID = lid;
        this.nowlayer = this.nowyear + lid;
        this.setImager({ ...lobj, lid });
      });
    },
    async GetDate() {
      this.yearList = [];
      let res = {};
      if (this.$props.pageType == 0) {
        res = await GetGdDate();
      } else {
        res = await GetYjjbntDate();
      }
      res.data.forEach((item) => {
        this.yearList.push({
          ...item,
          url: item.serverurl,
          fwgzkj: item.serverfwgzkj,
          fwmc: item.serverfwmc,
          source: "",
          title: item.year,
          id: item.serverid,
        });
      });

      this.nowyear = this.yearList.length ? this.yearList[0].year : "";
      this.nowlayer = this.nowyear;
      init_handler(this.yearList[0], this.showInfo);
      store.setaddNode([
        { id: "gdbh", url: this.yearList[0].url, label: "耕地保护" },
      ]);
      // + this.$props.pageType
      this.setImager(this.yearList[0], true, (layer) => {
        Getlayers(this.yearList[0].url, (layers) => {
          this.layers = layers;
          // SetParameters(
          //   layers,
          //   `dlbm like '${this.dlbm}%'`,
          //   this.provider,
          //   (lid) => {
          //     this.setImager({ ...this.yearList[0], lid });
          //   }
          // );
        });
      });
    },
    showInfo(data, obj) {
      let alegends = store.state.addlegend;
      if (alegends && alegends.length && alegends[0].id == "gdbh") {
        this.$emit("handleView", data, obj);
      }
    },
    setImager(obj, isshow = true, fun) {
      let lkey = obj.year + (obj.lid || "");
      // console.log(lkey, isshow, this.imagelayers[lkey], "---");
      if (this.imagelayers[lkey]) this.imagelayers[lkey].show = isshow;
      else if (isshow && obj.url) {
        let { supProvider, layer } = addImagery(obj);
        if (!obj.lid) this.provider = supProvider;
        this.imagelayers[lkey] = layer;
      }
      if (obj.top) viewer.imageryLayers.raiseToTop(this.imagelayers[lkey]);
      fun && fun(this.imagelayers[lkey]);
      if (this.imagelayers[lkey]) viewer.flyTo(this.imagelayers[lkey]);
    },
    async regionChange(region) {
      // this.region = region;
      if (this.dlbm == "01") this.gtype = this.pageType ? "永久基本农田" : '耕地'
      if (region) this.nowyear = "";
      if (!this.nowyear) await this.GetDate();
      this.getData();
    },
    getData() {
      this.$emit("updateParent", "loading", true);
      this.Getzzxm();
      // this.Getkjxx();
    },
    async Getzzxm() {
      let parms = { year: this.nowyear, xzqhdm: this.region, dlbm: this.dlbm };
      if (this.$props.pageType == 0) {
        GetGdZl(parms).then((res) => {
          this.zldata = res.data;
          GetGdQxfl(parms).then((res) => {
            this.citymax = 0
            res.data.forEach(c => {
              c.number = (c.mj_m / this.zldata.mj_m * 100).toFixed(2);
              if (this.citymax < c.number) this.citymax = Math.ceil(c.number / 10) * 10;
            })
            this.cityList = res.data;
          });
        });
        if (this.dlbm == "01")
          GetGdFl(parms).then((res) => {
            this.fldata = res.data;
          });

      } else {
        GetYjjbntZl(parms).then((res) => {
          this.zldata = res.data;
          GetYjjbntQxfl(parms).then((res) => {
            this.citymax = 0
            res.data.forEach(c => {
              c.number = (c.mj_m / this.zldata.mj_m * 100).toFixed(2);
              if (this.citymax < c.number) this.citymax = Math.ceil(c.number / 10) * 10;
            })
            this.cityList = res.data;
          });
        });
        if (this.dlbm == "01")
          GetYjjbntFl(parms).then((res) => {
            this.fldata = res.data;
          });

      }
      this.GetLnbhqk();
      this.GetBhqk();
    },

    GetLnbhqk() {
      this.eData.xData = [];
      this.eData.yData = [[]];
      let parms = { year: this.nowyear, xzqhdm: this.region, dlbm: this.dlbm };
      if (!this.$props.pageType) {
        GetGdLnbhqk(parms).then(({ data }) => {
          this.lnbndata = data;
          this.setLnbh(data);
        });
      } else {
        GetYjjbntLnbhqk(parms).then(({ data }) => {
          this.lnbndata = data;
          this.setLnbh(data);
        });
      }
    },
    setLnbh(data) {
      this.eData.yName = `变化面积${this.unitList[this.nowunit].unit}`;
      this.eData.xData = [];
      this.eData.yData = [[]];
      data.forEach((res) => {
        this.eData.xData.push(res.year);
        this.eData.yData[0].push(res[this.uprops[this.nowunit]]);
      });

      this.setEchart(this.eData, 0);
    },
    GetBhqk() {
      let params = {
        sourceyear: this.nowyear,
        targeyear: this.tab,
        xzqhdm: this.region,
      };
      if (!this.$props.pageType) {
        GetGdBhqk(params).then((res) => {
          this.bhdata = res.data;
        });
      } else {
        GetYjjbntBhqk(params).then((res) => {
          this.bhdata = res.data;
        });
      }
    },

    async Getkjxx() {
      let res = await QueryList({
        jscType: "qytuzz_sdzl_kjxx",
        id: this.region,
      });
      this.active_tableData(res.data);
    },
    active_tableData(newVal) {
      newVal.forEach((res, index) => {
        let color = legends[res.type].color;
        if (res.geom)
          loadGeoJSON(res.geom, color, { isfly: true }, (data) => {
            geoSources[res.id] = data;
            data.name = "LandConsolidation";
            // data.entities.values.forEach((entity) => {
            //   entity.properties = { type: "图斑上图", id: res.id };
            // });
          });
      });
    },
    contrast() {
      let dbdata = { id: this.region, fp: this.yearList.sort((a, b) => a.year - b.year), type: "gdbh" }; //+ this.$props.pageType,
      console.log("contrast", dbdata);
      this.setImager({ year: this.nowlayer }, false);
      this.$emit("contrast", dbdata);
    },
    fly() {
      // viewer.flyTo(this.imagelayers[this.nowlayer]);
    },
    sourcesshow(show) {
      this.setImager({ year: this.nowlayer }, show);
    },
    reset() {
      store.setaddNode([]);
      this.$nextTick(() => {
        // this.sourcesshow(false);
        Object.keys(this.imagelayers).forEach((key) => {
          viewer.imageryLayers.remove(this.imagelayers[key]);
        });
        this.imagelayers = {};
        this.typeList = [...JSON.parse(JSON.stringify(legends))];
      });
    },
    setEchart(data, id) {
      this.$nextTick(() => {
        this.$refs[`echartRef${id}`].setOptions(data);
      });
    },
  },
  watch: {
    region(newValue) {
      console.log(newValue, "---");
    },
    nowlayer(newValue, oldVal) {
      // this.setImager({ year: oldVal }, false);
      // this.setImager({ year: newValue }, true);
    },
  },
  beforeDestroy() {
    store.setaddNode([]);
    this.yearList.forEach((yi) => {
      viewer.imageryLayers.remove(this.imagelayers[yi.year]);
    });
  },
};
</script>

<style lang="scss" scoped>
.gdzl {
  height: 100%;

  .region {
    width: 100px !important;
    position: absolute;
    right: 20px;
  }

  .el-select {
    padding: 0 10px;
  }

  .headerSelect {
    width: 100%;
    height: 26px;
    //   background: #00ffff;
    margin: 5px 0px;
    display: flex;
    justify-content: space-between;
  }

  .content {
    width: 100%;
    height: 190px;
    padding-top: 5px;

    .item {
      width: 32%;
      // height: 100px;
      display: inline-block;
      position: relative;

      .icon {
        width: 100%;
        height: 50px;
        display: flex;
        justify-content: space-between;
      }

      .iicon {
        background: no-repeat 50%;
        background-image: url("/static/images/overview/icon_yrkkg.png");
        width: 45px;
        height: 45px;
        flex: 1;
      }
    }

    .item50 {
      width: 48%;
    }

    .text {
      display: inline-block;
      // border: #00FFFF 1px solid;
      width: 100%;
      margin-bottom: 4px;
      text-align: center;
      margin-left: 0.3rem;

      .cvalue {
        font-family: "Arial Negreta", "Arial Normal", "Arial";
        font-weight: 700;
        font-style: normal;
        color: #68f4fb;
      }

      .unit {
        color: #fff;
      }
    }
  }

  .gdzlc {
    height: 65px;
    display: flex;
    justify-content: space-between;

    .item {
      width: 48%;
      height: 60px;
      padding-left: 20px;
      background: rgba(104, 244, 251, 0.21568627); // #2f5b71;
      border-radius: 5px;

      .icon {
        width: 50px;
        display: inline-block;
      }

      .text {
        display: inline-block;
        width: calc(100% - 60px);
        text-align: left;
      }
    }
  }

  .scontent {
    height: 60px;
    background: rgba(104, 244, 251, 0.21568627); //#2f5b71;
    border-radius: 5px;
    padding-top: 10px;
    margin-top: 5px;
    display: flex;

    .posNum {
      color: #ec808d !important;
    }

    .negNum {
      color: #00cc3a !important;
    }
  }

  .echars {

    // width: 100%;
    // height: calc(100% - 120px);
    // overflow-y: auto;
    // overflow-x: hidden;
    .echartTitle {
      height: 35px;
    }

    .block-title {
      width: calc(100% - 185px) !important;
    }

    .titlesel {
      width: 250px;
      display: flex;
    }
  }

  .echart {
    height: 200px !important;
  }

  .pietitle {
    position: relative;
    width: 200px;
    line-height: 26px;
    text-align: center;
    border: 1px solid #3f93f5;
    border-top-right-radius: 10px;
    margin: 10px 20% 0px 20%;
    color: #3f93f5;
  }

  .pie_echart {
    // width: 400px;
    margin-top: 10px;
    width: 21vw;
    height: 140px;
  }
}
</style>
