<!--
 * @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="病害位置">
        <div ref="addMap" id="addMap" class="no-hand-cursor"></div>
      </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";

export default {
  name: "RoadAdd",
  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: [],
      },
      // 地图中心点
      centerPoint: [123.30297096718999, 41.87942945541742],
      // 点击坐标
      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 e = {
              lnglat: {
                lng: val.geometry.coordinates[0],
                lat: val.geometry.coordinates[1],
              },
            };
            this.onMapClick(e);
          });
        }
      },
      immediate: true,
      deep: true,
    },
  },
  /* 生命周期函数-mouted */
  mounted() {
    this.initMap();
  },
  methods: {
    /* 文件提交处理 */
    submitUpload() {
      this.$refs.upload.submit();
    },
    /* 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /* 文件上传成功处理 */
    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;
    },
    /* 点击确定事件 */
    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[0].lng, this.markers[0].lat],
              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("新增失败");
              });
          }
        }
      });
    },
    /* 点击取消事件 */
    cancel() {
      this.$emit("cancel");
    },
    /* 初始化天地图 */
    initMap() {
      // 初始化天地图
      this.map = new T.Map("addMap");
      this.map.centerAndZoom(
        new T.LngLat(this.centerPoint[0], this.centerPoint[1]),
        9
      );
      // 添加单击事件
      this.map.on("click", this.onMapClick);
    },
    /* 新增/编辑地图单击事件 */
    onMapClick(e) {
      const marker = new T.Marker(e.lnglat);
      if (this.markers.length > 0) {
        this.markers.shift();
        this.map.clearOverLays();
        this.map.addOverLay(marker);
        this.markers.push(e.lnglat);
      } else {
        this.map.addOverLay(marker);
        this.markers.push(e.lnglat);
      }
    },
  },
};
</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>