<template>
  <div>
    <ul class="importDiv" v-if="!resultDialog && !txtResultDialog && !dealDialog">
      <li>
        <el-upload class="avatar-uploader" action="#" accept=".txt" :auto-upload="false" :show-file-list="false"
          :on-change="txtFileChange">
          <!-- <el-button size="small" type="primary">点击上传</el-button>-->
          <i class="iconfont iconshangchuan"></i>
          <div class="title">TXT文本格式</div>
          <div class="templateDowload">
            <a href="#" @click.stop="downloadFile('./fileTemplate/txttemplet.txt', 'txttemplet.txt')">TXT模板下载</a>
          </div>
        </el-upload>
      </li>
      <li>
        <el-upload class="avatar-uploader" action="/api/tx/shpUtils/readShp" accept=".zip" :show-file-list="false"
          :on-success="shpFileSuccess">
          <!--<el-button size="small" type="primary">点击上传</el-button>-->
          <i class="iconfont iconshangchuan"></i>
          <div class="title">ESRI Shape文件格式</div>
        </el-upload>
      </li>
      <li>
        <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" accept=".dwg,.dxf"
          :show-file-list="false" :on-success="cadFileSuccess">
          <!-- <el-button size="small" type="primary">点击上传</el-button>-->
          <i class="iconfont iconshangchuan"></i>
          <div class="title">CAD文件</div>
        </el-upload>
      </li>
      <li>
        <el-upload class="avatar-uploader" action="/api/tx/excelGeo/readExcel" accept=".xls,.xlsx"
          :show-file-list="false" :on-success="excelFileSuccess">
          <!--<el-button size="small" type="primary">点击上传</el-button>-->
          <i class="iconfont iconshangchuan"></i>
          <div class="title">Excel文件格式</div>
          <div class="templateDowload">
            <a href="#"
              @click.stop="downloadFile('./fileTemplate/exceltemplet.xlsx', 'exceltemplet.xlsx')">Excel模板下载</a>
          </div>
        </el-upload>
      </li>
    </ul>
    <div v-if="resultDialog">
      <el-form :model="zdForm" ref="zdCheckForm" label-width="100px" size="small" @submit.native.prevent
        class="demo-ruleForm">
        <el-form-item label="宗地" prop="zdBsm" :rules="[
          { required: true, message: '请选择宗地', trigger: 'change' },
        ]">
          <el-select v-model="zdForm.zdBsm" filterable placeholder="请选择" @change="zdChange">
            <el-option v-for="item in resultData" :key="item.objectid" :label="item.XMMC" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('zdCheckForm')">导入</el-button>
          <el-button @click="cancel('zdCheckForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="txtResultDialog">
      <el-form :model="txtZd" ref="txtZdForm" label-width="100px" size="small" @submit.native.prevent
        class="demo-ruleForm">
        <el-form-item label="地块名称" prop="name" :rules="[
          { required: true, message: '请选择地块', trigger: 'change' },
        ]">
          <el-select v-model="txtZd.name" filterable placeholder="请选择" @change="txtChange">
            <el-option v-for="(item, index) in txtResult" :key="index" :label="item.attributes.name"
              :value="item.attributes.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitTxtForm('txtZdForm')">导入</el-button>
          <el-button @click="cancelTxtForm('txtZdForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="dealDialog">
      <el-form :model="dealForm" ref="dealForm" label-width="100px" size="small" @submit.native.prevent
        class="demo-ruleForm">
        <el-form-item label="处理方法" prop="method" :rules="[
          { required: true, message: '请选择', trigger: 'change' },
        ]">
          <el-select v-model="dealForm.method" filterable placeholder="请选择">
            <el-option v-for="(item, index) in dealMethods" :key="index" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitDealForm('dealForm')">确定</el-button>
          <el-button @click="cancelDealForm('dealForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import geoUtils from "@components/lineTree/tx/js/geoUtils";
import featureUpdate from "@libs/map/featureUpdate";
// import { addjzd, addjzx } from "@/api/zd"
export default {
  props: {
    propertyInfo: {
      type: Object,
      default: null
    },
    geoInfo: {
      type: Object,
      default: null
    },
    timeLine: {
      type: Number,
      default: null
    }
  },
  mixins: [geoUtils, featureUpdate],
  data () {
    return {
      resultData: [],
      resultDialog: false,
      zdForm: {
        zdBsm: ""
      },
      currentClickZd: null,
      txtResult: [],
      txtResultDialog: null,
      txtZd: {
        name: ""
      },
      overResults: [],//与导入宗地重叠的地块
      currntDealGraphic: null,
      dealMethods: [{
        label: "不做处理",
        value: "1"
      }, {
        label: "删除叠加部分",
        value: "2"
      }, {
        label: "删除已重叠部分",
        value: "3"
      }, {
        label: "删除原图形",
        value: "4"
      }],
      dealDialog: false,
      dealForm: {
        method: ""
      }
    }
  },
  watch: {
    timeLine (newValue, oldValue) {
      this.resultDialog = false;
      this.txtResultDialog = false;
      this.dealDialog = false;
    }
  },
  methods: {
    txtFileChange (file, fileList) {
      var self = this;
      var fileReader = new FileReader();
      fileReader.readAsText(file.raw);
      fileReader.onload = function (res) {
        var content = this.result;
        if (!content || content.length == 0) {
          self.$message.warning("文件内容为空!!!");
          return;
        }
        self.analysisTextFile(content);
      }
    },
    analysisTextFile (content) {
      var index = content.indexOf("[地块坐标]"),
        geoInfos = content.substr(index),
        geoList = geoInfos.split("\n");
      if (geoList.length < 1) {
        this.$message.warning("文本内容格式有误,请效验文本内容格式!!!");
        return;
      }
      //this.$emit("closeImportDialog");
      var features = [], attributes = {}, points = [], j = 1;
      for (var i = 1; i < geoList.length; i++) {
        var rowData = geoList[i];
        if ((rowData.indexOf("J") != -1 && rowData.indexOf("J") == 0) || (rowData.indexOf("j") != -1 && rowData.indexOf("j") == 0)) {
          //解析坐标点信息
          var pointInfo = rowData.split(",");
          var point = [parseFloat(pointInfo[2]), parseFloat(pointInfo[3])];
          points.push(point);
        } else {
          if (points.length > 0) {
            var graphic = {
              attributes: JSON.parse(JSON.stringify(attributes)),
              geometry: {
                rings: [points]
              }
            }
            features.push(graphic);
          }
          //新建一个信息 坐标名称 类型
          attributes = {};
          points = []
          var info = rowData.split(",");
          if (info[3] || info[3] == 'null') {
            attributes.name = '地块' + j;
            j++
          } else {
            attributes.name = info[3];
          }
        }
      }
      if (points.length > 0) {
        var graphic = {
          attributes: JSON.parse(JSON.stringify(attributes)),
          geometry: {
            rings: [[points.concat()]]
          }
        }
        features.push(graphic);
      }
      //新建一个信息 坐标名称 类型
      attributes = {};
      points = []
      this.txtResult = features;
      this.txtZd.name = "";
      this.txtResultDialog = true;
    },
    shpFileSuccess (response, file, fileList) {
      var self = this;
      if (response.success) {
        this.resultData = response.result;
        this.resultDialog = true;
      } else {
        this.$message.warning(response.message);
      }
    },
    cadFileSuccess (response, file, fileList) {

    },
    excelFileSuccess (response, file, fileList) {
      var self = this;
      if (response.success) {
        var result = response.result;
        var points = [];
        for (var i = 0; i < result.length; i++) {
          var point = [];
          point[0] = parseFloat(result[i].x);
          point[1] = parseFloat(result[i].y);
          points.push(point);
        }
        var wkt = "PROJCS[\"XADFZBX\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";
        var geometry = {
          rings: [points],
          spatialReference: {
            wkt: wkt
          },
          type: "polygon"
        }
        var graphic = {
          attributes: null,
          geometry: geometry
        }
        self.checkGeo(graphic);
      } else {
        this.$message.warning(response.message);
      }
    },
    //文本文档导入
    submitTxtForm (formName) {
      var self = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var wkt = "PROJCS[\"XADFZBX\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";
          var graphics = self.txtResult.filter(item => {
            return item.attributes.name == self.txtZd.name;
          })
          var graphic = graphics[0];
          graphic.geometry.type = "polygon";
          graphic.geometry.spatialReference = {
            wkt: wkt
          }
          self.checkGeo(graphic);
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    txtChange (value) {
      var wkt = "PROJCS[\"XADFZBX\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";
      var graphics = this.txtResult.filter(item => {
        return item.attributes.name == value;
      })
      var graphic = graphics[0];
      graphic.geometry.type = "polygon";
      graphic.geometry.spatialReference = {
        wkt: wkt
      }
      this.addOverLayer(graphic.geometry, []);
    },
    //校验空间完整性
    checkGeo (graphic) {
      var self = this;
      //校验完整性 直接调用空间方法 提交空间表
      self.geoJoint(graphic.geometry, function (isJoint, message) {
        if (isJoint) {
          self.$message.warning(message)
          return;
        } else {
          var type = self.propertyInfo.type;
          if (type == 'zd') {
            //重叠分析
            self.zdOverAnalys(self.propertyInfo.zdbsm, graphic, function (flag, results) {
              if (flag) {
                self.$message.warning("导入的宗地与其他宗地有重叠,请处理!!");
                self.dealOverData(results, graphic);
              } else {
                self.saveZd(graphic);
              }
            });
          } else {
            self.zrzOverAnalys(self.propertyInfo.bsm, graphic, function (flag, mes) {
              if (flag) {
                self.$message.warning(mes);
                return;
              } else {
                self.saveZRZ(graphic);
              }
            });
          }
        }
      });
    },
    //选择处理方式
    submitDealForm (formName) {
      var self = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //选择处理方式
          var value = self.dealForm.method;
          self.currntDealGraphic.attributes = {};
          switch (value) {
            case '1': self.currntDealGraphic.attributes.BGZT = 1; self.saveZd(self.currntDealGraphic); break;
            case "2": self.getDifference(self.currntDealGraphic, self.overResults, self.delOverGeo); break;
            case "3": self.getResultsDif(self.overResults, self.currntDealGraphic, self.delOtherGeo, true); break;
            case "4": self.getResultsDif(self.overResults, self.currntDealGraphic, self.delOtherGeo, false); break;
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    //裁剪自己在保存
    delOverGeo (geometry) {
      if (!this.currntDealGraphic.attributes) {
        this.currntDealGraphic.attributes = {};
      }
      this.currntDealGraphic.attributes.BGZT = 2;
      if (geometry == null) {
        this.$message.warning("完全重叠,已删除图形信息!!!")
        this.currntDealGraphic.geometry = geometry;
      }
      this.saveZd(this.currntDealGraphic);
    },
    //裁剪别的在保存
    delOtherGeo (results) {
      //执行编辑操作
      var layer = this.getLayerByName("ZDJBXX");
      var featureUrl = layer.layerUrl.replace("MapServer", "FeatureServer");
      featureUrl += "/" + layer.id;
      this.updateGraphic(featureUrl, results);
      this.saveZd(this.currntDealGraphic);
    },
    //下载文档模板
    downloadFile (url, fileName) {
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    //导入
    submitForm (formName) {
      //校验完整性 直接调用空间方法 提交空间表
      var self = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var geometry = self.parseWktToArc(self.currentClickZd.wkt);
          geometry.type = "polygon";
          var wkt = "PROJCS[\"XADFZBX\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";
          geometry.spatialReference = {
            wkt: wkt
          }
          var graphic = {
            attributes: self.currentClickZd,
            geometry: geometry
          }
          self.checkGeo(graphic);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    dealOverData (results, graphic) {
      this.overResults = results;
      this.currntDealGraphic = graphic;
      this.resultDialog = false;
      this.txtResultDialog = false;
      this.dealDialog = true;
    },
    saveZd (graphic) {
      var self = this;
      var points = null, lines = null,
        layer = self.getLayerByName("ZDJBXX");
      var featureUrl = layer.layerUrl.replace("MapServer", "FeatureServer");
      featureUrl += "/" + layer.id;
      if (self.geoInfo) {
        //替换 生成图像 高亮
        if (graphic.attributes && graphic.attributes.BGZT) {
          self.geoInfo.attributes.BGZT = graphic.attributes.BGZT;
        }
        self.geoInfo.attributes.BSM = this.propertyInfo.zdbsm;
        self.geoInfo.attributes.ZDDM = this.propertyInfo.zddm;
        self.geoInfo.attributes.XMMC = this.propertyInfo.mc;
        graphic.attributes = self.geoInfo.attributes;
        self.updateGraphic(featureUrl, graphic, function (res) {
          //保存成功之后生成界址点 界址线
          //生成坐标点
          //跳转至map界面updateResults
          var updResult = res.updateFeatureResults[0];
          if (updResult.objectId) {
            var OBJECTID = updResult.objectId;
            if (graphic.geometry) {
              points = self.craetJZPoint(graphic);
              self.savejzd(points)
              //生成边框线
              self.createJZLine(graphic, function (res) {
                lines = res;
                self.saveJzx(lines);
              });
            }
            self.$message.success("保存成功!!!");
            self.goMap();
          }
        });
      } else {
        //生成图像  保存
        var attributes = {
          BSM: this.propertyInfo.zdbsm,
          ZDDM: this.propertyInfo.zddm,
          XMMC: this.propertyInfo.mc
        };
        if (graphic.attributes && graphic.attributes.BGZT) {
          attributes.BGZT = graphic.attributes.BGZT;
        }
        graphic.attributes = attributes;
        self.addGraphic(featureUrl, graphic, function (res) {
          var addRresult = res.addFeatureResults[0];
          if (addRresult.objectId) {
            var OBJECTID = addRresult.objectId;
            if (graphic.geometry) {
              points = self.craetJZPoint(graphic);
              self.savejzd(points)
              //生成边框线
              self.createJZLine(graphic, function (res) {
                lines = res;
                self.saveJzx(lines);
              });
            }
            self.$message.success("保存成功!!!");
            self.goMap();
          }
        });
      }
    },
    savejzd (points) {
      var savePoints = []
      for (var i = 0; i < points.length; i++) {
        var obj = {
          glbsm: this.propertyInfo.zdbsm,
          jzdh: points[i].jzdh,
          sxh: points[i].sxh,
          xzbz: points[i].x,
          yzbz: points[i].y,
          jblx: "",
          jzdlx: ""
        }
        savePoints.push(obj);
      }
      //保存矢量数据表
      // addjzd(savePoints).then(res => {
      //   if (res.succcess) {
      //     console.log("界址点保存成成功!!!");
      //   }
      // });
      //保存空间数据

    },
    saveJzx (lines) {
      var jzxLines = [];
      for (var i = 0; i < lines.length; i++) {
        var obj = {
          glbsm: this.propertyInfo.zdbsm,
          qsd: lines[i].startPoint,
          zzd: lines[i].endPoint,
          jzjj: lines[i].distance,
          qdh: lines[i].qdh,
          zdh: lines[i].zdh,
          jzxlx: "",
          jzxwz: "",
          jxxz: "",
          sm: ""
        }
        jzxLines.push(obj);
      }
      //保存矢量数据表
      // addjzx(jzxLines).then(res => {
      //   if (res.success) {
      //     //触发查询界址线
      //     console.log("界址线保存成功!!!!!");
      //   }
      // });
      //保存空间数据表
    },
    saveZRZ (graphic) {
      var self = this;
      var layer = null;
      layer = self.getLayerByName("ZRZ");
      var featureUrl = layer.layerUrl.replace("MapServer", "FeatureServer");
      featureUrl += "/" + layer.id;
      if (self.geoInfo) {
        self.geoInfo.BSM = self.propertyInfo.bsm;
        graphic.attributes = self.geoInfo.attributes;
        //替换 生成图像 高亮
        self.updateGraphic(featureUrl, graphic, function (res) {
          var addRresult = res.updateFeatureResults[0];
          if (addRresult.objectId) {
            self.$message.success("保存成功!!!");
            self.goMap();
          }
        });
      } else {
        var attributes = {
          BSM: this.propertyInfo.bsm,
          XMMC: this.propertyInfo.xmmc
        }
        graphic.attributes = attributes;
        //生成图像  保存
        self.addGraphic(featureUrl, graphic, function (res) {
          var addRresult = res.addFeatureResults[0];
          if (addRresult.objectId) {
            self.$message.success("保存成功!!!");
            self.goMap();
          }
        });
      }
    },
    //操作成功不需要跳转地图 (直接定位新导入的图形)
    goMap () {
      var bsm = "", type = this.propertyInfo.type;
      if (type == "zd") {
        bsm = this.propertyInfo.zdbsm;
      } else {
        bsm = this.propertyInfo.bsm;
      }
      this.resultDialog = false;
      this.txtResultDialog = false;
      this.dealDialog = false;
      this.$emit("closeImportDialog");
      //TODO 定位当前新导入的图形
      this.addGeoByBsm(bsm, type, "testMap");
    },
    //取消
    cancel () {
      this.zdForm.zdBsm = "";
      this.currentClickZd = null;
      this.resultDialog = false;
      //  清空当前图层上显示的图形
      this.clearOverLayer();
    },
    //取消文本选择的弹出框
    cancelTxtForm () {
      this.txtZd.name = "";
      this.txtResultDialog = false;
      //  清空当前图层上显示的图形
      this.clearOverLayer();
    },
    //取消导入处理的结果
    cancelDealForm () {
      this.dealForm.method = "";
      this.dealDialog = false;
      this.overResults = [];
      //  清空当前图层上显示的图形
      this.clearOverLayer();
    },
    //宗地选择发生改变
    zdChange (value) {
      this.zdForm.zdBsm = value.XMMC;
      this.currentClickZd = value;
      var geometry = this.parseWktToArc(this.currentClickZd.wkt);
      geometry.type = "polygon";
      var wkt = "PROJCS[\"XADFZBX\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";
      geometry.spatialReference = {
        wkt: wkt
      }
      this.addOverLayer(geometry, []);
    }
  }
}
</script>
<style scoped lang="scss">
.importDiv {
  display: flex;
  justify-content: center;
  align-content: center;

  li {
    margin: 5px;
    width: 50%;

    .title {
      line-height: 1;
      margin-top: -57px;
      font-size: 14px;
    }

    .templateDowload {
      line-height: 1;
      margin-top: 7px;

      a {
        color: #409eff;
      }
    }
  }
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 178px;
  line-height: 178px;
}

/deep/ .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

/deep/ .iconfont {
  font-size: 20px;
  color: #8c939d;
  width: 100%;
  text-align: center;
}
</style>