
<style scoped>
.user-panel {
  margin: 10px auto;
}
</style>
<template>
  <div>
    <el-dialog
      :visible.sync="showDialog"
      :title="title"
      :modal-append-to-body="false"
      style="text-align: left"
      width="1200px"
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <div class="user-panel" v-loading="loading">
        <el-form
          ref="form"
          :model="formModel"
          :rules="ruleValidate"
          :label-width="'130px'"
          :inline="true"
        >
          <el-form-item label="所属公司" prop="companyId">
            <el-select-tree
              :props="props"
              :options="companyResult"
              v-model="formModel.companyId"
              size="mediumn"
              width="400px"
            ></el-select-tree>
          </el-form-item>
          <el-form-item label="地区" prop="regionId">
            <el-select-tree
              :props="props"
              :options="regionData"
              v-model="formModel.regionId"
              size="mediumn"
              width="400px"
            ></el-select-tree>
          </el-form-item>

          <el-form-item label="路线名称" prop="name">
            <el-input
              v-model="formModel.name"
              placeholder="请输入路线名称"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-time-picker
              v-model="formModel.startTime"
              class="date-box"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 400px"
              :picker-options="{
                selectableRange: `00:00:00 -${
                  formModel.endTime ? formModel.endTime + ':00' : '23:59:00'
                }`,
              }"
            ></el-time-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-time-picker
              v-model="formModel.endTime"
              class="date-box"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 400px"
              :picker-options="{
                selectableRange: `${
                  formModel.startTime ? formModel.startTime + ':00' : '00:00:00'
                }-23:59:00`,
              }"
            ></el-time-picker>
          </el-form-item>
          <el-form-item label="间隔时间(分钟)" prop="interval">
            <el-input-number
              v-model="formModel.interval"
              placeholder="请输入间隔时间"
              style="width: 400px"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <h3>车辆站点信息</h3>
          <el-divider></el-divider>
          <el-row class="button-group">
            <el-button
              type="primary"
              size="small"
              plain
              icon="el-icon-upload2"
              @click="batchImportVisible = true"
              >导入站点</el-button
            >
          </el-row>
          <el-table :data="formModel.stationList">
            <el-table-column
              type="index"
              label="序号"
              width="55"
            ></el-table-column>
            <el-table-column prop="name" label="站点名称" width="300px">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'stationList.' + scope.$index + '.name'"
                  :rules="ruleValidate['name']"
                >
                  <el-input
                    placeholder="站点名称"
                    v-model="scope.row.name"
                    style="width: 250px"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="classify" label="站点类型" width="130px">
              <template slot-scope="{ row }">
                <el-form-item>
                  <el-select
                    v-model="row.classify"
                    placeholder="请选择"
                    style="width: 120px"
                  >
                    <el-option
                      v-for="result in stationClassify"
                      :key="result.id"
                      :label="result.name"
                      :value="result.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="location" label="站点定位">
              <template slot-scope="{ row }">
                <el-form-item>
                  <el-input
                    placeholder="经纬度"
                    style="width: 200px"
                    v-model="row.location"
                  ></el-input>
                  <i
                    class="el-icon-map-location my-font"
                    @click="handleLocation(row)"
                  ></i>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="半径(米)" width="120px">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'stationList.' + scope.$index + '.radius'"
                  :rules="ruleValidate['radius']"
                >
                  <el-input
                    placeholder="半径"
                    v-model="scope.row.radius"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="{ row }">
                <el-form-item>
                  <i
                    class="el-icon-delete my-font"
                    @click="handleDelete(row)"
                  ></i>
                  <i class="el-icon-top my-font" @click="handleUp(row)"></i>
                  <i
                    class="el-icon-bottom my-font"
                    @click="handleDown(row)"
                  ></i>
                  <i
                    class="el-icon-document-add my-font"
                    @click="handleInsert(row)"
                  ></i>
                </el-form-item>
              </template>
            </el-table-column>
            <div slot="empty">
              <el-button
                icon="el-icon-circle-plus-outline"
                :plain="true"
                @click="handleAdd()"
                >新增</el-button
              >
            </div>
          </el-table>
        </el-form>
        <div
          class="el-table__empty-block"
          v-if="formModel.stationList.length != 0"
        >
          <el-button icon="el-icon-circle-plus-outline" @click="handleAdd()"
            >新增</el-button
          >
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="showMapDialog"
      title="地图选点"
      :modal-append-to-body="true"
      :append-to-body="true"
      style="text-align: left"
      :close-on-click-modal="false"
    >
      <el-amap
        ref="stationMap"
        vid="stationMap"
        :amap-manager="amapManager"
        :center="pointPosition"
        :zoom="zoom"
        :events="events"
        class="amap-demo"
      >
        <el-amap-marker
          vid="amapDemo"
          :position="pointPosition"
        ></el-amap-marker>
      </el-amap>
      <span slot="footer" class="dialog-footer">
        <div style="position: absolute; left: 20px; bottom: 20px">
          <el-input
            placeholder="当前经纬度"
            v-model="selectedRow.location"
            style="width: 400px"
          >
            <template slot="prepend">经纬度</template>
            <el-button slot="append" icon="el-icon-search" @click="handleRegeo"
              >定位</el-button
            >
          </el-input>
        </div>
        <el-button @click="showMapDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleSelectPoint()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="导入"
      :visible.sync="batchImportVisible"
      :modal-append-to-body="false"
      style="text-align: left"
      :close-on-click-modal="false"
    >
      <el-form label-width="150px">
        <el-form-item label="模板下载">
          <el-link
            href="http://rccs.oss-cn-hangzhou.aliyuncs.com/smart-bus/excel/stationInfo.xls"
            type="primary"
            target="_blank"
            >点击下载模板</el-link
          >
        </el-form-item>
        <el-form-item label="上传文件">
          <el-upload
            class="upload-demo"
            accept=".xls"
            :action="uploadUrlXls"
            :data="uploadXlsData"
            :headers="headers"
            :on-preview="handleBatchImportPreview"
            name="uploadFile"
            :multiple="true"
            :limit="1"
            :on-remove="handleBatchImportRemove"
            :before-remove="beforeBatchImportRemove"
            :before-upload="beforeUpload"
            :on-exceed="handleBatchImportExceed"
            :on-success="handleBatchImportSuccess"
            :file-list="batchImportFileList"
          >
            <el-button size="small" type="primary" :loading="xlsLoading"
              >点击上传</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传xls文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="batchImportVisible = false"
          >关 闭</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Constant from "@/constant";
import routeInfoApi from "@/api/bus/routeInfo";
import SelectTree from "@/components/SelectTree";
import companyInfoApi from "@/api/bus/companyInfo";
import dataDictionaryApi from "@/api/sys/dataDictionary";
import regionInfoApi from "@/api/base/regionInfo";

import { getToken } from "@/utils/auth"; // get token from cookie

import AMap from "vue-amap";
let amapManager = new AMap.AMapManager();

export default {
  props: ["businessKey", "title"],
  data() {
    return {
      formModel: {
        enableChangeParent: false,
        id: "",
        name: "",
        companyId: "",
        goodsId: "",
        stationList: [],
        removeStationList: [],
      },
      ruleValidate: {
        companyId: [
          { required: true, message: "所属单位不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "车牌号不能为空", trigger: "blur" }],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
        ],
        regionId: [
          { required: true, message: "地区不能为空", trigger: "blur" },
        ],
        interval: [
          { required: true, message: "间隔时间不能为空", trigger: "blur" },
        ],
        radius: [{ required: true, message: "半径不能为空", trigger: "blur" }],
      },
      showDialog: true,
      loading: false,
      submitting: false,
      stationClassify: [],
      //上传地址
      uploadUrl: Constant.serverUrl + "/uploadPicture",
      uploadData: {
        subFolder: "vehicleInfo",
      },
      fileUrl: "",
      headers: {
        Authorization: getToken(),
      },
      companyResult: [],
      typeData: [],
      treeData: [],
      selectedRow: {},
      pointPosition: [112.240222, 30.337053],
      showMapDialog: false,
      amapManager,
      zoom: 12,
      events: {
        click: (e) => {
          var pt = e.lnglat; //点击选择新地址为中心点
          console.log(pt);

          this.pointPosition = [pt.lng, pt.lat];
          this.selectedRow.location = pt.lng + "," + pt.lat;
        },
      },
      props: {
        // 配置项（必选）
        value: "id",
        label: "name",
        children: "children",
      },
      uploadUrlXls: Constant.serverUrl + "/bus/stationInfo/importXls",
      uploadXlsData: {
        subFolder: "station",
        routeId: this.businessKey,
      },
      sceneData: [],
      regionData: [],
      batchImportVisible: false,
      batchImportFileList: [],
      xlsLoading: false,
    };
  },
  created() {
    var self = this;

    var formData = new FormData();
    formData.append("catalogName", "站点类型");

    dataDictionaryApi.findByCatalogName(formData).then((response) => {
      var jsonData = response.data;
      this.stationClassify = jsonData.data;
    });

    companyInfoApi.treeList().then(function (response) {
      var jsonData = response.data;
      if (jsonData.result) {
        self.companyResult = jsonData.data;
      }
    });

    regionInfoApi.list().then((response) => {
      var jsonData = response.data;
      this.regionData = jsonData.data;
    });
  },
  methods: {
    closeDialog() {
      this.$emit("close", false);
    },
    handleSubmit() {
      var self = this;

      this.$refs["form"].validate((valid) => {
        if (valid) {
          (function () {
            var id = self.formModel.id;

            if (self.formModel.parentId == null) {
              self.formModel.parentId = "";
            }

            if (self.formModel.relationCompanyId == null) {
              self.formModel.relationCompanyId = "";
            }

            if (id == null || id.length == 0) {
              return routeInfoApi.add(self.formModel);
            } else {
              return routeInfoApi.update(self.formModel);
            }
          })().then(function (response) {
            var jsonData = response.data;

            if (jsonData.result) {
              self.$message({
                message: "保存成功!",
                type: "success",
              });

              self.$emit("close", true);
            } else {
              self.$message({
                message: jsonData.message + "",
                type: "warning",
              });

              self.$emit("close", false);
            }
          });
        }
      });
    },
    handleAvatarSuccess(res, file) {
      var self = this;
      self.formModel.picture = res.data;
      self.fileUrl =
        res.data + "?x-oss-process=image/resize,m_lfit,h_400,w_400";
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleLocation(row) {
      this.selectedRow = row;
      this.showMapDialog = true;

      if (row.location != null && row.location.length > 0) {
        var arr = row.location.split(",");

        this.pointPosition = arr;
      }
    },
    handleAdd() {
      this.formModel.stationList.push({
        sortNo: this.formModel.stationList.length + 1,
        name: "",
        routeId: this.businessKey,
        classify: "",
        location: "",
        delFlag: 0,
      });
    },
    handleInsert(row) {
      var stationList = this.formModel.stationList;
      var index = stationList.indexOf(row);

      if (index >= 0) {
        stationList.splice(index + 1, 0, {
          sortNo: index + 2,
          name: "",
          routeId: this.businessKey,
          classify: "",
          location: "",
          delFlag: 0,
        });
      }
    },
    handleRegeo() {
      var row = this.selectedRow;

      if (row.location != null && row.location.length > 0) {
        var arr = row.location.split(",");
        this.pointPosition = arr;
      }
    },
    handleSelectPoint() {
      this.selectedRow.location =
        this.pointPosition[0] + "," + this.pointPosition[1];
      this.showMapDialog = false;
    },
    handleDelete(row) {
      var stationList = this.formModel.stationList;

      stationList.splice(stationList.indexOf(row), 1);

      this.formModel.removeStationList.push(row);
    },
    handleUp(row) {
      var stationList = this.formModel.stationList;
      var index = stationList.indexOf(row);

      if (index > 0) {
        stationList.splice(index, 1);
        stationList.splice(index - 1, 0, row);
      }
    },
    handleDown(row) {
      var stationList = this.formModel.stationList;
      var index = stationList.indexOf(row);

      if (index < stationList.length - 1) {
        stationList.splice(index, 1);
        stationList.splice(index + 1, 0, row);
      }
    },
    beforeUpload(file, fileList) {
      //导入前判断
    },
    //批量导入-上传成功
    handleBatchImportSuccess(response, file, fileList) {
      var self = this;
      self.xlsLoading = false;
      if (response.result) {
        self.$message.success(response.message);
        this.batchImportFileList = [];
        this.refurbishList();
        this.uploadCompanyId = "";
        this.uploadXlsData.companyId = "";
        this.batchImportVisible = false;
      } else {
        //this.$message.error(response.message);
        this.refurbishList();
        this.batchImportFileList = [];
        this.uploadCompanyId = "";
        this.uploadXlsData.companyId = "";

        if (response.data != null) {
          //下载有错误信息提示的报表
          //window.open(response.data);
          self.$message({
            showClose: true,
            dangerouslyUseHTMLString: true,
            message:
              response.message +
              `,<a href="${response.data}" target="_blank">点击下载未导入的数据报表</a>&nbsp;`,
            duration: 30000,
          });
        }
      }
    },
    //批量导入-预览
    handleBatchImportPreview(file) {
      console.log(file.url);
    },
    //批量导入-移除
    handleBatchImportRemove(file, fileList) {
      console.log(file, fileList);
    },
    //批量导入-移除前操作
    beforeBatchImportRemove(file, fileList) {
      console.log(file, fileList);
    },
    //批量导入-文件超出个数限制时的钩子
    handleBatchImportExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    refurbishList() {
      var self = this;
      (function () {
        if (self.businessKey.length == 0) {
          return routeInfoApi.create();
        } else {
          return routeInfoApi.edit(self.businessKey);
        }
      })()
        .then((response) => {
          var jsonData = response.data;
          self.loading = false;

          if (jsonData.result) {
            self.formModel = jsonData.data;
          } else {
            self.$message.error(jsonData.message + "");
          }
        })
        .catch((error) => {
          self.$message.error(error + "");
        });
    },
  },
  components: {
    "el-select-tree": SelectTree,
  },
  mounted: function () {
    var self = this;
    (function () {
      if (self.businessKey.length == 0) {
        return routeInfoApi.create();
      } else {
        return routeInfoApi.edit(self.businessKey);
      }
    })()
      .then((response) => {
        var jsonData = response.data;
        self.loading = false;

        if (jsonData.result) {
          self.formModel = jsonData.data;
          if (self.formModel.interval == null) {
            self.formModel.interval = 40;
          }
        } else {
          self.$message.error(jsonData.message + "");
        }
      })
      .catch((error) => {
        self.$message.error(error + "");
      });
  },
};
</script>
<style scoped>
.user-panel {
  margin: 10px auto;
}

.amap-demo {
  width: 100%;
  height: 400px;
}

.my-font {
  font-size: 20px;
  cursor: pointer;
  margin-right: 10px;
}
</style>