
import GisUtils from '@/utils/gis.js';
import {
  fromLonLat
} from 'ol/proj'
import { treeselect, getDept, listDeptExcludeChild } from "@/api/system/dept";
import { getInfo } from "@/api/login";
import { getConfigKey } from "@/api/system/config";
import { getPermanentListByDeptId, listPermanent } from "@/api/asset/permanent.js";
import { getResourceListByDeptId, listResource } from "@/api/asset/resource.js";
import { attachmentList } from "@/api/common/uploadAttachment.js";
let gis = null;
export default {
  components: {
  },
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      showInfoDetail: false,
      addrOptions: [],
      addrText: [100,],
      deptTreeProps: {
        checkStrictly: true,
      },
      yellowIcon: require('./icon/yellow.png'),
      zcIcon: require('./icon/zc_icon.png'),
      mapGeoServerUrl: "",
      villageBorderLayerName: "",
      headerTitle: '',
      assetTypeOptions: [],
      unitOptions: [],
      resourceTypeOptions: [],

      //三务公开请求参数
      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,
      },
    };
  },
  computed: {
  },
  created () {
  },
  mounted () {
    treeselect().then((resp) => this.addrOptions = resp.data);
    this.getDicts("asset_type").then((response) => {
      this.assetTypeOptions = response.data;
    });
    this.getDicts("fixed_assets_unit").then((response) => {
      this.unitOptions = response.data;
    });
    this.getDicts("resource_type").then(response => {
      this.resourceTypeOptions = response.data;
    });
    getInfo().then(res => {
      this.headerTitle = res.user.deptName + '阳光村务一张图';
      listDeptExcludeChild(res.user.loginDeptId).then((resp) => {
        let deptOptions = [res.user.loginDeptId];
        resp.data.map(resm => {
          if (res.user.parentDeptName == resm.deptName) {
            deptOptions.unshift(resm.deptId)
            deptOptions.unshift(resm.parentId)
          }
        })
        this.addrText = deptOptions;
      });
      this.queryParams.deptId = res.user.loginDeptId;
      this.tempWorkerOpenQueryParams.deptId = res.user.loginDeptId;
      this.majorEventOpenQueryParams.deptId = res.user.loginDeptId;
      this.subsidyFundsQueryParams.deptId = res.user.loginDeptId;
      this.permanentQueryParams.deptId = res.user.loginDeptId;
      this.resourceListQueryParams.deptId = res.user.loginDeptId;
      this.contractionByPermanentQueryParams.deptId = res.user.loginDeptId;
      //列表请求
      this.getAllList();
      // 加载地图
      this.initMap(res.user.loginDeptId);
      // 获取geoserver的地址
      this.getGeoServerUrl();
      // 获取村边界的图层名称
      this.getVillageBorderLayerName();
    })
  },
  methods: {
    openImage (url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    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: ol.proj.fromLonLat([dept.lng, dept.lat]), // 中心点
        duration: 500, // 缩放持续时间，默认不需要设置
      });
    },
    // 获取村边界的图层名称
    getVillageBorderLayerName () {
      getConfigKey("geoserver.layer.villageBorder").then(response => {
        this.villageBorderLayerName = response.msg;
      });
    },
    // 获取资产列表
    getPermanentList (deptId) {
      getPermanentListByDeptId(deptId).then(response => {
        if (response.data && response.data.length > 0) {
          this.addPermanentLayer(response.data);
        }
      });
    },
    // 添加资产图层
    addPermanentLayer (permanentList) {
      let features = [];
      permanentList.forEach(item => {
        if (item.theGeom != null && item.theGeom !== '') {
          let fs = gis.getFeature2(item, this.zcIcon)
          features.push(fs);
        }
      });


      gis.getVectorLayerByFs(features)
      gis.mapSetFit(features)
    },
    // 添加村边界
    addVillageBorder (deptId) {
      gis.addImageLayer(this.mapGeoServerUrl, this.villageBorderLayerName, deptId)
    },
    // 获取geoserver的地址
    getGeoServerUrl () {
      getConfigKey("system.geoServer.url").then(response => {
        this.mapGeoServerUrl = response.msg;
      });
    },
    // 创建矢量数据源
    addDeptLayer (nextDeptSet) {
      let features = [];
      nextDeptSet.forEach(item => {
        let fs = gis.getFeature(item, this.yellowIcon)
        features.push(fs);
      });


      gis.getVectorLayerByFs(features)
      gis.mapSetFit(features)
    },
    openResourceDialog (data) {
      data.fileList = [];
      let parmasData = {
        tableId: data.id,
        tableName: 't_asset_resource',
        bizPath: 'asset',
      };
      attachmentList(parmasData).then((res) => {
        if (res.code == 200) {
          let UattachmentList = res.rows;
          for (let i = 0; i < UattachmentList.length; i++) {
            let fileName = UattachmentList[i].fileName;
            let subIndex = fileName.lastIndexOf(".");
            let ext = fileName.substring(subIndex + 1, fileName.length);
            let urls = "";
            let type = "";
            if (ext == "xlsx" || ext == "xls") {
              urls = require("@/assets/images/icon_excel.jpg");
              type = 'excel';
            } else if (ext == "doc" || ext == "docx") {
              urls = require("@/assets/images/icon_word.jpg");
              type = 'word';
            } else if (ext == "pdf") {
              urls = require("@/assets/images/icon_pdf.jpg");
              type = 'pdf';
            } else if (ext == "zip") {
              urls = require("@/assets/images/icon_zip.jpg");
              type = 'zip';
            } else {
              urls = '/api' + UattachmentList[i].fileUrl;
              type = 'image';
            }
            data.fileList.push({
              url: urls,
              urlApi: '/api' + UattachmentList[i].fileUrl,
              type: type
            })
          }
          this.showResourceDetail = true;
          this.resourceDetail = data;
        }
      });
    },
    listDialogHidden (type) {
      if (type == 'detail') {
        //合同信息详情弹窗
        this.showInfoDetail = false;
        //资源信息详情弹窗
        this.showResourceDetail = false;
        //资产信息详情弹窗
        this.showPermanentDetail = 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 = false;
        //农业补贴详情弹窗
        this.showSubsidyFundsDetail = false;
        //重大事项详情弹窗
        this.showMajorEventDetail = false;
        //零工公开详情弹窗
        this.showTempWorkerDetail = false;
        //三务公开详情弹窗
        this.showAffairsDetail = false;
      }

    },
    openPermanentDialog (data) {
      data.fileList = [];
      let parmasData = {
        tableId: data.id,
        tableName: 't_asset_permanent',
        bizPath: 'asset',
      };
      attachmentList(parmasData).then((res) => {
        if (res.code == 200) {
          let UattachmentList = res.rows;
          for (let i = 0; i < UattachmentList.length; i++) {
            let fileName = UattachmentList[i].fileName;
            let subIndex = fileName.lastIndexOf(".");
            let ext = fileName.substring(subIndex + 1, fileName.length);
            let urls = "";
            let type = "";
            if (ext == "xlsx" || ext == "xls") {
              urls = require("@/assets/images/icon_excel.jpg");
              type = 'excel';
            } else if (ext == "doc" || ext == "docx") {
              urls = require("@/assets/images/icon_word.jpg");
              type = 'word';
            } else if (ext == "pdf") {
              urls = require("@/assets/images/icon_pdf.jpg");
              type = 'pdf';
            } else if (ext == "zip") {
              urls = require("@/assets/images/icon_zip.jpg");
              type = 'zip';
            } else {
              urls = '/api' + UattachmentList[i].fileUrl;
              type = 'image';
            }
            data.fileList.push({
              url: urls,
              urlApi: '/api' + UattachmentList[i].fileUrl,
              type: type
            })
          }
          this.showPermanentDetail = true;
          this.permanentDetail = data;
        }
      });
    },
    // 加载地图
    initMap (deptId) {
      getDept(deptId).then(response => {
        const dept = response.data;
        let mapCenterLocation;
        // 定义地图中心坐标
        if (dept.lng && dept.lat) {
          mapCenterLocation = [dept.lng, dept.lat];
        } else {
          mapCenterLocation = [116.391458, 39.902377];
        }
        gis = new GisUtils('map2')
        gis.addTianDiTuLayer()
        gis.addAnnotationLayer()
        // 添加村边界
        this.addVillageBorder(deptId);
        let deptList = [];
        deptList.push(dept);
        // 添加坐标点图层
        this.addDeptLayer(deptList);
        // // 获取资产列表
        this.getPermanentList(deptId);
        // // 获取资源列表
        this.getResourceList(deptId);

        var that = this;
        //点击查询详细信息
        gis.getMapContainer().on("singleclick", function (evt) {
          let feature = gis.getMapContainer().forEachFeatureAtPixel(
            evt.pixel,
            (feature) => feature
          );
          if (feature) {
            var ifConsole = feature.values_.level;
            console.log(ifConsole);
            if (ifConsole == "permanent") {
              that.listDialogHidden('detail');
              that.openPermanentDialog(feature.values_.detail);
            } else {
              that.listDialogHidden('detail');
              that.openResourceDialog(feature.values_.detail);
            }
          }
        });
      });
    },
    // 获取资源列表
    getResourceList (deptId) {
      getResourceListByDeptId(deptId).then(response => {
        if (response.data && response.data.length > 0) {
          this.addResourceLayer(response.data);
        }
      });
    },
    // 添加资源图层
    addResourceLayer (resourceList) {
      let features = [];
      resourceList.forEach(item => {
        if (item.theGeom != null && item.theGeom !== '') {
          let fs = gis.getFeature3(item)
          features.push(fs);
        }

      });


      gis.getVectorLayerByFs(features)
      gis.mapSetFit(features)
    },
    getAllList () {
      //三务公开
      // this.getList(null);
      // //零工公开
      // this.getTempWorkerOpenList();
      // //重大事项公开
      // this.getMajorEventOpenList();
      // //补贴资金管理
      // this.getSubsidyFundsList();
      // //固定资产
      // this.getPermanentListList();
      // //资源资产
      // this.getResourceListList();
      // //合同信息
      // this.getContractionByPermanentList();
      // //资金情况
      // this.getFundAndBankAmountByDeptIdArray();
    },
  }
};
