import { getConfigKey } from "@/api/system/config";
import { getInfo } from "@/api/login";
import { treeselect, treeselectByDeptId } from "@/api/system/dept";

import GisUtils from '@/utils/gis.js';
import {
  assetsStatistics,
  deptFundStatistics,
  financeSummary, financeSummaryOverview, incomeBookRank, incomeMonthStatistics, incomeTownRank,
  resourceAssetsStatistics
} from "@/api/dataScreen/bigDataMonitoring2/stockCooperative.js";
import { comps } from './data.js'
import {
  fromLonLat
} from 'ol/proj'

let gis = null;

const DEPT_CHANGED = 1;
const YEAR_CHANGED = 1 << 1;
const ALL_CHANGED = ~(1 << 31);
export default {
  components: {
  },
  props: {
    showYears: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    'queryParams.deptId': {
      handler: function () {
        this.commitDept(this.queryParams.deptId);
      },
      immediate: true, // 立即执行

    },
    deptLength: {
      handler: function () {
        console.log(this.deptLength);
        this.commitDeptLength(this.deptLength);
      },
      immediate: true, // 立即执行
    }
  },
  data () {
    return {
      financeSummary: {
        funds: 0, // 资金
        totalAssets: 0, // 资产
        totalResource: 0, // 资源
        income: 0, // 经营收入
        outcome: 0, // 经营支出
        overhead: 0, // 管理费用
        revenue: 0, // 发包收入
        otherIncome: 0, // 其他收入
        otherOutcome: 0, // 其他支出
      },
      financeSummaryOverview: {
        zeroIncomeBook: 0, // 0收入组织
        areaTotalIncome: 0, // 区收入总和
        townAvgIncome: 0, // 镇平均收入
        bookAvgIncome: 0, // 组织平均收入
      },
      //搜索栏参数
      centerYear: new Date().getFullYear(),
      yearList: [
        new Date().getFullYear(),
        new Date().getFullYear() - 1,
        new Date().getFullYear() - 2,
        new Date().getFullYear() - 3,
        new Date().getFullYear() - 4,
      ],
      addrText: [100,],
      deptTreeProps: {
        checkStrictly: true,
      },
      queryParams: {
        year: new Date().getFullYear(),
        deptId: 100,
      },
      deptLength: 0,
      yellowIcon: require('./icon/yellow.png'),
      comps,
      map: "",                        // 地图
      mapGeoServerUrl: "",            // geoserver地址
      mapBorder: "",                  // 地图边界
      deptLayer: "",                  // 坐标点图层
      countyBorderLayerName: "",      // 区县边界图层名称
      townBorderLayerName: "",        // 乡镇边界图层名称
      villageBorderLayerName: "",     // 村边界图层名称
      groupBorderLayerName: "",       // 组边界图层名称
      addrOptions: []
    };
  },
  computed: {
    currentComp: function () {
      return this.comps[this.tab]
    }
  },
  created () {
  },
  mounted () {
    this.commitYear(this.centerYear);
    // 获取geoserver的地址
    this.getGeoServerUrl();
    getInfo().then(res => {
      // this.getData();
      treeselectByDeptId({ deptId: res.user.deptId }).then((resp) => {
        this.addrOptions = resp.data;
        // 初始化地图
        this.initMap();
      });
    });
  },
  methods: {
    /**
     * 提交dept
     * @param {*} deptId
     */
    commitDept (deptId) {
      this.$store.commit('SET_DEPTID', deptId);
    },
    commitDeptLength (length) {
      this.$store.commit('SET_DEPTIDLENGTH', length);
    },
    commitYear (year) {
      this.$store.commit('SET_YEAR', year);
    },
    //切换年份
    yearDropdown (item) {
      this.queryParams.year = item;
      this.centerYear = item;
      this.getData(YEAR_CHANGED);
      this.commitYear(item);
    },
    // 绘制地图
    drawMap (node, isLocated) {    // isLocated 控制地图是否跳转
      const dept = node.data;
      gis.getMapContainer().removeLayer(this.mapBorder);
      this.mapBorder = '';
      gis.getMapContainer().removeLayer(this.deptLayer);
      this.deptLayer = '';
      if (dept.deptLevel === '5') {
        this.cityId = dept.id;
        this.currentDeptLevel = '5';
        if (dept.children && dept.children.length > 0) {
          // 添加区县边界
          this.addCountyBorder(dept.children.map(item => item.id));
          // 添加坐标点图层
          this.addDeptLayer(dept.children, 'yellow.png');
        }
        if (isLocated) {
          gis.getMapContainer().getView().setZoom(9);
          gis.getMapContainer().getView().setCenter(fromLonLat([dept.lng, dept.lat]));
        }
      } else if (dept.deptLevel === '4') {
        this.countyId = dept.id;
        this.currentDeptLevel = '4';
        if (dept.children && dept.children.length > 0) {
          // 添加乡镇边界
          this.addTownBorder(dept.children.map(item => item.id));
          // 添加坐标点图层
          this.addDeptLayer(dept.children, 'yellow.png');
        }
        if (isLocated) {
          gis.getMapContainer().getView().setZoom(11);
          gis.getMapContainer().getView().setCenter(fromLonLat([dept.lng, dept.lat]));
        }
        // this.villageIds = this.findLeafNodeIds(dept);
      } else if (dept.deptLevel === '3') {
        this.townId = dept.id;
        this.countyId = node.path.slice(-2)[0];
        this.currentDeptLevel = '3';
        if (dept.children && dept.children.length > 0) {
          // 添加村边界
          this.addVillageBorder(dept.children.map(item => item.id));
          // 添加坐标点图层
          this.addDeptLayer(dept.children, 'yellow.png');
        }
        if (isLocated) {
          gis.getMapContainer().getView().setZoom(13);
          gis.getMapContainer().getView().setCenter(fromLonLat([dept.lng, dept.lat]));
        }
        // this.villageIds = this.findLeafNodeIds(dept);
      } else if (dept.deptLevel === '2') {
        this.ruralId = dept.id;
        this.townId = node.path.slice(-2)[0];
        this.countyId = node.path.slice(-3)[0];
        this.currentDeptLevel = '2';
        if (dept.children && dept.children.length > 0) {
          const groupIds = dept.children.map(item => item.id);
          // 添加组边界
          this.addGroupBorder(groupIds);
          // 添加组的坐标点图层，并且跳转到图层的中心点位置
          this.addGroupPointLayer(groupIds, isLocated);
        } else {
          // 添加村边界
          this.addVillageBorder(dept.id);
          // 添加坐标点图层
          let deptList = [];
          deptList.push(dept);
          this.addDeptLayer(deptList, 'yellow.png');
          if (isLocated) {
            gis.getMapContainer().getView().setCenter(fromLonLat([dept.lng, dept.lat]));
          }
        }
        if (isLocated) {
          gis.getMapContainer().getView().setZoom(15);
        }
        // this.villageIds = this.findLeafNodeIds(dept);
      } else if (dept.deptLevel === '1') {
        this.ruralId = node.path.slice(-2)[0];
        this.townId = node.path.slice(-3)[0];
        this.countyId = node.path.slice(-4)[0];
        this.currentDeptLevel = '1';
        // 添加组边界
        this.addGroupBorder(dept.id);
        // 添加组的坐标点图层，并且跳转到图层的中心点位置
        this.addGroupPointLayer(dept.id, isLocated);
        if (isLocated) {
          gis.getMapContainer().getView().setZoom(17);
        }
        // this.villageIds = this.findLeafNodeIds(dept);
      }
      // this.changeLayerByDept();
    },
    tabChange (info) {
      this.tab = info.id;
    },
    // 初始化地图
    initMap () {
      let dept = this.addrOptions[0];
      let mapCenterLocation;
      if (dept.lng && dept.lat) {
        mapCenterLocation = [dept.lng, dept.lat];
      } else {
        mapCenterLocation = [116.391461, 39.902359];
      }
      gis = new GisUtils('map22222')
      gis.addTianDiTuLayer()
      gis.addAnnotationLayer()
      if (dept.deptLevel === '5') {
        // 登录身份为市级领导
        this.userRole = 'cityLeader';
        this.cityId = dept.id;
        this.currentDeptLevel = '5';
        // 添加区县边界
        this.addCountyBorder(dept.children.map(item => item.id));
      } else if (dept.deptLevel === '4') {
        // 登录身份为县级领导
        this.userRole = 'countyLeader';
        this.countyId = dept.id;
        this.currentDeptLevel = '4';
        // 添加乡镇边界
        this.addTownBorder(dept.children.map(item => item.id));
        gis.getView().setZoom(11);
      } else if (dept.deptLevel === '3') {
        // 登录身份为镇级领导
        this.userRole = 'townLeader';
        this.townId = dept.id;
        this.currentDeptLevel = '3';
        // 添加村边界
        this.addVillageBorder(dept.children.map(item => item.id));
        gis.getView().setZoom(13);
      }
      // 添加坐标点图层
      if (dept.children) {
        this.addDeptLayer(dept.children);
      }
      gis.getView().setCenter(fromLonLat(mapCenterLocation))

      // 地图点击事件
      gis.getMapContainer().on("click", (evt) => {
        let feature = gis.getMapContainer().forEachFeatureAtPixel(
          evt.pixel,
          (feature) => feature
        );
        if (feature) {
          // 镇级：加载村级坐标点
          if (feature.get('level') === 'deptPoint') {
            let parentIds = [];
            this.findParentNodeIds(this.addrOptions, feature.get('deptId'), parentIds);
            this.addrText = parentIds;
            this.selectAddress(parentIds);
          }
        }
      });
    },
    getData (mask) {
      if (!mask)
        mask = ALL_CHANGED;
      financeSummary(this.queryParams).then((resp) => {
        let data = resp;
        this.financeSummary.funds = data.funds;
        this.financeSummary.totalAssets = data.totalAssets;
        this.financeSummary.totalResource = data.totalResource;
        this.financeSummary.income = data.income;
        this.financeSummary.outcome = data.outcome;
        this.financeSummary.overhead = data.overhead;
        this.financeSummary.revenue = data.revenue;
        this.financeSummary.otherIncome = data.otherIncome;
        this.financeSummary.otherOutcome = data.otherOutcome;
      });
      deptFundStatistics(this.queryParams).then((resp) => {
        let data = resp.data;
        // this.leftTopEchart(this.genChartData(data));
        this.fundAmountTotal = data.extras.total;
      });
      resourceAssetsStatistics(this.queryParams).then((resp) => {
        // this.leftBottomEchart(this.genChartData(resp.data));
      });
      assetsStatistics(this.queryParams).then((resp) => {
        // let data = this.genChartData(resp.data);
        // this.leftCenterEchart(data);
        // this.assetStatistics = data.xAxis.data.map((x, i) => {
        //   return {
        //     name: x,
        //     value: data.series[0].data[i],
        //   };
        // });
      });
      incomeMonthStatistics(this.queryParams).then((resp) => {
        // this.rightTopEchart(this.genChartData(resp.data));
      });
      incomeBookRank(this.queryParams).then((resp) => {
        this.incomeBookRankList = resp.data;
      });
      if (mask & YEAR_CHANGED) {
        incomeTownRank(this.queryParams).then((resp) => {
          this.incomeTownRankList = resp.data;
        });
        financeSummaryOverview(this.queryParams).then((resp) => {
          let data = resp.data;
          this.financeSummaryOverview.zeroIncomeBook = data.zeroIncomeBook;
          this.financeSummaryOverview.areaTotalIncome = data.areaTotalIncome;
          this.financeSummaryOverview.townAvgIncome = data.townAvgIncome;
          this.financeSummaryOverview.bookAvgIncome = data.bookAvgIncome;
          // this.dashboardZeroincome();
          // this.dashboardZeroincome2();
          // this.dashboardZeroincome3();
          // this.dashboardZeroincome4();
        });
      }
    },
    selectAddress (value, isLocated = true) {  // isLocated 控制地图是否跳转
      this.queryParams.deptId = value[value.length - 1];
      this.deptLength = value.length;
      this.getData(DEPT_CHANGED);
      let node = this.$refs["cascader2"].panel.getNodeByValue(value);
      this.drawMap(node, isLocated);
    },
    // 查找指定deptId的所有父节点id
    findParentNodeIds (tree, deptId, result) {
      for (let node of tree) {
        if (node.id === deptId) {
          result.unshift(node.id);
          return true;
        }
        if (node.children && node.children.length > 0) {
          let isFind = this.findParentNodeIds(node.children, deptId, result);
          if (isFind) {
            result.unshift(node.id);
            return true;
          }
        }
      }
      return false;
    },

    // 添加坐标点图层
    addDeptLayer (nextDeptSet) {
      let features = [];
      nextDeptSet.forEach(item => {
        let fs = gis.getFeature(item, this.yellowIcon)
        features.push(fs);
      });
      gis.getVectorLayerByFs(features)
      gis.mapSetFit(features)

    },
    // 添加区县边界
    addCountyBorder (deptIds) {
      gis.addImageLayer(this.mapGeoServerUrl, this.countyBorderLayerName, deptIds)
    },
    // 添加乡镇边界
    addTownBorder (deptIds) {
      gis.addImageLayer(this.mapGeoServerUrl, this.townBorderLayerName, deptIds)
    },
    // 添加村边界
    addVillageBorder (deptIds) {
      gis.addImageLayer(this.mapGeoServerUrl, this.villageBorderLayerName, deptIds)
    },
    // 获取geoserver的地址
    getGeoServerUrl () {
      // 获取geoserver的地址
      getConfigKey("system.geoServer.url").then(response => {
        this.mapGeoServerUrl = response.msg;
      });
      // 获取区县边界图层名称
      getConfigKey("geoserver.layer.countyBorder").then(response => {
        this.countyBorderLayerName = response.msg;
      });
      // 获取乡镇边界的图层名称
      getConfigKey("geoserver.layer.townBorder").then(response => {
        this.townBorderLayerName = response.msg;
      });
      // 获取村边界的图层名称
      getConfigKey("geoserver.layer.villageBorder").then(response => {
        this.villageBorderLayerName = response.msg;
      });
      // 获取组边界的图层名称
      getConfigKey("geoserver.layer.groupBorder").then(response => {
        this.groupBorderLayerName = response.msg;
      });
    }
  }
};
