<template>
  <div class="app-container">
    <div>上传图片</div>
    <el-upload
      :action="actionUrl"
      :headers="headers"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :file-list="fileList"
      style="margin: 10px 0"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <el-form
      :label-position="labelPosition"
      label-width="120px"
      :model="station"
      :rules="rules"
      ref="stationRef"
    >
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="站点名称" prop="stationName">
            <el-input v-model="station.stationName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="area" label="站点区域">
            <!--<el-input v-model="station.areaCode"> </el-input>-->
            <el-cascader
              size="large"
              :options="options"
              v-model="areaCodeList"
              @change="handleChange"
              disabled
            >
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="address" label="地址">
            <el-input v-model="station.address" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="stationTel" label="联系电话">
            <el-input v-model="station.stationTel"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item prop="matchCars" label="适配车辆类型">
            <el-select v-model="station.selectMatchCars" multiple placeholder="请选择">
              <el-option
                v-for="item in dict.type.match_cars"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="publicFlag" label="是否对外开放">
            <el-select v-model="station.publicFlag" placeholder="请选择">
              <el-option
                v-for="item in publicFlagOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="openFlag" label="是否营业中">
            <el-select v-model="station.openFlag" placeholder="请选择">
              <el-option
                v-for="item in openFlagOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="merchantAdminName" label="管理员">
            <el-input
              :value="
                station.merchantAdminName === null
                  ? '无'
                  : station.merchantAdminName
              "
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item prop="stationLng" label="经度">
            <el-input v-model="station.stationLng" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="stationLat" label="纬度">
            <el-input v-model="station.stationLat" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="merchantName" label="运营商">
            <el-input
              :value="
                station.merchantName === null ? '无' : station.merchantName
              "
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="stationType" label="站点类型">
            <el-select v-model="station.stationType" placeholder="请选择">
              <el-option
                v-for="item in dict.type.station_type"
                :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="6">
          <el-form-item prop="construction" label="建设场所">
            <el-select v-model="station.construction" placeholder="请选择">
              <el-option
                v-for="item in dict.type.construction_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="electricityPrice" label="充电费率">
            <el-input
              :value="station.electricityPrice === null ? 0 : station.electricityPrice
              "
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="servicePrice" label="服务费率">
            <el-input
              :value="station.servicePrice === null ? 0 : station.servicePrice"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="businessHours" label="营业时间">
            <el-input v-model="station.businessHours"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button type="primary" style="margin-left: 94%" @click="present" v-has-permi = "['pile:station:edit']">提交</el-button>
  </div>
</template>

<script>
import {
  getStationInfo,
  updateStation,
} from "@/api/pile/station.js";
import bus from "@/bus/bus";
import { regionData} from "element-china-area-data";
import {getToken} from "@/utils/auth";

export default {
  dicts: ["station_type", "match_cars", "construction_type"],
  data() {
    return {
      actionUrl:process.env.VUE_APP_BASE_API+'/common/uploadOSS',
      dialogVisible:false,
      headers: {
        Authorization: "Bearer " + getToken()
      },
      imageUrl: null,
      dialogImageUrl:'',
      options: regionData,
      labelPosition: "right",
      station: {
        stationName: "",
        areaCode: "",
        address: "",
        stationTel: "",
        matchCars: "",
        selectMatchCars: [],
        publicFlag: "",
        openFlag: "",
        merchantAdminName: "",
        stationLng: "",
        stationLat: "",
        merchantId: "",
        stationStatus: "",
        construction: "",
        businessHours: "",
        pictures: "",
        deptId: "",
      },
      stationId: this.$route.params.id,
      publicFlagOptions: [
        {
          value: "1",
          label: "是",
        },
        {
          value: "0",
          label: "否",
        },
      ],
      openFlagOptions: [
        {
          value: "1",
          label: "是",
        },
        {
          value: "0",
          label: "否",
        },
      ],
      rules: {
        stationName: [
          { required: true, message: "请输入站点名称", trigger: "blur" },
        ],
        areaCode: [
          { required: true, message: "请输入站点区域", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入地址", trigger: "blur" }
        ],
        stationTel: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
        ],
        matchCars: [
          { required: true, message: "请输入适配车辆类型", trigger: "blur" },
        ],
        publicFlag: [
          { required: true, message: "请填写是否对外开放", trigger: "blur" },
        ],
        openFlag: [
          { required: true, message: "是否营业中", trigger: "blur" }
        ],
        // merchantAdminName: [
        //   { required: true, message: "请输入管理员", trigger: "blur" },
        // ],
        stationLng: [
          { required: true, message: "请输入经度", trigger: "blur" },
        ],
        stationLat: [
          { required: true, message: "请输入纬度", trigger: "blur" },
        ],
        // merchantId: [
        //   { required: true, message: "请输入管理员", trigger: "blur" },
        // ],
        stationType: [
          { required: true, message: "请输入站点类型", trigger: "blur" },
        ],
        construction: [
          { required: true, message: "请输入建设场所", trigger: "blur" },
        ],
        region: [
          { required: true, message: "请输入充电费率", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请输入服务费率", trigger: "blur" }
        ],
        businessHours: [
          { required: true, message: "请输入营业时间", trigger: "blur" },
        ],
      },
      fileList: [], // 用于图片回显
      // dialogVisible: null,
    };
  },
  created() {
   
  },
  methods: {
    handleSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log("图片上传成功 url：", this.imageUrl);
      console.log("图片上传成功 res：", res);
      this.fileList.push({url: res.url});
    },
    handleRemove(file, fileList) {
      console.log("移除图片", file, fileList);
      // 从pics数组中，找到图片对应的索引值
      const i = this.fileList.findIndex(x => x.uid === file.uid);
      // 调用splice方法，移除图片信息
      this.fileList.splice(i, 1);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      console.log(this.dialogImageUrl)
      this.dialogVisible = true;
    },
    handleChange() {
      console.log("111");
    },
    // 渲染表格数据
    async queryStationInfo() {
      const res = await getStationInfo(this.stationId);
      console.log(res);
      this.station = res.data;
      if (res.data.pictures != null) {
        var pictures = res.data.pictures.split(',');
        for (let i = 0; i < pictures.length; i++) {
          this.fileList.push({"url": pictures[i]});
        }
      }
      console.log("queryStationInfo表格数据", this.station);
    },
    // 提交按钮
    present() {
      // 赋值
      this.station.matchCars = this.station.selectMatchCars.join(",");
      this.station.pictures = this.pictureList.join(',');
      // console.log("matchCars赋值后：", this.station.matchCars);
      this.$refs.stationRef.validate((valid) => {
        if (valid) {
          this.subUpdate();
          this.$message.success("提交成功");
        }
      });
    },
    // 修改充电站信息
    async subUpdate() {
      await updateStation(this.station);
    },
  },
  mounted() {
    // 接收map 地图传过来的搜索值
    bus.$on("res", (data) => {
      // console.log("data", data); // data就是它传过来的值
      // console.log("原始this.station", this.station);
      // 地址
      this.detailedAddress = data.address;
      // console.log("详细地址", data.address);
      var adcode = data.adcode;
      var areaCode = [];
      areaCode[0] = adcode.substr(0,2) + "0000";
      areaCode[1] = adcode.substr(0,4) + "00";
      areaCode[2] = adcode;
      // console.log("拼装的areaCode", areaCode);
      // 修改数据
      this.station.areaCode = areaCode.join(",");
      this.station.stationLng = String(data.pos[0]);
      this.station.stationLat = String(data.pos[1]);
      // console.log("修改后this.station", this.station);

      // 优化之后
      let newAddress2 = this.detailedAddress
        .replace(/(?<=[省市区])/g, "$&,")
        .split(",");
      let end = newAddress2.pop();
      console.log("详细地址", end);
      this.station.address = end;
    });
  },
  computed: {
    areaCodeList() {
      return this.station.areaCode.split(",");
    },
    pictureList() {
      var pictureList = [];
      for (let i = 0; i < this.fileList.length; i++) {
        pictureList.push(this.fileList[i].url);
      }
      return pictureList;
    }
  },
};
</script>
