
<style scoped>
.user-panel {
  margin: 10px auto;
}
</style>
<template>
  <el-dialog
    top="5vh"
    :visible.sync="showDialog"
    :title="title"
    :modal-append-to-body="false"
    style="text-align: left"
    width="800px"
    @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'"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属公司" prop="companyId">
              <el-select-tree
                :props="props"
                :options="companyResult"
                v-model="formModel.companyId"
                size="mediumn"
                width="200px"
              ></el-select-tree>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线路" prop="routeId">
              <el-select
                v-model="formModel.routeId"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in routeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车牌号" prop="licensePlateNumber">
              <el-input
                v-model="formModel.licensePlateNumber"
                placeholder="请输入车牌号"
                style="width: 200px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="gps设备编号" prop="gpsDeviceNo">
              <el-input
                v-model="formModel.gpsDeviceNo"
                placeholder="请输入gps设备编号"
                style="width: 200px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="打卡设备编号" prop="deviceNo">
              <el-input
                v-model="formModel.deviceNo"
                placeholder="请输入打卡设备编号"
                style="width: 200px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="平板设备编号" prop="activationCode">
            <el-input
              v-model="formModel.activationCode"
              placeholder="请输入激活码"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="荷载人数" prop="loadNumber">
              <el-input
                v-model="formModel.loadNumber"
                type="number"
                placeholder="请输入荷载人数"
                style="width: 200px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="轨迹间隔(秒)" prop="trailInterval">
              <el-input
                v-model="formModel.trailInterval"
                type="number"
                placeholder="请输入轨迹间隔"
                style="width: 200px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="车辆照片" prop="picture">
              <el-upload
                class="avatar-uploader"
                name="photoFile"
                :action="uploadUrl"
                :show-file-list="false"
                :headers="headers"
                :data="uploadData"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="fileUrl" :src="fileUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </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>
</template>
<script>
import Constant from "@/constant";
import vehicleInfoApi from "@/api/bus/vehicleInfo";
import SelectTree from "@/components/SelectTree";
import companyInfoApi from "@/api/bus/companyInfo";
import routeInfoApi from "@/api/bus/routeInfo";

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

export default {
  props: ["businessKey", "title"],
  data() {
    return {
      formModel: {
        enableChangeParent: false,
      },
      ruleValidate: {
        companyId: [
          { required: true, message: "所属单位不能为空", trigger: "blur" },
        ],
        licensePlateNumber: [
          { required: true, message: "车牌号不能为空", trigger: "blur" },
        ],
        gpsDeviceNo: [
          { required: true, message: "gps设备号不能为空", trigger: "blur" },
        ],
        deviceNo: [
          { required: true, message: "打卡设备编号不能为空", trigger: "blur" },
        ],
        activationCode: [
          { required: true, message: "激活码不能为空", trigger: "blur" },
        ],
        routeId:[
          { required: true, message: "线路不能为空", trigger: "blur" },
        ],
      },
      showDialog: true,
      loading: false,
      submitting: false,
      //上传地址
      uploadUrl: Constant.serverUrl + "/uploadPicture",
      uploadData: {
        subFolder: "vehicleInfo",
      },
      fileUrl: "",
      headers: {
        Authorization: getToken(),
      },
      companyResult: [],
      typeData: [],
      treeData: [],
      props: {
        // 配置项（必选）
        value: "id",
        label: "name",
        children: "children",
      },
      sceneData: [],
      regionData: [],
      routeList: [],
    };
  },
  watch: {
    "formModel.companyId"(newVal, oldVal) {
      var formData = new FormData();
      formData.append("companyId", newVal);
      routeInfoApi.list(formData).then((response) => {
        var jsonData = response.data;
        this.routeList = jsonData.data;
      });
    },
  },
  created() {
    var self = this;

    companyInfoApi.treeList().then(function (response) {
      var jsonData = response.data;
      if (jsonData.result) {
        self.companyResult = 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 vehicleInfoApi.add(self.formModel);
            } else {
              return vehicleInfoApi.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;
    },
  },
  components: {
    "el-select-tree": SelectTree,
  },
  mounted: function () {
    var self = this;
    (function () {
      if (self.businessKey.length == 0) {
        return vehicleInfoApi.create();
      } else {
        return vehicleInfoApi.edit(self.businessKey);
      }
    })()
      .then((response) => {
        var jsonData = response.data;
        self.loading = false;

        if (jsonData.result) {
          self.formModel = jsonData.data;
          let picture = self.formModel.picture;
          if (picture != null) {
            self.fileUrl =
              picture + "?x-oss-process=image/resize,m_lfit,h_400,w_400";
          }

          var formData = new FormData();
          formData.append("companyId", self.formModel.companyId);
          routeInfoApi.list(formData).then((response) => {
            var jsonData = response.data;
            this.routeList = jsonData.data;
          });
        } else {
          self.$message.error(jsonData.message + "");
        }
      })
      .catch((error) => {
        self.$message.error(error + "");
      });
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>