<!--
 * @Author: SunTao 328867980@qq.com
 * @Date: 2024-10-11 16:52:24
 * @LastEditors: SunTao 328867980@qq.com
 * @LastEditTime: 2024-11-05 15:18:59
 * @FilePath: \znxjxt-ui\src\views\xj\inspection\road-management\components\road-add.vue
 * @Description: 路产管理-新增/编辑弹窗
-->

<template>
  <div class="add-content">
    <el-form
      class="addForm"
      ref="roadForm"
      :model="roadForm"
      :rules="rules"
      label-width="100px"
    >
      <el-row :gutter="24">
        <el-col :span="dialogItem.title === '添加路产' ? 12 : 24">
          <el-form-item label="道路名称" prop="segmentId">
            <el-select
              v-model="roadForm.segmentId"
              placeholder="请选择路段"
              clearable
            >
              <el-option
                v-for="item in segmentList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="dialogItem.title === '添加路产'">
          <el-form-item label="路产类型" prop="equipmentType">
            <el-select
              v-model="roadForm.equipmentType"
              placeholder="请选择路产类型"
              clearable
            >
              <el-option
                v-for="item in roadType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <!-- <el-col :span="12">
          <el-form-item label="校验状态" prop="dataStatus">
            <el-select
              v-model="roadForm.dataStatus"
              placeholder="请选择校验状态"
              clearable
            >
              <el-option
                v-for="item in states"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="上下行" prop="inspectDirection">
            <el-select
              v-model="roadForm.inspectDirection"
              placeholder="请选择上下行"
              clearable
            >
              <el-option label="上行" value="0" />
              <el-option label="下行" value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="路产状态" prop="state">
            <el-select
              v-model="roadForm.state"
              placeholder="请选择路产状态"
              clearable
            >
              <el-option
                v-for="item in defectStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="开始桩号" prop="stakeStart">
            <el-input
              v-model="roadForm.stakeStart"
              placeholder="请输入开始桩号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束桩号" prop="stakeEnd">
            <el-input
              v-model="roadForm.stakeEnd"
              placeholder="请输入结束桩号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="病害位置">
        <fssm-map
          ref="addMap"
          @map-click="getMapClick"
          class="no-hand-cursor"
        ></fssm-map>
      </el-form-item>
      <el-form-item label="上传病害图片">
        <el-upload
          ref="upload"
          accept=".jpg, .png"
          :action="upload.url"
          :headers="upload.headers"
          :file-list="upload.fileList"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          list-type="picture"
        >
          <el-button slot="trigger" size="small" type="primary"
            >选取文件</el-button
          >
          <el-button
            style="margin-left: 1rem"
            size="small"
            type="success"
            :loading="upload.isUploading"
            @click="submitUpload"
            >上传到服务器</el-button
          >
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { addRoad, uploadRoad } from "@/api/xj/road";
import { getToken } from "@/utils/auth";
// 地图
import FssmMap from "@/components/map/fssm-map.vue";
import { Feature } from "ol";
import { Point } from "ol/geom";
import { Style } from "ol/style";
import * as styleExports from "ol/style";
import VectorLayer from "ol/layer/Vector";
import { Vector as VectorSource } from "ol/source";

export default {
  name: "RoadAdd",
  components: {
    FssmMap,
  },
  props: {
    dialogItem: {
      type: Object,
      require: true,
      default: () => {},
    },
    segmentList: {
      type: Array,
      require: true,
    },
    defectStatus: {
      type: Array,
      require: true,
    },
    roadType: {
      type: Array,
      require: true,
    },
  },
  data() {
    return {
      // 表单绑定
      roadForm: {},
      // 校验状态下拉数据
      states: [
        {
          label: "未校验",
          value: "1",
        },
        {
          label: "已校验",
          value: "2",
        },
      ],
      // 表单校验规则
      rules: {
        segmentId: [
          { required: true, message: "请选择路段", trigger: "change" },
        ],
        equipmentType: [
          { required: true, message: "请选择路产类型", trigger: "change" },
        ],
        state: [
          { required: true, message: "请选择路产状态", trigger: "change" },
        ],
        dataStatus: [
          { required: true, message: "请选择校验状态", trigger: "change" },
        ],
        stakeStart: [
          { required: true, message: "请输入开始桩号", trigger: "blur" },
          {
            pattern: /^K\d{4}\+\d{3}$/,
            message: "请按照K0000+000格式进行填写",
          },
        ],
        stakeEnd: [
          { required: true, message: "请输入结束桩号", trigger: "blur" },
          {
            pattern: /^K\d{4}\+\d{3}$/,
            message: "请按照K0000+000格式进行填写",
          },
        ],
        targetLen: [
          { required: true, message: "请填写病害长度", trigger: "blur" },
          {
            type: "number",
            min: 0,
            message: "病害长度必须为正数",
            trigger: "change",
          },
        ],
        targetArea: [
          { required: true, message: "请填写病害面积", trigger: "blur" },
          {
            type: "number",
            min: 0,
            message: "病害面积必须为正数",
            trigger: "change",
          },
        ],
        inspectDirection: [
          { required: true, message: "请选择上下行", trigger: "change" },
        ],
      },
      // 上传参数设置
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
      },
      // 点击坐标
      markers: [],
    };
  },
  /* 监听传过来的弹窗数据 */
  watch: {
    dialogItem: {
      handler(val) {
        if (val.title === "修改路产") {
          this.roadForm = JSON.parse(JSON.stringify(val));
          this.upload.fileList = val.media.map((item) => {
            return {
              ...item,
              url: item.img,
            };
          });
          this.$nextTick(() => {
            const map = this.$refs.addMap.instance.get("map");
            map.getView().setCenter(val.geometry.coordinates);
            this.markers = val.geometry.coordinates;
            this.drawMapPoint();
          });
        }
      },
      immediate: true,
      deep: true,
    },
  },
  /**
   * @description: 生命周期函数-mouted
   * @return {*}
   */
  mounted() {},
  methods: {
    /**
     * @description: 传回来的地图点击事件获取点位数据
     * @param {*} e
     * @return {*}
     */
    getMapClick(e) {
      const map = this.$refs.addMap.instance.get("map");
      map.removeLayer(this.markLayerPoints);
      const { coordinate } = e;
      this.markers = coordinate;
      this.drawMapPoint();
    },

    /**
     * @description: 绘制地图点位
     * @param {*} val
     * @return {*}
     */
    drawMapPoint() {
      const features = [];
      const point = new Point(this.markers); // 修改坐标格式
      const feature = new Feature({
        geometry: point,
        type: "icon", //  自己设置一个标识
      });
      feature.setStyle([
        new Style({
          image: new styleExports.Circle({
            //点样式
            radius: 6,
            stroke: new styleExports.Stroke({
              color: "#9a9c9e",
              width: 4,
            }),
            fill: new styleExports.Fill({
              color: "blue",
            }),
          }),
        }),
      ]);
      features.push(feature);
      //设置地图的数据源
      const pointSource = new VectorSource({
        features,
      });
      this.markLayerPoints = new VectorLayer({
        source: pointSource,
        properties: {
          type: "point",
        },
      });
      this.$nextTick(() => {
        const map = this.$refs.addMap.instance.get("map");
        map.addLayer(this.markLayerPoints);
      });
    },

    /**
     * @description: 文件提交处理
     * @param {*} e
     * @return {*}
     */
    submitUpload() {
      this.$refs.upload.submit();
    },

    /**
     * @description: 文件上传中处理
     * @param {*} event
     * @param {*} file
     * @param {*} fileList
     * @return {*}
     */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    /**
     * @description: 文件上传成功处理
     * @param {*} response
     * @param {*} file
     * @param {*} fileList
     * @return {*}
     */
    handleFileSuccess(response, file, fileList) {
      this.upload.fileList = fileList.map((item) => {
        if (item.response) {
          return { ...item, img: item.response.url };
        }
        return item;
      });
      this.upload.isUploading = false;
    },

    /**
     * @description: 点击确定事件
     * @return {*}
     */
    submitForm() {
      this.$refs["roadForm"].validate((valid) => {
        if (valid) {
          // 验证点位
          if (this.markers.length < 1) {
            this.$modal.msgWarning("请选择病害位置");
            return false;
          }
          // 验证文件上传列表
          if (this.upload.fileList.length < 1) {
            this.$modal.msgWarning("请上传图片");
            return false;
          }
          const dataItem = {
            ...this.roadForm,
            media: this.upload.fileList.map((item) => {
              return { ...item, img: item.img };
            }),
            geometry: {
              type: "Point",
              coordinates: this.markers,
              id: this.roadForm?.geometry?.id,
            },
          };
          if (this.roadForm.id) {
            // 更新缺陷
            uploadRoad(dataItem)
              .then(({ code, data }) => {
                if (code === 200) {
                  this.$modal.msgSuccess("修改成功");
                  this.$refs["roadForm"].resetFields();
                  this.upload.fileList = [];
                  this.markers = [];
                  this.cancel();
                }
              })
              .catch(() => {
                this.$modal.msgError("修改失败");
              });
          } else {
            // 添加缺陷
            addRoad(dataItem)
              .then(({ code, data }) => {
                if (code === 200) {
                  this.$modal.msgSuccess("新增成功");
                  this.$refs["roadForm"].resetFields();
                  this.upload.fileList = [];
                  this.markers = [];
                  this.cancel();
                }
              })
              .catch(() => {
                this.$modal.msgError("新增失败");
              });
          }
        }
      });
    },

    /**
     * @description: 点击取消事件
     * @return {*}
     */
    cancel() {
      this.$emit("cancel");
    },
  },
};
</script>

<style lang="scss" scoped>
/* 新增弹窗/编辑弹窗 */
.addForm {
  .el-select,
  .el-cascader {
    width: 100%;
  }
}
/* 地图框样式 */
.no-hand-cursor {
  cursor: default !important;
  width: 100%;
  height: 20rem;
}

/* 上传文件列表样式 */
::v-deep .el-upload-list {
  img {
    width: auto;
  }
}

/* 页脚 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>