<template>
  <div
    class="ZTGlobal"
    style="width: 100%; padding: 1rem 1rem 0rem 1rem; color: white"
  >
    <el-container style="height: 100%">
      <el-header height="12rem">
        <el-row :gutter="10" style="display: flex; align-items: center">
          <el-col :span="18">
            {{ info.BenchmarkLandPrice.ProjectName }}
          </el-col>
          <el-col :span="6">
            <el-button size="mini" type="default" @click="handleGetBG"
              >导出报告</el-button
            >
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-row :gutter="10" class="container_center">
              <el-col
                :span="8"
                class="container_center"
                style="
                  height: 3rem;
                  background-color: rgba(2, 167, 240, 1);
                  border-radius: 6px;
                "
              >
                <i style="font-size: 2rem" class="el-icon-office-building"></i>
              </el-col>
              <el-col
                :span="16"
                class="container_center"
                style="justify-content: flex-start"
              >
                <div class="con-col" style="align-items: flex-start">
                  <a style="color: white">分析总范围（亩）</a>
                  <a style="font-weight: bold; color: rgba(2, 167, 240, 1)">{{
                    Number(
                      info.BenchmarkLandPrice.AnalysisResults.analysisArea
                    ).toFixed(2)
                  }}</a>
                </div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="10" class="container_center">
              <el-col
                :span="8"
                class="container_center"
                style="
                  height: 3rem;
                  background-color: rgba(2, 167, 240, 1);
                  border-radius: 6px;
                "
              >
                <i style="font-size: 2rem" class="el-icon-bank-card"></i>
              </el-col>
              <el-col
                :span="16"
                class="container_center"
                style="justify-content: flex-start"
              >
                <div class="con-col" style="align-items: flex-start">
                  <a style="color: white">总地价（万元）</a>
                  <a style="font-weight: bold; color: rgba(2, 167, 240, 1)">{{
                    Number(
                      info.BenchmarkLandPrice.AnalysisResults.totalLandPrice
                    ).toFixed(2)
                  }}</a>
                </div>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-row :gutter="10" class="container_center">
              <el-col
                :span="8"
                class="container_center"
                style="
                  height: 3rem;
                  background-color: rgba(2, 167, 240, 1);
                  border-radius: 6px;
                "
              >
                <i style="font-size: 2rem" class="el-icon-discount"></i>
              </el-col>
              <el-col
                :span="16"
                class="container_center"
                style="justify-content: flex-start"
              >
                <div class="con-col" style="align-items: flex-start">
                  <a style="color: white">计算地价面积</a>
                  <a style="color: white">（亩）</a>
                  <a style="font-weight: bold; color: rgba(2, 167, 240, 1)">{{
                    Number(
                      info.BenchmarkLandPrice.AnalysisResults.ParticipationArea
                    ).toFixed(2)
                  }}</a>
                </div>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <el-tabs v-model="activeName" class="full-height">
          <el-tab-pane label="总体情况" name="first" style="height: 100%">
            <div id="echartFGY" ref="echartFGY" class="EchartsWH">
              <div
                id="GYEcharts"
                ref="GYEcharts"
                style="width: 100%; height: 100%"
              ></div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="地块详情" name="second" style="height: 100%">
            <el-table
              :data="tableData"
              :span-method="objectSpanMethod"
              border
              height="100%"
              style="width: 100%"
              @row-click="rowClick"
            >
              <el-table-column prop="dkbm" label="地块编码" width="60">
              </el-table-column>
              <el-table-column prop="ghyt" label="地类名称"> </el-table-column>

              <el-table-column prop="area" align="center">
                <template slot="header">
                  <div>占用面积</div>
                  <div>（亩）</div>
                </template>
                <template slot-scope="scope">
                  <span>{{ scope.row.area }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="tdjb" align="center" width="40">
                <template slot="header">
                  <div>级别</div>
                </template>
                <template slot-scope="scope">
                  <span>{{ scope.row.tdjb }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="dj" align="center">
                <template slot="header">
                  <div>单价</div>
                  <div>（万元）</div>
                </template>
                <template slot-scope="scope">
                  <span>{{ scope.row.dj }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="zdj" align="center">
                <template slot="header">
                  <div>总地价</div>
                  <div>（万元）</div>
                </template>
                <template slot-scope="scope">
                  <span>{{ scope.row.zdj }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import elementResizeDetectorMaker from "element-resize-detector";
import PlanningPlotInfo from "@/views/ConstructionApplication3D/PlanningPlot/PlanningPlotInfo.vue";
import { getJZDJWord, getWord } from "@/api/zt/ztApi.js";
export default {
  data() {
    return {
      tableData: [],
      spanArray: [],

      //点查entities事件
      getEntitiesHandler: {},
      /**
       * tabs 标签
       */
      activeName: "first",
      GYmyChart: null,
      JTmyChart: null,
      Interval: null,
      entitieid: "",
      Interval: null,
    };
  },
  props: {
    info: {
      type: Object,
      default: () => {
        return {};
      },
    },
    layerid: {
      type: String,
      default: "",
    },
    lydata: {
      type: Object,
      default: () => {
        return {};
      },
    },
    lyoption: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  created() {},
  mounted() {
    const erd = elementResizeDetectorMaker();
    let that = this;
    erd.listenTo([this.$refs.echartFGY], () => {
      //, this.$refs.echartFJT
      that.$nextTick(() => {
        //监听到事件后执行的业务逻辑
        window.echarts.init(this.$refs.GYEcharts).resize();
        // window.echarts.init(this.$refs.JTEcharts).resize();
      });
    });
    this.init();
  },
  methods: {
    async init() {
      // 设置用地类型图层颜色
      let ghyts = [];
      this.info.BenchmarkLandPrice.AnalysisResults.ghdkDetailedDjList.forEach(
        (ghdkDetailedDj) => {
          if (!ghyts[ghdkDetailedDj.ghyt]) {
            ghyts[ghdkDetailedDj.ghyt] = this.getLandColor(ghdkDetailedDj.ghyt);
          }
        }
      );
      this.info.BenchmarkLandPrice.AnalysisResults.ghdkDetailedDjList.forEach(
        (ghdkDetailedDj) => {
          ghdkDetailedDj.ColorString = ghyts[ghdkDetailedDj.ghyt];
        }
      );

      this.initEntitiesHandler();
      this.DrawScope();
      this.initTable();
      let entitys = [];
      if (viewer.entities.getById("HZFW")) {
        entitys.push(viewer.entities.getById("HZFW"));
      }
      viewer.flyTo(entitys);
      await this.YDFLZDJChart();
    },
    /**
     * 渲染绘制范围
     */
    DrawScope() {
      this.info.BenchmarkLandPrice.AnalysisResults.ghdkDetailedDjList.forEach(
        (ghdkDetailedDj) => {
          let point3ds = [];
          let pointholes = [];
          let startindex = 0;
          for (
            let index = 0;
            index < ghdkDetailedDj.geometry.parts.length;
            index++
          ) {
            let thisps = [];
            const endindex = startindex + ghdkDetailedDj.geometry.parts[index];
            let geometryPoints = ghdkDetailedDj.geometry.points.slice(
              startindex,
              endindex
            );
            for (
              let pointindex = 0;
              pointindex < geometryPoints.length;
              pointindex++
            ) {
              const point = geometryPoints[pointindex];
              thisps.push(point.x);
              thisps.push(point.y);
            }
            if (ghdkDetailedDj.geometry.partTopo[index] === 1) {
              point3ds.push(Cesium.Cartesian3.fromDegreesArray(thisps));
            } else {
              pointholes.push(Cesium.Cartesian3.fromDegreesArray(thisps));
            }

            startindex = endindex;
          }

          let col = Cesium.Color.fromCssColorString(ghdkDetailedDj.ColorString);
          if (point3ds.length > 0 && pointholes.length > 0) {
            let holes = [];
            pointholes.forEach((hole) => {
              holes.push({ positions: hole });
            });

            var orangePolygon1 = viewer.entities.add({
              id: ghdkDetailedDj.id,
              polygon: {
                hierarchy: {
                  // Cesium.PolygonHierarchy
                  positions: point3ds[0],
                  holes: holes, // Cesium.PolygonHierarchy 数组
                },
                material: col.withAlpha(0.4),
                outline: true,
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 2.0,
              },
            });
          } else if (point3ds.length > 0) {
            var orangePolygon1 = viewer.entities.add({
              id: ghdkDetailedDj.id,
              polygon: {
                hierarchy: point3ds[0],
                material: col.withAlpha(0.4),
                outline: true,
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 2.0,
              },
            });
          }
        }
      );

      let ProjectScope = this.info.BenchmarkLandPrice.ProjectScope;
      if (ProjectScope.length > 0) {
        if (ProjectScope[0] != ProjectScope[ProjectScope.length - 1]) {
          ProjectScope.push(ProjectScope[0]);
        }
        let points = ProjectScope.map((obj) => [obj.x, obj.y]).flat();
        var orangePolygon1 = viewer.entities.add({
          id: "HZFW",
          polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
            material: Cesium.Color.CHARTREUSE.withAlpha(0.1), //Cesium.Color.RED.withAlpha(0.4),
            outline: true,
            outlineColor: Cesium.Color.RED,
            outlineWidth: 2.0,
          },
        });
      } else {
        // this.$message.error("请在传入分析范围");
        console.log("未传入分析范围");
      }
    },

    initTable() {
      this.info.BenchmarkLandPrice.AnalysisResults.ghdkDetailedDjList.forEach(
        (ghdkDetailedDj, i) => {
          if (ghdkDetailedDj.zytdList.length > 0) {
            this.spanArray.push(ghdkDetailedDj.zytdList.length);
            for (
              let index = 1;
              index < ghdkDetailedDj.zytdList.length;
              index++
            ) {
              this.spanArray.push(0);
            }
          } else {
            this.spanArray.push(1);
          }
          if (ghdkDetailedDj.zytdList.length > 0) {
            ghdkDetailedDj.zytdList.forEach((zytd) => {
              let row = {
                ColorString: ghdkDetailedDj.ColorString,
                dkbm: ghdkDetailedDj.dkbm,
                ghyt: ghdkDetailedDj.ghyt,
                area: zytd.area.toFixed(2),
                dj: zytd.dj.toFixed(2),
                tdjb: zytd.tdjb,
                zdj: zytd.zdj.toFixed(2),
                ghdkDetailedDjid: ghdkDetailedDj.id,
              };
              this.tableData.push(row);
            });
          } else {
            let row = {
              ColorString: ghdkDetailedDj.ColorString,
              dkbm: ghdkDetailedDj.dkbm,
              ghyt: ghdkDetailedDj.ghyt,
              ghdkDetailedDjid: ghdkDetailedDj.id,
            };
            this.tableData.push(row);
          }
        }
      );
    },
    objectSpanMethod({ rowIndex, columnIndex }) {
      debugger;
      if (columnIndex === 0 || columnIndex === 1) {
        let _row = this.spanArray[rowIndex];
        let _col = _row > 0 ? 1 : 0;
        // console.log(`{rowspan: ${_row}, colspan: ${_col}}`);
        // 打印结果
        // {rowspan: 3, colspan: 1}
        // {rowspan: 0, colspan: 0}
        // {rowspan: 0, colspan: 0}
        // {rowspan: 2, colspan: 1}
        // {rowspan: 0, colspan: 0}
        // {rowspan: 4, colspan: 1}
        // {rowspan: 0, colspan: 0}
        // {rowspan: 0, colspan: 0}
        // {rowspan: 0, colspan: 0}

        // {rowspan: 0, colspan: 0}  表示此行不显示
        // {rowspan: 2, colspan: 1}  表示跨两行
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    rowClick(row) {
      let that = this;
      debugger;
      if (that.Interval) {
        clearInterval(that.Interval);
        that.Interval = null;
      }

      if (that.entitieid != "") {
        var entitie = viewer.entities.getById(that.entitieid);
        let ghdkDetailedDj =
          this.info.BenchmarkLandPrice.AnalysisResults.ghdkDetailedDjList.find(
            (c) => c.id == that.entitieid
          );
        let col = Cesium.Color.fromCssColorString(
          ghdkDetailedDj.ColorString
        ).withAlpha(0.4);
        entitie.polygon.material = col;
        that.entitieid = "";
      }
      if (row) {
        that.entitieid = row.ghdkDetailedDjid;
        that.Interval = setInterval(function () {
          var entitie = viewer.entities.getById(that.entitieid);
          if (entitie.polygon.material.color.getValue().alpha == 0.4) {
            entitie.polygon.material = new Cesium.Color(
              3 / 255,
              240 / 255,
              248 / 255,
              1
            );
          } else {
            entitie.polygon.material = new Cesium.Color(
              3 / 255,
              240 / 255,
              248 / 255,
              0.4
            );
          }
        }, 1000);

        var entitie = viewer.entities.getById(that.entitieid);
        if (entitie) {
          viewer.flyTo(entitie, { maximumHeight: 30 });
        }
      }
    },

    /**
     * 点击弹窗显示图斑信息
     */
    initEntitiesHandler() {
      let that = this;
      this.getEntitiesHandler = new Cesium.ScreenSpaceEventHandler(
        scene.canvas
      );
      this.getEntitiesHandler.setInputAction(function (click) {
        let pick = viewer.scene.pick(click.position);
        let id, info;

        //规划地块信息弹窗
        if (pick && pick.id.id) {
          id = pick.id.id;
          info =
            that.info.BenchmarkLandPrice.AnalysisResults.ghdkDetailedDjList.find(
              (c) => c.id == id
            );
          if (info) {
            that.openOBJInfo("规划地块详情", info.data);
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    //打开用地红线信息弹窗
    openOBJInfo(title, info) {
      let w = document.body.offsetWidth;
      let h = document.body.offsetHeight;
      //左上角(left=弹窗宽/2;top=弹窗高/2+header高)
      //右上角 (left=w-弹窗宽+(弹窗宽/2);top=弹窗高/2+header高);
      let left = 430 / 2 + 556;
      let top = 430 / 2 + 60;
      this.$layer.iframe({
        id: "OBJInfolayer",
        content: {
          content: PlanningPlotInfo, //传递的组件对象
          parent: this, //当前的vue对象
          data: { info }, //props
        },
        offset: [left, top], //left top
        area: ["430px", "430px"], //宽 高
        title: title,
        maxmin: false,
        shade: false, //是否显示遮罩
        shadeClose: false, //点击遮罩是否关闭
        cancel: () => {
          //关闭事件
          // alert("关闭iframe");
        },
      });
    },
    /**
     * 打印分析报告
     */
    async handleGetBG() {
      if (
        this.info.BenchmarkLandPrice &&
        this.info.BenchmarkLandPrice.AnalysisResults
      ) {
        debugger;
        await getJZDJWord(this.info.BenchmarkLandPrice.AnalysisResults);
      }
    },

    clear() {
      //删除规划地块图层
      for (
        let index = 0;
        index <
        this.info.BenchmarkLandPrice.AnalysisResults.ghdkDetailedDjList.length;
        index++
      ) {
        const element =
          this.info.BenchmarkLandPrice.AnalysisResults.ghdkDetailedDjList[
            index
          ];
        viewer.entities.removeById(element.id);
      }
      this.info.BenchmarkLandPrice.AnalysisResults.ghdkDetailedDjList = [];
      //删除绘制范围
      viewer.entities.removeById("HZFW");
    },

    /**
     * 获取用地用海分类统一颜色
     */
    getLandColor(name) {
      var color = "rgb(172,255,207)";
      window.colorList.forEach((element) => {
        if (element.name.indexOf(name) > -1) color = element.color;
      });
      if (color == "rgb(172,255,207)") {
        const r = Math.floor(Math.random() * 256);
        const g = Math.floor(Math.random() * 256);
        const b = Math.floor(Math.random() * 256);
        color = `rgb(${r}, ${g}, ${b})`;
      }
      return color;
    },
    /**
     *用地分类总地价chart
     */
    YDFLZDJChart() {
      var that = this;

      this.myChart = window.echarts.init(this.$refs.GYEcharts);
      var datas = [];
      var nameLength = 0;
      var colors = [];
      var color = "";
      let djGroup = this.GroupByzdj(this.tableData);
      djGroup.forEach((element) => {
        if (element.ghyt.length > nameLength) {
          nameLength = element.ghyt.length;
        }

        datas.push({
          area: Number(element.area.toFixed(2)),
          value: Number(element.zdj.toFixed(2)),
          name: element.ghyt,
        });
        color = element.ColorString;
        colors.push(color);
      });

      var option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c}万元 ({d}%)",
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          right: 0,
          top: "center",
          // bottom: 20,
          radius: "55%",
          textStyle: {
            // fontSize: '12px',
            color: "#FFFF",
          },
          pageTextStyle: {
            color: "#FFFF",
          },
          data: datas.map((t) => t.name),
          formatter: function (name) {
            var thisdata = datas.find((t) => t.name == name);

            let lab = "";
            // 遍历输入字符串的每个字符
            for (let i = 0; i < name.length; i++) {
              if ((i + 1) % 4 === 0 && i !== name.length - 1) {
                lab += name[i] + "\n";
              } else {
                lab += name[i];
              }
            }

            var lastSpace = "   ";
            if (name.length % 4 != 0) {
              lastSpace += "   ".repeat(4 - (name.length % 4));
            }
            return (
              lab +
              lastSpace +
              "\n" +
              thisdata.area +
              "亩" +
              thisdata.value +
              "万元"
            );
          },
        },
        color: colors, // ['#0a915d', '#bb88dd', '#6699ff', '#d5b158', '#ff6347', 'indigo', 'purple'],
        series: [
          {
            name: "规划地类总地价",
            type: "pie",
            center: ["25%", "50%"],
            radius: ["30%", "50%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 12,
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: datas,
          },
        ],
      };
      this.myChart.setOption(option);
    },

    /**
     * 对数组字段分组并求和计算每个土地用途的总地价
     * @param data
     */
    GroupByzdj(data) {
      const groupedData = data.reduce((accumulator, currentValue) => {
        // 如果累加器（accumulator）中没有这个分组，就添加它
        if (!accumulator[currentValue.ghyt]) {
          accumulator[currentValue.ghyt] = {
            ghyt: currentValue.ghyt,
            zdj: 0,
            area: 0,
            ColorString: currentValue.ColorString,
          };
        }
        // 将当前对象的b值累加到对应分组上
        accumulator[currentValue.ghyt].zdj += Number(
          currentValue.zdj ? currentValue.zdj : 0
        );
        accumulator[currentValue.ghyt].area += Number(
          currentValue.area ? currentValue.area : 0
        );
        // 返回累加器，以便下一次迭代使用
        return accumulator;
      }, {});

      // 将结果转换为数组（如果需要的话）
      const resultArray = Object.keys(groupedData).map(
        (key) => groupedData[key]
      );
      return resultArray;
    },
  },
  beforeDestroy() {
    if (this.Interval) {
      clearInterval(this.Interval);
      this.Interval = null;
    }
    if (this.getEntitiesHandler) {
      this.getEntitiesHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_CLICK
      );
    }
    this.clear();
  },
};
</script>
<style lang="scss">
@import "@/../../zt.scss";
</style>
<style scoped>
.el-date-editor--daterange.el-input__inner {
  width: auto;
  background-color: rgba(4, 28, 50, 0.5);
  border: 1px solid rgba(15, 122, 200, 0.4);
}
.card_body_style {
  border: 1px dashed #02a7f0;
}
.hover_style:hover {
  border: 1px solid #02a7f0;
}
.con-col {
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
}

.container_center {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中，如果也需要水平居中的话 */
}
.EchartsWH {
  width: 100%;
  height: 100%;
}
.full-height {
  height: 100%; /* 适应父容器的高度 */
}
.full-height >>> .el-tabs__content {
  height: calc(100% - 55px); /* 计算内容区域的高度 */
  overflow-y: auto; /* 滚动条 */
}
.el-main {
  padding: 0px;
}
</style>
