<template>
  <div>
    <el-dialog
      :class="'ContentDetail'"
      v-model="isDialogShow"
      width="650px"
      top="7%"
      title="内容编辑"
      :close-on-click-modal="false"
      :before-close="dialogBeforeClose"
      style="overflow: auto; height: 700px"
    >
      <el-form
        :model="dataForm"
        :rules="dataFormRules"
        label-width="150px"
        ref="dataForm"
      >
        <el-form-item :label="'ID(内置)'" v-show="false">
          <el-input v-model="dataForm.id" />
        </el-form-item>
        <el-form-item :label="'标题(内置)'" prop="title" :rules="dataFormRules.required">
          <el-input
            v-model="dataForm.title"
            :placeholder="'请输入标题'"
            :disabled="isView"
          />
        </el-form-item>
        <el-form-item
          :label="'描述(内置)'"
          prop="content"
          :rules="dataFormRules.required"
        >
          <el-input
            v-model="dataForm.content"
            :placeholder="'请输入描述'"
            :disabled="isView"
          />
        </el-form-item>
        <!-- :label="formItem.alias + ':'" -->
        <el-form-item
          v-for="formItem in modelFieldList"
          :key="formItem.name"
          :prop="formItem.name"
          :rules="formItem.must ? dataFormRules.required : false"
        >
          <template #label>
            <!-- <span title="这里是额外的信息">用户名</span> -->
            <span class="el-form-item-label" :title="formItem.alias"
              >{{ formItem.alias }}:</span
            >
          </template>

          <!--文本内容-->
          <el-input
            v-if="['varchar', 'content', 'text'].indexOf(formItem.frontType) > -1"
            v-model="dataForm[formItem.name]"
            :type="formItem.name == 'password' ? 'password' : 'text'"
            :placeholder="formItem.describe"
            :disabled="isView"
          />
          <!--日期时间-->
          <span v-else-if="['date_time'].indexOf(formItem.frontType) > -1">
            <el-date-picker
              v-if="!isView"
              type="datetime"
              v-model="dataForm[formItem.name]"
              value-format="x"
              :placeholder="formItem.describe"
            />
            <span v-else>{{
              dataForm[formItem.name] == "" ||
              dataForm[formItem.name] == undefined ||
              dataForm[formItem.name] == null
                ? "无数据"
                : handleDateFormat(dataForm[formItem.name], formItem.dateType)
            }}</span>
          </span>

          <!--整数类型-->
          <el-input-number
            v-if="['int_num'].indexOf(formItem.frontType) > -1"
            style="width: 80%"
            v-model="dataForm[formItem.name]"
            :placeholder="formItem.describe"
            :disabled="isView"
          />
          <!--浮点类型-->
          <el-input-number
            v-if="['float_num'].indexOf(formItem.frontType) > -1"
            :min="formItem.min"
            :max="formItem.max"
            style="width: 80%"
            v-model="dataForm[formItem.name]"
            :placeholder="formItem.describe"
            :disabled="isView"
          />
          <!--布尔类型-->
          <span v-if="['boolean'].indexOf(formItem.frontType) > -1">
            <el-switch
              :active-text="'true'"
              :inactive-text="'false'"
              v-model="dataForm[formItem.name]"
              :disabled="isView"
            />
            <span
              style="
                font-size: 7px;
                color: #606266;
                display: inline-block;
                margin-left: 8px;
              "
            >
              [{{ formItem.describe }}]
            </span>
          </span>

          <!--单选类型-->
          <el-radio-group
            v-if="['check'].indexOf(formItem.frontType) > -1"
            v-model="dataForm[formItem.name]"
            :disabled="isView"
          >
            <el-radio
              v-for="itemItem in itemLists[formItem.extendId]"
              :key="itemItem.index"
              :label="itemItem.index"
            >
              {{ itemItem.name }}
            </el-radio>
          </el-radio-group>
          <!--多选类型-->
          <el-checkbox-group
            v-if="['multiple_check'].indexOf(formItem.frontType) > -1"
            v-model="dataForm[formItem.name]"
            :disabled="isView"
          >
            <el-checkbox
              v-for="item in itemLists[formItem.extendId]"
              :key="item.index"
              :label="item.index"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
          <!--类别-->
          <el-select
            clearable
            v-if="['select'].indexOf(formItem.frontType) > -1"
            v-model="dataForm[formItem.name]"
            :placeholder="formItem.describe"
            :disabled="isView"
          >
            <el-option
              v-for="item in itemLists[formItem.extendId]"
              :key="item.index"
              :label="item.name"
              :value="item.index"
            >
              <div
                :style="{
                  width: '100%',
                  height: '100%',
                  'background-color': item.bgColor,
                }"
              >
                <el-image
                  style="
                    width: 25px;
                    height: 25px;
                    vertical-align: middle;
                    margin-right: 3px;
                  "
                  :src="item.icon"
                  fit="fill"
                >
                  <template #error>
                    <div class="image-slot"></div>
                  </template>
                </el-image>
                <span :style="{ color: item.frontColor }">{{ item.name }}</span>
              </div>
            </el-option>
          </el-select>
          <!--多级类别-->
          <el-cascader
            clearable
            v-if="['multiple_select'].indexOf(formItem.frontType) > -1"
            v-model="dataForm[formItem.name]"
            :options="itemLists[formItem.extendId]"
            :props="{
              label: 'name',
              value: 'index',
              checkStrictly: true,
              emitPath: false,
            }"
            :disabled="isView"
          >
            <template #default="{ node, data }">
              <div style="display: none">{{ node }}</div>
              <div
                :style="{
                  width: '100%',
                  height: '100%',
                  'background-color': data.bgColor,
                }"
              >
                <el-image
                  style="
                    width: 25px;
                    height: 25px;
                    vertical-align: middle;
                    margin-right: 3px;
                  "
                  :src="data.icon"
                  fit="fill"
                >
                  <template #error>
                    <div class="image-slot"></div>
                  </template>
                </el-image>
                <span :style="{ color: data.frontColor }">{{ data.name }}</span>
              </div>
            </template>
          </el-cascader>

          <!-- 经纬度、点、线、面选择-->
          <span
            v-if="
              [
                'latlng',
                'point',
                'polyline',
                'polygon',
                'spoint',
                'spolyline',
                'spolygon',
                'map_draw',
              ].indexOf(formItem.frontType) > -1
            "
          >
            <el-input v-show="false" v-model="dataForm[formItem.name]" />
            <el-button @click="handleMapSelect(formItem)">
              <span>{{ isView ? "查看" : "设置" }}</span
              >地理元素
            </el-button>
            <el-icon
              :color="'green'"
              style="margin: 0 5px"
              v-if="dataForm[formItem.name] && dataForm[formItem.name] != ''"
            >
              <ElIconCircleCheck />
            </el-icon>
            <span
              style="
                font-size: 10px;
                color: #606266;
                display: inline-block;
                margin-left: 5px;
              "
            >
              {{ formItem.describe }}
            </span>
          </span>

          <!--文件/图片/音频/视频-->
          <span
            v-if="['files', 'picture', 'video', 'audio'].indexOf(formItem.frontType) > -1"
          >
            <el-upload
              :ref="formItem.name + '-upload'"
              :file-list="dataForm[formItem.name + '-fileList']"
              :limit="1"
              :http-request="(options) => handleUpload(options, formItem.name)"
              :before-upload="
                (rawFile) =>
                  handleBeforeUpload(
                    rawFile,
                    formItem.name + '-upload',
                    formItem.frontType
                  )
              "
              :on-exceed="(val) => handleUploadExceed(val, formItem.name)"
              :before-remove="(val) => handleUploadRemove(val, formItem.name)"
              :on-preview="(file) => handlePreview(file, formItem.frontType)"
              :disabled="isView"
            >
              <el-input
                v-model="dataForm[formItem.name]"
                :disabled="true"
                v-show="false"
              />
              <el-button type="primary" :disabled="isView">选择文件</el-button>
              <el-icon
                :color="'green'"
                style="margin: 0 5px"
                v-if="
                  dataForm[formItem.name + '-fileStatus'] !== -1 &&
                  dataForm[formItem.name] &&
                  dataForm[formItem.name] != ''
                "
              >
                <ElIconCircleCheck />
              </el-icon>
              <span v-if="dataForm[formItem.name + '-fileStatus'] === -1">
                <el-popover
                  placement="top-start"
                  trigger="hover"
                  popper-class="file_warning"
                  content="文件无法访问"
                >
                  <template #reference>
                    <el-icon :color="'orange'" style="margin: 0 5px; cursor: help">
                      <ElIconWarning />
                    </el-icon>
                  </template>
                </el-popover>
              </span>
              <template #tip>
                <span
                  class="el-upload__tip"
                  style="display: inline-block; margin-left: 10px"
                >
                  {{ formItem.describe }}
                </span>
              </template>
            </el-upload>
          </span>

          <!--带地理位置的图片、音频、视频-->
          <span
            v-if="
              ['picture_location', 'audio_location', 'video_location'].indexOf(
                formItem.frontType
              ) > -1
            "
          >
            <el-upload
              :ref="formItem.name + '-upload'"
              :file-list="dataForm[formItem.name + '-fileList']"
              :limit="1"
              :http-request="
                (options) => handleUpload(options, formItem.name + '-file', true)
              "
              :before-upload="
                (rawFile) =>
                  handleBeforeUpload(rawFile, formItem.name, formItem.frontType)
              "
              :on-exceed="(val) => handleUploadExceed(val, formItem.name + '-file')"
              :before-remove="
                (val) => handleUploadRemove(val, formItem.name + '-file', true)
              "
              :on-preview="(file) => handlePreview(file, formItem.frontType)"
              :disabled="isView"
            >
              <el-button type="primary" :disabled="isView">选择文件</el-button>
              <el-icon
                :color="'green'"
                style="margin: 0 5px"
                v-if="
                  dataForm[formItem.name + '-fileStatus'] !== -1 &&
                  dataForm[formItem.name + '-file'] &&
                  dataForm[formItem.name + '-file'] != ''
                "
              >
                <ElIconCircleCheck />
              </el-icon>
              <span v-if="dataForm[formItem.name + '-fileStatus'] === -1">
                <el-popover
                  placement="top-start"
                  trigger="hover"
                  popper-class="file_warning"
                  content="文件无法访问"
                >
                  <template #reference>
                    <el-icon :color="'orange'" style="margin: 0 5px; cursor: help">
                      <ElIconWarning />
                    </el-icon>
                  </template>
                </el-popover>
              </span>
              <template #tip>
                <span
                  class="el-upload__tip"
                  style="display: inline-block; margin-left: 10px"
                >
                  {{ formItem.describe }}
                </span>
              </template>
            </el-upload>
            <el-button @click="handleMapSelect(formItem, formItem.name + '-location')">
              <span>{{ isView ? "查看" : "设置" }}</span
              >地理位置
            </el-button>
            <el-icon
              :color="'green'"
              style="margin: 0 5px"
              v-if="
                dataForm[formItem.name + '-location'] &&
                dataForm[formItem.name + '-location'] != ''
              "
            >
              <ElIconCircleCheck />
            </el-icon>
          </span>

          <!--图册-->
          <el-upload
            v-if="['pictures'].indexOf(formItem.frontType) > -1"
            list-type="picture-card"
            :file-list="dataForm[formItem.name + '-fileList']"
            :disabled="isView"
            :http-request="(options) => handleTCUpload(options, formItem.name)"
            :on-preview="(file) => handleTCPreview(file)"
          >
            <el-icon v-if="!isView">
              <ElIconPlus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="sure" v-if="!isView">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      :class="'ContentMap'"
      v-model="isMapShow"
      v-if="isMapShow"
      width="1200px"
      top="7%"
      bottom="5%"
      title="地图选择"
      :close-on-click-modal="false"
      :before-close="mapDialogBeforeClose"
    >
      <div style="width: 100%; height: 40px; padding-bottom: 5px" v-if="!isView">
        <el-button
          style="margin: 5px"
          @click="mapMarkPoint"
          v-if="
            [
              'map_draw',
              'latlng',
              'point',
              'spoint',
              'picture_location',
              'audio_location',
              'video_location',
            ].indexOf(currMapItem.frontType) > -1
          "
          >点标记</el-button
        >
        <el-button
          style="margin: 5px"
          @click="mapMarkLine"
          v-if="['map_draw', 'polyline', 'spolyline'].indexOf(currMapItem.frontType) > -1"
          >线标记</el-button
        >
        <el-button
          style="margin: 5px"
          @click="mapMarkPolygon"
          v-if="['map_draw', 'polygon', 'spolygon'].indexOf(currMapItem.frontType) > -1"
          >面标记</el-button
        >
        <el-button style="margin: 5px" @click="calcelMark">取消标记</el-button>
      </div>
      <div id="mapContent">
        <div id="mapPicker" style="width: 100%; height: 100%"></div>
      </div>
      <div id="mapRight">
        <el-form :label-position="'top'">
          <el-form-item :label="'地理信息预览:'">
            <!-- <json-viewer
              :style="{ height: '350px', overflow: 'auto' }"
              :value="JSON.parse(JSON.stringify(geoJsons))"
              :expand-depth="5"
              copyable
              boxed
              sort
            ></json-viewer> -->
            <div style="position: absolute;z-index: 9;top: 2px;right: 50px;cursor: pointer;" @click="copyText(geoJsons)">复制</div>
            <json-editor-vue
              class="json-editor"
              :modeList="couldView"
              :style="{ height: '370px',width: '100%', overflow: 'auto' }"
              :modelValue="JSON.parse(JSON.stringify(geoJsons))"
              @update:modelValue="changeValue"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" @click="mapSure()" v-if="!isView">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-if="isMediaShow" v-model="isMediaShow" title="资源预览">
      <span v-if="currMedia.images">
        <!-- style="width: 200px; height: 200px; margin: 5px" -->
        <el-image
          w-full
          v-for="(item, index) in currMedia.images"
          :key="index"
          :src="item"
          :fit="fit"
        />
      </span>
      <span v-if="currMedia.video">
        <video width="500" height="300" :src="currMedia.video" controls></video>
      </span>
      <span v-if="currMedia.audio">
        <audio :src="currMedia.audio" controls></audio>
      </span>
      <span v-if="currMedia.file">
        <el-button>
          <a :href="currMedia.file" :download="currMedia.file">点击下载</a>
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { toRaw } from "vue";
import api from "@/api/content";
import { genFileId, ElLoading } from "element-plus";
import moment from 'moment';
export default {
  name: "contentDetail",
  data() {
    return {
      isDialogShow: true,
      dataForm: {},
      dataFormRules: {
        required: [
          { required: true, message: "该字段不能为空", trigger: "blur" },
          { required: true, message: "该字段不能为空", trigger: "change" },
        ],
      },
      modelFieldList: [],
      itemLists: {},

      map: {},
      currMapItem: {},
      isMapShow: true,
      mapMarkers: {
        layers: [],
        points: [],
        linePoints: [],
        polPoints: [],
        lines: [],
        pols: [],
      },
      mapLines: [],
      geoJsons: [],

      isMediaShow: false,
      currMedia: {
        images: [],
      },
      mediaTypes: {
        image: ["image/gif", "image/jpeg", "image/jpg", "image/bmp", "image/png"],
        video: ["video/mp4"],
        audio: ["audio/mpeg"],
      },
      couldView: ["code"] // "tree", "code", "form", "view"
    };
  },
  props: {
    isShow: Boolean,
    columnModel: Object,
    column: Object,
    item: Object,
    isView: Boolean,
    close: Function,
  },
  created() {
    let that = this;
    let modelFields = JSON.parse(this.columnModel.fieldList);
    // 无序
    let keys = Object.keys(modelFields)
    for (let i = 0; i < keys.length; i++) {
      let obj = modelFields[keys[i]];
      if (!obj.name) {
        obj = JSON.parse(obj)
      }
      obj["key"] = keys[i];
      if (["check", "multiple_check"].indexOf(obj.frontType) > -1) {
        this.getCheckItems(obj, 1);
      } else if (["select", "multiple_select"].indexOf(obj.frontType) > -1) {
        this.getCheckItems(obj, 2);
      }
      this.modelFieldList.push(obj);
    }
    // 有序
    // for (let key in modelFields) {
    //   let obj = modelFields[key];
    //   if (!obj.name) {
    //     obj = JSON.parse(obj);
    //   }
    //   obj["key"] = key;
    //   if (["check", "multiple_check"].indexOf(obj.frontType) > -1) {
    //     this.getCheckItems(obj, 1);
    //   } else if (["select", "multiple_select"].indexOf(obj.frontType) > -1) {
    //     this.getCheckItems(obj, 2);
    //   }
    //   debugger
    //   console.log(1111);
      
    //   this.modelFieldList.push(obj);
    // }
    this.modelFieldList.sort((a, b) => {
      // return a.index > b.index ? 1 : a.sequence > b.sequence ? 1 : -1;
      return a.index > b.index ? 1 : -1;
    });
    if (this.item && this.item !== "" && JSON.stringify(this.item) != "{}") {
      this.modelFieldList.forEach((data) => {
        if (
          [
            "latlng",
            "point",
            "polyline",
            "polygon",
            "spoint",
            "spolyline",
            "spolygon",
          ].indexOf(data.frontType) > -1
        ) {
          that.item[data.name] = that.item[data.name];
        } else if (
          ["picture_location", "audio_location", "video_location"].indexOf(
            data.frontType
          ) > -1
        ) {
          let obj = JSON.parse(that.item[data.name]);
          that.item[data.name + "-file"] = obj.url;
          api
            .getContentFile(obj.url)
            .then((response) => {
              that.item[data.name + "-fileList"] = [];
              let file = new File(
                [response],
                that.item[data.name].substr(
                  that.item[data.name].length - 40,
                  that.item[data.name].length
                )
              );
              file.serverUrl = obj.url;
              that.item[data.name + "-fileList"].push(file);
            })
            .catch((err) => {
              if (err.response.status !== 200) {
                that.item[data.name + "-fileStatus"] = -1;
              }
            });
          that.item[data.name + "-location"] = obj.location;
        } else if ("multiple_check" == data.frontType) {
          if (!that.item[data.name]) {
            that.item[data.name] = [];
          } else {
            let val = [];
            let splice = that.item[data.name].split(",");
            for (let i = 0; i < splice.length; i++) {
              val.push(Number(splice[i]));
            }
            that.item[data.name] = val;
          }
        } else if (["check", "select", "multiple_select"].indexOf(data.frontType) > -1) {
          that.item[data.name] = Number(that.item[data.name]);
        } else if (["files", "picture", "audio", "video"].indexOf(data.frontType) > -1) {
          if (!that.item[data.name]) return;
          api
            .getContentFile(that.item[data.name])
            .then((response) => {
              that.item[data.name + "-fileList"] = [];
              let file = new File(
                [response],
                that.item[data.name].substr(
                  that.item[data.name].length - 40,
                  that.item[data.name].length
                )
              );
              file.serverUrl = that.item[data.name];
              that.item[data.name + "-fileList"].push(file);
            })
            .catch((err) => {
              if (err.response.status !== 200) {
                that.item[data.name + "-fileStatus"] = -1;
              }
            });
        } else if ("pictures" === data.frontType) {
          if (!that.item[data.name]) {
            that.item[data.name + "-fileList"] = [];
            return;
          }

          let obj = JSON.parse(that.item[data.name]);
          that.item[data.name + "-fileList"] = [];
          obj.forEach((i) => {
            let url =
              i.indexOf(systemConfig.dmsDataProxy) !== 0
                ? systemConfig.dmsDataProxy + i
                : i;
            that.item[data.name + "-fileList"].push({
              name: i.substr(i.length - 40, i.length),
              url: url,
              serverUrl: i,
            });
          });
        }
      });
    }
    this.dataForm = this.item;
    // console.log(this.dataForm)
  },
  mounted() {
    this.isMapShow = false;
  },
  methods: {
    async textToCopy(){
      let that = this;
      // copyText(JSON.stringify(that.geoJsons))
      await navigator.clipboard.writeText(JSON.stringify(that.geoJsons));
      this.$message({ message: "复制成功", type: "success" });
    },
    changeValue(json){
      let that = this;
      let Icon = L.divIcon({
        className: "my-div-icon", //自定义icon css样式
        iconSize: [10, 10], //点大小
      });
      that.geoJsons = json
      let center = that.geoJsons[0].geometry.coordinates;
      let type = that.geoJsons[0].geometry.type;
      if(type == "Point"){//更新点坐标
        that.mapMarkers.points[0].setLatLng([center[1],center[0]]);
      }else if(type == 'LineString'){ // 更新面数据
        let geojsons = [];
        that.mapMarkers.layers.forEach((item) => {
          that.map.removeLayer(item);
        });
        that.mapMarkers = {
          layers: [],
          points: [],
          linePoints: [],
          polPoints: [],
          lines: [],
          pols: [],
        };

        for (var i = 0; i < that.geoJsons.length; i++) {
            that.geoJsons[i].geometry.coordinates.forEach((item) => {
              let marker = L.marker([item[1],item[0]], {
                icon: Icon,
              }).addTo(that.map);
              if (["polyline", "spolyline"].indexOf(that.currMapItem.frontType) > -1) {
                that.mapMarkers.lines.forEach((item) => {
                  that.map.removeLayer(item);
                });
                that.mapMarkers.lines = [];
                geojsons = [];
              }
              //添加点到地图中
              that.mapMarkers.linePoints.push(marker);
              that.mapMarkers.layers.push(marker);
              if (that.mapMarkers.linePoints.length > 1) {
                let points = [];
                that.mapMarkers.linePoints.forEach((item) => {
                  points.push([item._latlng.lat, item._latlng.lng]);
                });
                let line = L.polyline(points, {
                  color: "red",
                }).addTo(that.map);
                that.mapMarkers.layers.push(line);
                if (
                  that.currMapItem.frontType == "map_draw" &&
                  that.mapMarkers.linePoints.length > 2
                ) {
                  let lastLine = that.mapMarkers.lines[that.mapMarkers.lines.length - 1];
                  that.map.removeLayer(lastLine);
                  that.mapMarkers.lines.splice(that.mapMarkers.lines.length - 1, 1);
                  geojsons.splice(geojsons.length - 1, 1);
                }
                that.mapMarkers.lines.push(line);
                geojsons.push(line.toGeoJSON())
              }
            });
        }
        that.geoJsons = geojsons
      }else if(type == 'Polygon'){
        let geojsons = [];
        that.mapMarkers.layers.forEach((item) => {
          that.map.removeLayer(item);
        });
        that.mapMarkers = {
          layers: [],
          points: [],
          linePoints: [],
          polPoints: [],
          lines: [],
          pols: [],
        };
        for (var i = 0; i < that.geoJsons.length; i++) {
            that.geoJsons[i].geometry.coordinates.forEach((coordItem) => {
              coordItem.forEach((item) => {
                let marker = L.marker([item[1],item[0]], {
                  icon: Icon,
                }).addTo(that.map);
                //添加点到地图中
                that.mapMarkers.polPoints.push(marker);
                that.mapMarkers.layers.push(marker);

                if (["polygon", "spolygon"].indexOf(that.currMapItem.frontType) > -1) {
                  that.mapMarkers.pols.forEach((item) => {
                    that.map.removeLayer(item);
                  });
                  that.mapMarkers.pols = [];
                  geojsons = [];
                }

                if (that.mapMarkers.polPoints.length > 2) {
                  let points = [];
                  that.mapMarkers.polPoints.forEach((item) => {
                    points.push([item._latlng.lat, item._latlng.lng]);
                  });
                  let polygon = L.polygon(points, {
                    color: "red",
                  }).addTo(that.map);
                  that.mapMarkers.layers.push(polygon);
                  if (
                    that.currMapItem.frontType == "map_draw" &&
                    that.mapMarkers.polPoints.length > 3
                  ) {
                    let lastPol = that.mapMarkers.pols[that.mapMarkers.pols.length - 1];
                    that.map.removeLayer(lastPol);
                    that.mapMarkers.pols.splice(that.mapMarkers.pols.length - 1, 1);
                    geojsons.splice(geojsons.length - 1, 1);
                  }
                  that.mapMarkers.pols.push(polygon);
                  geojsons.push(polygon.toGeoJSON());
                }
              })
            })
          }
          that.geoJsons = geojsons
      }
      let bboxObj = {
          type: "FeatureCollection",
          features: that.geoJsons.map(function (item) {
            if (item.type == "Feature") {
              return item;
            } else {
              return {
                type: "Feature",
                geometry: item,
              };
            }
          }), 
        };
        let extent = turf.bbox(bboxObj);
        var bounds = L.latLngBounds([
          [extent[3], extent[2]],
          [extent[1], extent[0]],
        ]);

        //定位到矩形
        that.map.fitBounds(bounds,{ padding: [10, 10], maxZoom: 15 });


    },
    dialogBeforeClose() {
      this.close();
    },
    mapDialogBeforeClose() {
      this.isMapShow = false;
      this.calcelMark();
      this.geoJsons = [];
      this.mapMarkers = {
        layers: [],
        points: [],
        linePoints: [],
        polPoints: [],
        lines: [],
        pols: [],
      };
    },
    handleMapFileChange(name) {
      if (
        this.dataForm[name + "-file"] &&
        this.dataForm[name + "-file"] !== "" &&
        this.dataForm[name + "-location"] &&
        this.dataForm[name + "-location"] !== ""
      ) {
        let obj = {
          location: this.dataForm[name + "-location"],
          url: this.dataForm[name + "-file"],
        };
        this.dataForm[name] = obj;
      } else {
        this.dataForm[name] = "";
      }
      this.$refs.dataForm.validateField(name);
    },
    mapSure() {
      this.isMapShow = false;
      if (this.geoJsons.length < 1) {
        this.dataForm[this.currMapItem.name] = null;
      } else {
        if (
          [
            "latlng",
            "point",
            "spoint",
            "polyline",
            "spolyline",
            "polygon",
            "spolygon",
            "picture_location",
            "audio_location",
            "video_location",
          ].indexOf(this.currMapItem.frontType) > -1
        ) {
          this.dataForm[this.currMapItem.name] = this.$WKT.convert(
            this.geoJsons[0].geometry
          );
        } else {
          let geoCollection = {
            type: "FeatureCollection",
            features: [],
          };
          this.geoJsons.forEach((item) => {
            geoCollection.features.push(toRaw(item));
          });
          this.dataForm[this.currMapItem.name] = JSON.stringify(geoCollection);
        }
      }
      if (
        ["picture_location", "audio_location", "video_location"].indexOf(
          this.currMapItem.frontType
        ) > -1
      ) {
        this.handleMapFileChange(
          this.currMapItem.name.substr(0, this.currMapItem.name.length - 9)
        );
      }
      this.calcelMark();
      this.geoJsons = [];
      this.mapMarkers = {
        layers: [],
        points: [],
        linePoints: [],
        polPoints: [],
        lines: [],
        pols: [],
      };
    },
    mapMarkPoint() {
      let that = this;
      that.map.off("click");
      let Icon = L.divIcon({
        className: "my-div-icon", //自定义icon css样式
        iconSize: [10, 10], //点大小
      });
      that.map.on("click", function (e) {
        var lat = e.latlng.lat; //纬度
        var lng = e.latlng.lng; //经度
        //打点
        if (
          [
            "latlng",
            "point",
            "spoint",
            "picture_location",
            "audio_location",
            "video_location",
          ].indexOf(that.currMapItem.frontType) > -1 &&
          that.mapMarkers.points.length > 0
        ) {
          //更新点坐标
          that.mapMarkers.points[0].setLatLng([lat, lng]);
          that.geoJsons[0] = that.mapMarkers.points[0].toGeoJSON();
        } else {
          let marker = L.marker([lat, lng], {
            icon: Icon,
          }).addTo(that.map);
          //添加点到地图中
          that.mapMarkers.points.push(marker);
          that.mapMarkers.layers.push(marker);
          that.geoJsons.push(marker.toGeoJSON());
        }
      });
    },
    mapMarkLine() {
      let that = this;
      if (this.currMapItem.frontType == "map_draw") {
        that.mapMarkers.linePoints = [];
      }
      that.map.off("click");
      let Icon = L.divIcon({
        className: "my-div-icon", //自定义icon css样式
        iconSize: [10, 10], //点大小
      });
      that.map.on("click", function (e) {
        var lat = e.latlng.lat; //纬度
        var lng = e.latlng.lng; //经度
        let marker = L.marker([lat, lng], {
          icon: Icon,
        }).addTo(that.map);
        if (["polyline", "spolyline"].indexOf(that.currMapItem.frontType) > -1) {
          that.mapMarkers.lines.forEach((item) => {
            that.map.removeLayer(item);
          });
          that.mapMarkers.lines = [];
          that.geoJsons = [];
        }
        //添加点到地图中
        that.mapMarkers.linePoints.push(marker);
        that.mapMarkers.layers.push(marker);
        if (that.mapMarkers.linePoints.length > 1) {
          let points = [];
          that.mapMarkers.linePoints.forEach((item) => {
            points.push([item._latlng.lat, item._latlng.lng]);
          });
          let line = L.polyline(points, {
            color: "red",
          }).addTo(that.map);
          that.mapMarkers.layers.push(line);
          if (
            that.currMapItem.frontType == "map_draw" &&
            that.mapMarkers.linePoints.length > 2
          ) {
            let lastLine = that.mapMarkers.lines[that.mapMarkers.lines.length - 1];
            that.map.removeLayer(lastLine);
            that.mapMarkers.lines.splice(that.mapMarkers.lines.length - 1, 1);
            that.geoJsons.splice(that.geoJsons.length - 1, 1);
          }
          that.mapMarkers.lines.push(line);
          that.geoJsons.push(line.toGeoJSON());
        }
      });
    },
    mapMarkPolygon() {
      let that = this;
      if (this.currMapItem.frontType == "map_draw") {
        that.mapMarkers.polPoints = [];
      }
      that.map.off("click");
      let Icon = L.divIcon({
        className: "my-div-icon", //自定义icon css样式
        iconSize: [10, 10], //点大小
      });
      that.map.on("click", function (e) {
        var lat = e.latlng.lat; //纬度
        var lng = e.latlng.lng; //经度
        let marker = L.marker([lat, lng], {
          icon: Icon,
        }).addTo(that.map);
        //添加点到地图中
        that.mapMarkers.polPoints.push(marker);
        that.mapMarkers.layers.push(marker);

        if (["polygon", "spolygon"].indexOf(that.currMapItem.frontType) > -1) {
          that.mapMarkers.pols.forEach((item) => {
            that.map.removeLayer(item);
          });
          that.mapMarkers.pols = [];
          that.geoJsons = [];
        }

        if (that.mapMarkers.polPoints.length > 2) {
          let points = [];
          that.mapMarkers.polPoints.forEach((item) => {
            points.push([item._latlng.lat, item._latlng.lng]);
          });
          let polygon = L.polygon(points, {
            color: "red",
          }).addTo(that.map);
          that.mapMarkers.layers.push(polygon);
          if (
            that.currMapItem.frontType == "map_draw" &&
            that.mapMarkers.polPoints.length > 3
          ) {
            let lastPol = that.mapMarkers.pols[that.mapMarkers.pols.length - 1];
            that.map.removeLayer(lastPol);
            that.mapMarkers.pols.splice(that.mapMarkers.pols.length - 1, 1);
            that.geoJsons.splice(that.geoJsons.length - 1, 1);
          }
          that.mapMarkers.pols.push(polygon);
          that.geoJsons.push(polygon.toGeoJSON());
        }
      });
    },
    calcelMark() {
      let that = this;
      that.map.off("click");
      that.mapMarkers.layers.forEach((item) => {
        that.map.removeLayer(item);
      });
      that.mapMarkers = {
        layers: [],
        points: [],
        linePoints: [],
        polPoints: [],
        lines: [],
        pols: [],
      };
      this.geoJsons = [];
    },
    handleMapSelect(item, alias) {
      this.isMapShow = true;
      item = JSON.parse(JSON.stringify(item));
      if (alias && alias != "") {
        item.name = alias;
      }
      this.currMapItem = item;
      let that = this;
      this.$nextTick(() => {
        that.map = that.$L.map("mapPicker", {
          minZoom: 3,
          maxZoom: 20,
          // center: [39.915457, 116.453437],
          center: [31.175188130627745, 121.26786280328167],
          zoom: 15,
          zoomControl: false,
          attributionControl: false,
          crs: L.CRS.EPSG4326,
        });
        that.$L
          .tileLayer(systemConfig.VEC_C + systemConfig.TDT_TK, {
            maxZoom: 20,
            tileSize: 256,
            zoomOffset: 1,
          })
          .addTo(that.map);
        that.$L
          .tileLayer(systemConfig.CVA_C + systemConfig.TDT_TK, {
            maxZoom: 20,
            tileSize: 256,
            zoomOffset: 1,
          })
          .addTo(that.map);
        if (that.dataForm[item.name]) {
          let Icon = L.divIcon({
            className: "my-div-icon", //自定义icon css样式
            iconSize: [10, 10], //点大小
          });
          let geojsons = [];
          if (that.currMapItem.frontType != "map_draw") {
            if (that.dataForm[item.name].value) {
              geojsons.push(that.$WKT.parse(that.dataForm[item.name].value));
            } else {
              geojsons.push(that.$WKT.parse(that.dataForm[item.name]));
            }
          } else {
            let obj = JSON.parse(that.dataForm[item.name]);
            if (obj.features && obj.features !== "") {
              obj.features.forEach((i) => geojsons.push(i));
            }
          }

          let bboxObj = {
            type: "FeatureCollection",
            features: geojsons.map(function (item) {
              if (item.type == "Feature") {
                return item;
              } else {
                return {
                  type: "Feature",
                  geometry: item,
                };
              }
            }),
          };
          let extent = turf.bbox(bboxObj);
          var bounds = L.latLngBounds([
            [extent[3], extent[2]],
            [extent[1], extent[0]],
          ]);

          //定位到矩形
          that.map.fitBounds(bounds);

          // console.log(t)

          for (let i = 0; i < geojsons.length; i++) {
            let layer = that.$L
              .geoJSON(geojsons[i], {
                onEachFeature: function (feature, layer) {
                  if (feature.properties && feature.properties.name) {
                    layer.bindTooltip(feature.properties.name);
                    layer.bindPopup(feature.properties.address);
                  }
                },
                pointToLayer: function (feature, latlng) {
                  let marker = L.marker(latlng, {
                    icon: Icon,
                  });
                  that.mapMarkers.points.push(marker);
                  return marker;
                },
              })
              .addTo(that.map);
            that.geoJsons.push(layer.toGeoJSON().features[0]);
          }
        }
      });
    },

    handleBeforeUpload(file, ref, type) {
      let fileType = file.type;
      let fileSize = file.size / 1024 / 1024;
      // 判断类型
      if (["picture", "picture_location"].indexOf(type) > -1) {
        if (this.mediaTypes.image.indexOf(fileType) < 0) {
          this.$message({ message: "不支持的图片类型", type: "warning" });
          return false;
        }
      } else if (["audio", "audio_location"].indexOf(type) > -1) {
        if (this.mediaTypes.audio.indexOf(fileType) < 0) {
          this.$message({ message: "不支持的音频类型", type: "warning" });
          return false;
        }
      } else if (["video", "video_location"].indexOf(type) > -1) {
        if (this.mediaTypes.video.indexOf(fileType) < 0) {
          this.$message({ message: "不支持的视频类型", type: "warning" });
          return false;
        }
      }
      // 判断大小
      if (["video", "video_location"].indexOf(type) > -1) {
        if (fileSize > 40) {
          this.$message({ message: "文件不能超过40M", type: "warning" });
          return false;
        }
      } else {
        if (fileSize > 10) {
          this.$message({ message: "文件不能超过10M", type: "warning" });
          return false;
        }
      }
      return true;
    },
    handleUpload(options, ref, isMapFile, isMulti) {
      let that = this;
      let params = {
        columnId: this.columnModel.id,
        contentId: this.item.id,
        paraName: options.file.name,
        type: 0,
        file: options.file,
      };
      const loadingInstance = ElLoading.service({
        customClass: "content-detail-upload-loading",
        fullscreen: true,
        text: "上传中，请稍后...",
      });
      api.uploadFile(params).then((res) => {
        if (res.code === 200) {
          loadingInstance.close();
          that.dataForm[ref + "-fileStatus"] = null;
          options.file.serverUrl = res.content;
          if (isMulti) {
            let urls = [];
            that.dataForm[ref + "-fileList"].forEach((i) => {
              let serverUrl = i.raw ? i.raw.serverUrl : i.serverUrl ? i.serverUrl : "";
              urls.push(serverUrl);
            });
            that.dataForm[ref] = urls;
          } else {
            that.dataForm[ref] = res.content;
          }
          if (isMapFile) {
            this.handleMapFileChange(ref.substr(0, ref.length - 5));
          }
        } else {
          loadingInstance.close();
          that.$message({ message: res.content, type: "error" });
        }
      });
    },
    handleUploadExceed(file, ref) {
      this.$refs[ref + "-upload"][0].clearFiles();
      file = file[0];
      file.uid = genFileId();
      this.$refs[ref + "-upload"][0].handleStart(file);
      this.$refs[ref + "-upload"][0].submit();
    },
    handleUploadRemove(file, ref, isMapFile) {
      this.dataForm[ref] = "";
      if (isMapFile) {
        this.handleMapFileChange(ref.substr(0, ref.length - 5));
      }
    },
    handlePreview(file, type) {
      this.isMediaShow = true;
      this.currMedia = {};
      let serverUrl = file.raw
        ? file.raw.serverUrl
        : file.serverUrl
        ? file.serverUrl
        : "";
      let url =
        serverUrl.indexOf(systemConfig.dmsDataProxy) !== 0
          ? systemConfig.dmsDataProxy + serverUrl
          : serverUrl;
      if (["picture", "picture_location"].indexOf(type) > -1) {
        this.currMedia.images = [url];
      } else if (["video", "video_location"].indexOf(type) > -1) {
        this.currMedia.video = url;
      } else if (["audio", "audio_location"].indexOf(type) > -1) {
        this.currMedia.audio = url;
      } else {
        this.currMedia.file = url;
      }
    },

    handleTCUpload(options, ref) {
      let that = this;
      let params = {
        columnId: this.columnModel.id,
        contentId: this.item.id,
        paraName: options.file.name,
        type: 0,
        file: options.file,
      };
      // loading
      const loadingInstance = ElLoading.service({
        customClass: "content-detail-upload-loading",
        fullscreen: true,
        text: "上传中，请稍后...",
      });
      api.uploadFile(params).then((res) => {
        if (res.code === 200) {
          loadingInstance.close();
          that.dataForm[ref + "-fileStatus"] = null;
          options.file.serverUrl = res.content;
          let url = systemConfig.dmsDataProxy + res.content;
          that.dataForm[ref + "-fileList"].push({
            name: options.file.name,
            url: url,
            serverUrl: res.content,
          });
        } else {
          loadingInstance.close();
          that.$message({ message: res.content, type: "error" });
        }
      });
    },
    handleTCPreview(file) {
      file = toRaw(file);
      let serverUrl = file.raw
        ? file.raw.serverUrl
        : file.serverUrl
        ? file.serverUrl
        : "";
      let url =
        serverUrl.indexOf(systemConfig.dmsDataProxy) !== 0
          ? systemConfig.dmsDataProxy + serverUrl
          : serverUrl;
      this.currMedia.images = [url];
      this.isMediaShow = true;
    },

    handleDateFormat(val, fmt) {
      if (!fmt || fmt == "") {
        fmt = "0";
      }
      if (fmt == "0") {
        return moment(val).format('YYYY-MM-DD');
      } else if (fmt == "1") {
        return moment(val).format('YYYY-MM-DD HH:mm:ss');
      } else if (fmt == "2") {
        return moment(val).format('YYYY-MM-DD HH:mm:ss.ssss')
      } else {
        return moment(val).format('YYYY-MM-DD HH:mm:ss');
      }
    },
    sure() {
      let that = this;
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          console.log('[ eeeee ] >')
          let content = {};
          content["id"] = that.dataForm["id"];
          content["title"] = that.dataForm["title"];
          content["content"] = that.dataForm["content"];
          that.modelFieldList.forEach((field) => {
            if (field.frontType == "multiple_check") {
              if (that.dataForm[field.name] == undefined) that.dataForm[field.name] = [];
              let str = that.dataForm[field.name].join(",");
              str.replace("[", "");
              str.replace("]", "");
              content[field.name] = str;
            } else if (field.frontType == "date_time") {
              content[field.name] = that.dataForm[field.name];
            } else if (field.frontType == "pictures") {
              content[field.name] = [];
              if (that.dataForm[field.name + "-fileList"]) {
                that.dataForm[field.name + "-fileList"].forEach((i) => {
                  content[field.name].push(i.serverUrl);
                });
              }
              content[field.name] = JSON.stringify(content[field.name]);
            } else {
              content[field.name] = that.dataForm[field.name];
            }
          });
          let params = {
            content: JSON.stringify(content),
            columnId: that.column.columnId,
            modelId: that.column.modelId,
          };
          if (content.id && content.id !== "") {
            api
              .updateContent(params)
              .then((res) => {
                if (res.code === 200) {
                  that.close(true);
                  that.$message({ message: "修改成功", type: "success" });
                } else {
                  that.$message({ message: res.content, type: "error" });
                }
              })
              .catch((err) => {
                that.$message({ message: err.message, type: "error" });
              });
          } else {
            api
              .addContent(params)
              .then((res) => {
                if (res.code === 200) {
                  that.close(true);
                  let message = "添加成功";
                  if(that.column.columnId == systemConfig.columnIds[3] && that.column.modelId == systemConfig.modelIds[1]){ //指定 一张图登录栏目 申请账号时使用判断
                    message = "申请成功！请等待三个工作日后，管理员审核通过后，您才能登录系统。"
                  }
                  that.$message({ message: message, type: "success" });
                } else {
                  that.$message({ message: res.content, type: "error" });
                }
              })
              .catch((err) => {
                that.$message({ message: err.message, type: "error" });
              });
          }
        }
      });
    },
    getCheckItems(item, type) {
      let that = this;
      console.log('[ eee ] >')
      if (type === 1) {
        api.getCheckDetail({ sName: item.extendId }).then((res) => {
          if (res.code == 200) {
            that.itemLists[item.extendId] = res.content;
          }
        });
      } else if (type === 2) {
        let cType =
          item.frontType === "select"
            ? 0
            : item.frontType === "multiple_select"
            ? 1
            : null;
        api.getCategoryDetail({ type: cType, cName: item.extendId }).then((res) => {
          if (res.code == 200) {
            that.itemLists[item.extendId] = res.content;
          }
        });
      }
    },
  },
};
</script>

<style>
.jsoneditor-menu{
  display: none;
}
.jsoneditor-statusbar{
  display: none;
}
.jsoneditor-validation-errors-container{
  display: none;
}
div.jsoneditor-outer.has-main-menu-bar {
    margin-top: 0px; 
    padding-top: 40px; 
    background-color: #e2f1fa;
}
.full-screen{
    right: 10px !important;
    background-color: #d9d9d9 !important;
}

#mapContent {
  height: 400px;
  width: 70%;
  display: inline-block;
}

#mapRight {
  padding-left: 10px;
  height: 400px;
  width: 25%;
  display: inline-block;
  vertical-align: top;
}

.my-div-icon {
  width: 15px;
  height: 15px;
  background-color: red;
  border-radius: 50%;
}

.file_warning {
  background-color: #fdf6ec !important;
  color: #e8a84a !important;
  font-weight: bold;
}

.el-form-item .el-form-item-label {
  display: inline-block;
  text-align: right;
  /* 防止文本换行 */
  white-space: nowrap;
  /* 隐藏溢出的内容 */
  overflow: hidden;
  /* 显示省略符号 */
  text-overflow: ellipsis;
}

.content-detail-upload-loading svg {
  width: 80px;
  height: 90px;
}

.content-detail-upload-loading .el-loading-text {
  font-size: 20px;
}

</style>
