
import GisUtils from '@/utils/gis.js';
import {
  fromLonLat
} from 'ol/proj'
import { getPermanentListByDeptId, listPermanent } from "@/api/asset/permanent.js";
import { getInfo } from "@/api/login";
import { getResourceListByDeptId, listResource, getResourceListNew } from "@/api/asset/resource.js";
import Legend from '@/components/legend/index.vue';
import { attachmentList } from "@/api/common/uploadAttachment.js";
import { treeselect, getDept, listDeptExcludeChild } from "@/api/system/dept";
import { getConfigKey } from "@/api/system/config";
import { treeselectByDeptId } from "@/api/system/dept";
import AssetDetails from './asset-details/index.vue';
let gis = null;
export default {
  components: {
    AssetDetails,
    Legend
  },
  data () {
    return {
      showPermanentDetail: {
        show: false,
        id: ''
      },
      yellowIcon: require('./icon/yellow.png'),
      //三务公开请求参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        openType: '1',
        detailedCategoriesType: null,
        villageType: null,
        openItems: null,
        meetingOpenType: null,
        deptId: null,
        isWechat: null,
        status: null,
        translate_dict: 1,
      },

      //零工公开请求参数
      tempWorkerOpenQueryParams: {
        // 分页
        pageNum: 1,
        pageSize: 10,
        // 查询排序
        //orderByColumn: "id",
        //isAsc: "desc",
        bookId: null,
        deptId: null,
        deptName: null,
        openNy: null,
        openYear: null,
        openName: null,
        openFile: null,
        openPic: null,
        remark: null,
        translate_dict: 1,
      },

      //重大事项公开请求参数
      majorEventOpenQueryParams: {
        // 分页
        pageNum: 1,
        pageSize: 10,
        // 查询排序
        //orderByColumn: "id",
        //isAsc: "desc",
        bookId: null,
        deptId: null,
        deptName: null,
        openNy: null,
        openYear: null,
        openDate: null,
        openName: null,
        openFile: null,
        openPic: null,
        content: null,
        remark: null,
        translate_dict: 1,
      },

      //补贴资金管理请求参数
      subsidyFundsQueryParams: {
        // 分页
        pageNum: 1,
        pageSize: 10,
        // 查询排序
        orderByColumn: "id",
        isAsc: "desc",
        year: null,
        areaName: null,
        name: null,
        idCard: null,
        itemName: null,
        releaseDate: null,
        translate_dict: 1,
      },

      //固定资产请求参数
      permanentQueryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        assetType: null,
        operationType: null,
        addType: null,
        useType: null,
        assetStatus: '1',
        translate_dict: 1,
      },

      //资源资产请求参数
      resourceListQueryParams: {
        pageNum: 1,
        pageSize: 10,
        bookId: null,
        deptId: null,
        code: null,
        name: null,
        resourceType: null,
        /*farmingResourceType: null,
        buildResourceType: null,
        unusedResourceType: null,*/
        resourceSort: null,
        totalArea: null,
        location: null,
        east: null,
        west: null,
        south: null,
        north: null,
        sumArea: null,
        groupArea: null,
        groupValue: null,
        rentArea: null,
        rentValue: null,
        rentLessee: null,
        rentStartTime: null,
        rentEndTime: null,
        otherArea: null,
        otherValue: null,
        farmerArea: null,
        circulationArea: null,
        circulationValue: null,
        investmentArea: null,
        investmentValue: null,
        investmentLessee: null,
        investmentStartTime: null,
        investmentEndTime: null,
        status: null,
        translate_dict: 1,
      },
      //合同信息请求参数
      contractionByPermanentQueryParams: {
        pageNum: 1,
        pageSize: 10,
        bookId: null,
        deptId: null,
        code: null,
        name: null,
        assetType: null,
        firstParty: null,
        secondParty: null,
        collectionPay: null,
        contractionSource: null,
        totalAmount: null,
        receivedAmount: null,
        settledAmount: null,
        buildingTime: null,
        startTime: null,
        endTime: null,
        num: null,
        unit: null,
        price: null,
        contractionStatus: null,
        translate_dict: 1,
      },
      addrText: [100],
      deptTreeProps: {
        checkStrictly: true,
      },
      addrOptions: [],
      dialogImageUrl: '',
      dialogVisible: false,
      //资产信息详情弹窗
      showResourceDetail: false,
      mapGeoServerUrl: "",            // geoserver地址
      mapBorder: "",                  // 地图边界
      deptLayer: "",                  // 坐标点图层
      countyBorderLayerName: "",      // 区县边界图层名称
      townBorderLayerName: "",        // 乡镇边界图层名称
      villageBorderLayerName: "",     // 村边界图层名称
      groupBorderLayerName: "",       // 组边界图层名称
      LegendData: [
        {
          iconStyle: {
            background: 'rgba(241,240,6,0.45)',
            borderColor: '#f1f006',
            border: '2px solid #f1f006'
          },
          name: '自用'
        },
        {
          iconStyle: {
            background: 'rgba(195,33,215,0.45)',
            borderColor: '#c321d7',
            border: '2px solid #c321d7'
          },
          name: '闲置'
        },
        {
          iconStyle: {
            background: 'rgba(2,243,62,0.45)',
            borderColor: '#02f33e',
            border: '2px solid #02f33e'
          },
          name: '出租'
        },
        {
          iconStyle: {
            background: 'rgba(237,2,109,0.45)',
            borderColor: '#ed026d',
            border: '2px solid #ed026d'
          },
          name: '其他'
        }
      ],
    };
  },
  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, // 立即执行
    }
  },
  computed: {
  },
  created () {
    this.getGeoServerUrl();
  },
  mounted () {
    getInfo().then(res => {
      treeselectByDeptId({ deptId: res.user.deptId }).then((resp) => {
        this.addrOptions = resp.data;
        // listDeptExcludeChild(res.user.deptId).then((resp) => {
        //   let deptOptions = [res.user.deptId];
        //   resp.data.map(resm => {
        //     if (res.user.parentDeptName == resm.deptName) {
        //       deptOptions.unshift(resm.deptId)
        //       deptOptions.unshift(resm.parentId)
        //     }
        //   })
        //   this.addrText = [100,...deptOptions];
        // });
        this.queryParams.deptId = res.user.deptId;
        this.tempWorkerOpenQueryParams.deptId = res.user.deptId;
        this.majorEventOpenQueryParams.deptId = res.user.deptId;
        this.subsidyFundsQueryParams.deptId = res.user.deptId;
        this.permanentQueryParams.deptId = res.user.deptId;
        this.resourceListQueryParams.deptId = res.user.deptId;
        this.contractionByPermanentQueryParams.deptId = res.user.deptId;
        //列表请求
        this.getAllList();
        // 加载地图
        this.initMap(res.user.deptId);

        // 获取村边界的图层名称
        this.getVillageBorderLayerName();
      });

    })
  },
  methods: {
    commitDept (deptId) {
      this.$store.commit('SET_DEPTID', deptId);
    },
    commitDeptLength (length) {
      this.$store.commit('SET_DEPTIDLENGTH', length);
    },
    commitYear (year) {
      this.$store.commit('SET_YEAR', year);
    },
    openImage (url) {
      //console.log(url)
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    // 获取村边界的图层名称
    getVillageBorderLayerName () {
      getConfigKey("geoserver.layer.villageBorder").then(response => {
        this.villageBorderLayerName = response.msg;
      });
    },
    // 添加区县边界
    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)
    // },
    // // 获取资源列表
    // getResourceList (deptId) {
    //   getResourceListByDeptId(deptId).then(response => {
    //     if (response.data && response.data.length > 0) {
    //       this.addResourceLayer(response.data);
    //     }
    //   });
    // },
    // 获取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;
      });
    },
    selectAddress (value) {
      const deptId = value[value.length - 1];
      this.queryParams.deptId = deptId;
      this.tempWorkerOpenQueryParams.deptId = deptId;
      this.majorEventOpenQueryParams.deptId = deptId;
      this.subsidyFundsQueryParams.deptId = deptId;
      this.permanentQueryParams.deptId = deptId;
      this.resourceListQueryParams.deptId = deptId;
      this.contractionByPermanentQueryParams.deptId = deptId;
      this.infoTotal = undefined;
      this.resourceTotal = undefined;
      this.permanentTotal = undefined;
      this.subsidyFundsTotal = undefined;
      this.majorEventOpenTotal = undefined;
      this.tempWorkerOpenTotal = undefined;
      this.affairsTotal = undefined;
      this.affairsList = [];
      this.tempWorkerOpenList = [];
      this.majorEventOpenList = [];
      this.subsidyFundsList = [];
      this.permanentList = [];
      this.resourceList = [];
      this.infoList = [];
      this.getAllList();

      gis.getMapContainer().removeLayer(this.villageBorder);
      this.villageBorder = '';
      // 添加村边界
      this.addVillageBorder(deptId);
      gis.getMapContainer().removeLayer(this.permanentLayer);
      this.permanentLayer = '';
      // 获取资产列表
      // this.getPermanentList(deptId);
      gis.getMapContainer().removeLayer(this.resourceLayer);
      this.resourceLayer = '';
      // 获取资源列表
      this.getResourceList(deptId);
      let node = this.$refs["cascader"].panel.getNodeByValue(value);
      const dept = node.data;
      const deptData = {
        deptId: dept.id,
        deptName: dept.label,
        lat: dept.lat,
        lng: dept.lng,
        deptLevel: dept.deptLevel,
        orgCode: dept.orgCode
      };
      let deptList = [];
      deptList.push(deptData);
      gis.getMapContainer().removeLayer(this.deptLayer);
      this.deptLayer = '';
      // 添加坐标点图层
      this.addDeptLayer(deptList, 'yellow.png');
      gis.getMapContainer().getView().animate({
        // 只设置需要的属性即可
        center: fromLonLat([dept.lng, dept.lat]), // 中心点
        duration: 500, // 缩放持续时间，默认不需要设置
      });
    },
    // 添加村边界
    addVillageBorder (deptIds) {
      gis.addImageLayer(this.mapGeoServerUrl, this.villageBorderLayerName, deptIds)
    },
    // 加载地图
    initMap (deptId) {
      gis = new GisUtils('map2')
      gis.addTianDiTuLayer()
      gis.addAnnotationLayer()
      // // 获取资源列表
      this.getResourceList(deptId);
      let dept2 = this.addrOptions[0];
      ////console.log(this.addrOptions, 'this.addrOptions');
      if (dept2.deptLevel === '5') {
        // 登录身份为市级领导
        this.userRole = 'cityLeader';
        this.cityId = deptId;
        this.currentDeptLevel = '5';
        // 添加区县边界
        this.addCountyBorder(dept2.children.map(item => item.id));
      } else if (dept2.deptLevel === '4') {
        // 登录身份为县级领导
        this.userRole = 'countyLeader';
        this.countyId = dept2.id;
        this.currentDeptLevel = '4';
        // 添加乡镇边界
        this.addTownBorder(dept2.children.map(item => item.id));
        gis.getView().setZoom(11);
      } else if (dept2.deptLevel === '3') {
        // 登录身份为镇级领导
        this.userRole = 'townLeader';
        this.townId = dept2.id;
        this.currentDeptLevel = '3';
        // 添加村边界
        this.addVillageBorder(dept2.children.map(item => item.id));
        gis.getView().setZoom(13);
      }
      // 添加坐标点图层
      if (dept2.children) {
        this.addDeptLayer(dept2.children);
      }
      gis.getMapContainer().on("click", (evt) => {
        let feature = gis.getMapContainer().forEachFeatureAtPixel(
          evt.pixel,
          (feature) => feature
        );
        if (feature) {
          // 镇级：加载村级坐标点
          if (feature.get('deptLevel') === '3') {
            gis.getMapContainer().getView().animate({
              center: fromLonLat([feature.get('lng'), feature.get('lat')]), // 中心点
              zoom: 12, // 缩放级别
              rotation: undefined, // 缩放完成view视图旋转弧度
              duration: 1000, // 缩放持续时间，默认不需要设置
            });
          } else {
            this.listDialogHidden('detail');
            this.openResourceDialog(feature.values_.detail);
          }
        }
      });

      // 缩小地图，重新加载页面
      gis.getMapContainer().on("moveend", (evt) => {
        const zoom = gis.getMapContainer().getView().getZoom();
        if (this.villagePointLayer && zoom < 10.5) {
          gis.getMapContainer().removeLayer(this.villagePointLayer);
          this.villagePointLayer = "";
        }
      });
    },
    listDialogHidden (type) {
      if (type == 'detail') {
        //合同信息详情弹窗
        this.showInfoDetail = false;
        //资源信息详情弹窗
        this.showResourceDetail = false;
        //资产信息详情弹窗
        this.showPermanentDetail.show = false;
        //农业补贴详情弹窗
        this.showSubsidyFundsDetail = false;
        //重大事项详情弹窗
        this.showMajorEventDetail = false;
        //零工公开详情弹窗
        this.showTempWorkerDetail = false;
        //三务公开详情弹窗
        this.showAffairsDetail = false;
      } else {
        //三务公开列表弹窗
        this.showAffairs = false;
        //零工公开列表弹窗
        this.showTempWorker = false;
        //重大事项列表弹窗
        this.showMajorEvent = false;
        //农业补贴列表弹窗
        this.showSubsidyFunds = false;
        //资产信息列表弹窗
        this.showPermanent = false;
        //资源信息列表弹窗
        this.showResource = false;
        //合同信息列表弹窗
        this.showInfo = false;
        //合同信息详情弹窗
        this.showInfoDetail = false;
        //资源信息详情弹窗
        this.showResourceDetail = false;
        //资产信息详情弹窗
        this.showPermanentDetail.show = false;
        //农业补贴详情弹窗
        this.showSubsidyFundsDetail = false;
        //重大事项详情弹窗
        this.showMajorEventDetail = false;
        //零工公开详情弹窗
        this.showTempWorkerDetail = false;
        //三务公开详情弹窗
        this.showAffairsDetail = false;
      }

    },
    openResourceDialog (data) {
      let id = data.id;
      this.showPermanentDetail = {
        id,
        show: true
      }
    },
    // 创建矢量数据源
    addDeptLayer (nextDeptSet, locationIcon) {
      ////console.log('nextDeptSet', nextDeptSet);
      let features = [];
      nextDeptSet.forEach(item => {
        let fs = gis.getFeature(item, this.yellowIcon)
        features.push(fs);
      });
      gis.getVectorLayerByFs(features)
      gis.mapSetFit(features)
    },
    // 获取资源列表
    getResourceList (deptId) {
      getResourceListNew({deptId:deptId}).then(response => {
        if (response.rows && response.rows.length > 0) {
          this.addResourceLayer(response.rows);
        }
      });
    },
    // 添加资源图层
    addResourceLayer (resourceList) {
      let features = [];
      resourceList.forEach(item => {
        if (item.theGeom != null && item.theGeom !== '') {
          const { useType } = item
          let color = this.LegendData[useType - 1 + '']
          //console.log(color)
          if (color){
            let fs = gis.getFeature3(item, color.iconStyle.background, color.iconStyle.borderColor)
            features.push(fs);
          }
        }
      });
      gis.getVectorLayerByFs(features)
      gis.mapSetFit(features)
    },
    // 获取资产列表
    getPermanentList (deptId) {
      getPermanentListByDeptId(deptId).then(response => {
        if (response.data && response.data.length > 0) {
          this.addPermanentLayer(response.data);
        }
      });
    },
    getAllList () {
      //三务公开
      // this.getList(null);
      // //零工公开
      // this.getTempWorkerOpenList();
      // //重大事项公开
      // this.getMajorEventOpenList();
      // //补贴资金管理
      // this.getSubsidyFundsList();
      // //固定资产
      // this.getPermanentListList();
      // //资源资产
      // this.getResourceListList();
      // //合同信息
      // this.getContractionByPermanentList();
      // //资金情况
      // this.getFundAndBankAmountByDeptIdArray();
    },
  }
};
