<template>
  <el-dialog :class="'singleDataDialog'" :visible.sync="isShow" width="700px" top="7%" :close-on-click-modal="false"
    :before-close="dialogBeforeClose">
    <el-form :model="fromDataRender" class="singledata" ref="single_form" label-width="80px" :rules="rules">
      <el-row>
        <el-col :span="11">
          <el-form-item label="名称" prop="title">
            <el-input v-model="fromDataRender.title" :readonly="!edit" maxlength="20" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="行政区划编码" prop="areaCode">
            <el-input v-model="fromDataRender.areaCode" :readonly="!edit" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="11">
          <el-form-item label="几何类型" prop="type">
            <el-select
              v-model="fromDataRender.type"
              placeholder="请选择"
              :disabled="true"
            >
              <el-option
                v-for="item in geoTypeArr"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>-->
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="第三方ID" prop="threeId">
            <el-input v-model="fromDataRender.threeId" :readonly="!edit" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="第三方表名" prop="tableName">
            <el-input v-model="fromDataRender.tableName" :readonly="!edit" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="中心经度" prop="centerLon">
            <el-input v-model="fromDataRender.centerLon" :readonly="!edit"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="中心纬度" prop="centerLat">
            <el-input v-model="fromDataRender.centerLat" :readonly="!edit"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button v-if="edit" :style="{
            fontSize: '23px',
            padding: '7px',
            float: 'right',
          }" :title="'中心点修改'" @click="openCenterLocation(fromDataRender)" icon="el-icon-location-outline">
          </el-button>
        </el-col>
      </el-row>
      <el-row v-if="modelParams.type != 0">
        <el-col :span="22">
          <el-form-item label="点集">
            <!-- :readonly="!edit" -->
            <el-input v-model="fromDataRender.locations" readonly="false" disabled="false"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button v-if="edit" :style="{
            fontSize: '23px',
            padding: '7px',
            float: 'right',
          }" :title="'点集修改'" @click="openGeometryLocation(fromDataRender)" icon="el-icon-edit">
          </el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item label="描述" prop="content">
            <el-input v-model="fromDataRender.content" :readonly="!edit" maxlength="100" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-form-item label="内容描述">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="fromDataRender.jsonStr"
            maxlength="5000"
            show-word-limit
            :readonly="!edit"
            :autosize="{ minRows: 4, maxRows: 6 }"
          >
          </el-input>
        </el-form-item>
      </el-row>-->
      <el-row>
        <el-button type="text" style="float: right" @click="changeAdvancedOptionsStatue()">
          高级选项
          <i v-show="!advancedOptionsShow" class="el-icon-caret-bottom el-icon--right"></i>
          <i v-show="advancedOptionsShow" class="el-icon-caret-top el-icon--right"></i>
        </el-button>
        <!-- el-icon-caret-bottom -->
        <!-- el-icon-caret-top -->
      </el-row>
      <!-- 高级选项 table -->
      <div v-if="advancedOptionsShow">
        <el-table :data="listData" :class="['advanceOptionsTable']" max-height="250">
          <el-table-column label="名称">
            <template slot-scope="scope">
              <el-input placeholder="例：建筑金额" v-model="scope.row.name" :readonly="!edit"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="内容">
            <template slot-scope="scope">
              <el-input placeholder="例：14" v-model="scope.row.value" :readonly="!edit"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单位">
            <template slot-scope="scope">
              <el-input placeholder="例：万元" v-model="scope.row.unit" :readonly="!edit"></el-input>
            </template>
          </el-table-column>

          <el-table-column align="right" v-if="edit">
            <template slot="header">
              <el-button size="mini" @click="addAdvancedOptionsRow()">
                <i class="el-icon-plus"></i>
              </el-button>
            </template>
            <template slot-scope="scope">
              <el-button size="mini" @click="deleteAdvancedOptionsRow(scope.$index, scope)">
                <i class="el-icon-minus"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 高级选项 table end -->
    </el-form>
    <!-- centerPoint: centerPoint, -->
    <CenterLocation1 v-if="isShowUpdateCenterDialog" v-bind="{
      isShow: isShowUpdateCenterDialog,
      title: '中心点修改',
      centerPoint: centerPoint,
      beforeClose: beforeCloseUpdateCenterDialog,
      updateData: updateDataCenterLocation,
    }"></CenterLocation1>

    <CenterLocation2 v-if="isShowUpdateGeometryDialog" v-bind="{
      isShow: isShowUpdateGeometryDialog,
      title: '点集',
      geometry: geometry,
      drawType: modelParams.type,
      beforeClose: beforeCloseUpdateGeometryDialog,
      updateData: updateDataGeometryLocation,
    }"></CenterLocation2>

    <span slot="title" class="dialog-title">
      <div class="title">
        <span>{{ title }}</span>
      </div>
    </span>
    <span slot="footer" class="dialog-footer" v-if="edit">
      <el-button @click="dialogBeforeClose()">取 消</el-button>
      <el-button type="primary" @click="sure">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import api from "@/api/content";
export default {
  components: {
    CenterLocation1: () => import("@/components/Map/CenterLocation.vue"),
    CenterLocation2: () => import("@/components/Map/CenterLocation.vue"),
  },
  props: {
    isShow: {
      type: Boolean,
      default: false,
    },
    edit: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "",
    },
    beforeClose: {
      type: Function,
    },
    updateData: {
      type: Function,
    },
    modelParams: {
      type: Object,
      default: null,
    },
    formData: {
      type: Object,
      default: function () {
        return {
          // modelId:"",
          threeId: "",
          tableName: "",
          type: 0,
          title: "",
          content: "",
          centerLon: "",
          centerLat: "",
          locations: "",
          jsonStr: "",
          areaCode: "",
          richText: "",
          extend1: "",
          extend2: "",
          extend3: "",
        };
      },
    },
  },
  data() {
    var checkLon = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("中心经度不能为空"));
      }
      setTimeout(() => {
        if (isNaN(value)) {
          callback(new Error("请输入数字值"));
        } else {
          callback();
        }
      }, 100);
    };
    var checkLat = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("中心纬度不能为空"));
      }
      setTimeout(() => {
        if (isNaN(value)) {
          callback(new Error("请输入数字值"));
        } else {
          callback();
        }
      }, 100);
    };
    return {
      fromDataRender: {
        // modelId:"",
        threeId: "",
        tableName: "",
        type: 0,
        title: "",
        content: "",
        centerLon: "",
        centerLat: "",
        locations: "",
        jsonStr: "",
        areaCode: "",
        richText: "",
        extend1: "",
        extend2: "",
        extend3: "",
      },
      geoTypeArr: [
        {
          name: "点",
          value: 0,
        },
        {
          name: "线",
          value: 1,
        },
        {
          name: "面",
          value: 2,
        },
      ],
      listData: [],
      rules: {
        title: [{ required: true, message: "请输入名称", trigger: "blur" }],

        centerLon: [
          { required: true, message: "请填写中心点经度", trigger: "blur" },
          { validator: checkLon, trigger: 'blur' }
          // { type: "number", message: "中心经度必须数字值" },
        ],
        centerLat: [
          { required: true, message: "请填写中心点纬度", trigger: "blur" },
          { validator: checkLat, trigger: 'blur' }
          // { type: "number", message: "中心纬度必须数字值" },
        ],
        threeId: [
          { required: true, message: "请输入第三方ID", trigger: "blur" },
        ],
        tableName: [
          { required: true, message: "请输入第三方表名", trigger: "blur" },
        ],
        content: [{ required: true, message: "请填写描述", trigger: "blur" }],
      },
      isShowUpdateCenterDialog: false,
      centerPoint: [],
      tableData: [{}],
      advancedOptionsShow: false,

      isShowUpdateGeometryDialog: false,
      geometry: null,
    };
  },
  methods: {
    // 创建
    sure() {
      let that = this;
      if (this.listData.length > 0) {
        let judge = this.listData.every(function (item) {
          return item.name != "" && item.value != ""; // && item.unit;
        });
        if (!judge) {
          this.$message({
            type: "error",
            message: "高级选项相关内容未填写完整，请完善后重新提交！",
          });
          return;
        }
      }

      this.$refs["single_form"].validate((valid) => {
        if (valid) {
          let data;
          if (that.modelParams) {
            data = Object.assign({}, that.fromDataRender, that.modelParams);
            data.jsonStr = JSON.stringify(that.listData);
            if (data.type == 0)
              data.locations =
                "POINT (" + data.centerLon + " " + data.centerLat + ")";
            that.addSingleData(data);
          } else {
            data = Object.assign({}, that.fromDataRender);
            data.jsonStr = JSON.stringify(that.listData);
            delete data.updateDate;
            delete data.createDate;
            that.updateSingleData(data);
          }
        } else {
          that.$message({
            type: "error",
            message: "信息填写有误，请修改后提交",
          });
          return false;
        }
      });
    },

    // 创建
    addSingleData(data) {
      let that = this;
      // 上传loading
      const loading = that.$loading({
        customClass: "allPageLoading",
        lock: true,
        text: "数据新增中，请勿刷新！",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      api
        .addSingleData(data)
        .then((result) => {
          if (result.code == 200) {
            loading.close();
            that.$message({
              type: "success",
              message: "数据增加成功！",
            });
            if (that.updateData) that.updateData();
            that.dialogBeforeClose();
          } else {
            checkRequestCode(result);
          }
        })
        .catch((err) => {
          loading.close();
          that.$message({
            type: "error",
            message: err,
          });
        });
    },

    // 更新
    updateSingleData(data) {
      let that = this;
      // 上传loading
      const loading = that.$loading({
        customClass: "allPageLoading",
        lock: true,
        text: "数据更新中，请勿刷新！",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      api
        .updateSingleData(data)
        .then((result) => {
          if (result.code == 200) {
            loading.close();
            that.$message({
              type: "success",
              message: "数据更新成功！",
            });
            if (that.updateData) that.updateData();
            that.dialogBeforeClose();
          } else {
            checkRequestCode(result);
          }
        })
        .catch((err) => {
          that.$message({
            type: "error",
            message: err,
          });
        });
    },

    // 创建数据集窗口关闭前
    dialogBeforeClose() {
      this.fromDataRender = {
        // modelId:"",
        threeId: "",
        tableName: "",
        type: 0,
        title: "",
        content: "",
        centerLon: "",
        centerLat: "",
        locations: "",
        jsonStr: "",
        areaCode: "",
        richText: "",
        extend1: "",
        extend2: "",
        extend3: "",
      };
      this.advancedOptionsShow = false;
      this.clearAdvancedOptions();
      this.beforeClose();
      this.$refs.single_form.clearValidate();
    },

    // 打开 更新/新建 中心点 面板
    openCenterLocation(item) {
      // Terraformer.WKT.parse(wktData[0])
      // debugger
      if (!isNaN(Number(item.centerLon)) && !isNaN(Number(item.centerLat))) {
        this.centerPoint = [item.centerLon, item.centerLat];
        this.isShowUpdateCenterDialog = true;
      } else {
        that.$message({
          type: "warning",
          message: "当前坐标有误，请正确填写后查看或修改位置"
        })
      }

    },

    // 更新 中心点
    updateDataCenterLocation(item) {
      this.fromDataRender.centerLon = item[0];
      this.fromDataRender.centerLat = item[1];
    },

    // 关闭 中心点修改
    beforeCloseUpdateCenterDialog() {
      this.isShowUpdateCenterDialog = false;
    },

    // 打开 更新/新建 点集 面板
    openGeometryLocation(item) {
      this.geometry = item.locations;
      this.isShowUpdateCenterDialog = true;
    },

    // 更新 点集
    updateDataGeometryLocation(item) {
      this.fromDataRender.locations = item
    },

    // 关闭 点集修改
    beforeCloseUpdateGeometryDialog() {
      this.isShowUpdateCenterDialog = false;
    },

    // 更改高级选项显示状态
    changeAdvancedOptionsStatue() {
      this.advancedOptionsShow = !this.advancedOptionsShow;
    },

    // 添加 高级选项input 按钮
    addAdvancedOptionsRow() {
      this.listData.push({
        name: "",
        value: "",
        unit: "",
      });
    },
    // 删除 高级选项input 按钮
    deleteAdvancedOptionsRow(index) {
      this.listData.splice(index, 1);
    },

    // 清空高级选项
    clearAdvancedOptions() {
      this.listData = [];
    },
  },

  watch: {
    isShow(newVal, oldVal) {
      if (newVal) {
        this.fromDataRender = this.formData;
        if (this.formData.jsonStr.length != 0) {
          this.advancedOptionsShow = true;
          this.listData = JSON.parse(this.formData.jsonStr);
        } else {
          this.advancedOptionsShow = false;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.singleDataDialog {
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
    padding: 15px;
  }

  .title {
    height: 30px;
    line-height: 30px;
    font-size: 20px;
    font-weight: bold;
  }

  /deep/ .el-dialog__body {
    padding-top: 20px;
    padding-bottom: 20px;
  }

  /deep/ .el-dialog__footer {
    border-top: 1px solid #eeeeee;
    padding: 10px 20px;
  }

  .el-form-item {
    /deep/ .el-form-item__label {
      width: 100px !important;
    }

    /deep/ .el-form-item__content {
      margin-left: 100px !important;
    }
  }

  .advanceOptionsTable {
    border: 1px solid #eeeeee;
    border-bottom: 0px solid #eeeeee;
    margin-top: 20px;
  }

  /deep/ .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before {
    content: " ";
    width: 0px;
    margin-right: 0px;
  }

  .is-required /deep/.el-form-item__label:after {
    content: " *";
    color: #3f9dfe;
    font-size: 150%;
  }
}
</style>