<template>
<div>
  <sticky className="sub-navbar">
    <div style="text-align:right;">
      <el-button type="success" :loading="onSubmit" @click="handleSave">保存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </sticky>
  <div class="app-container app-edit">
    <el-form class="small-space" :model="form" :rules="rules" ref="form" label-position="right" label-width="120px" style="width:500px;">

      <!-- 店名称 -->
      <el-form-item label="店名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入店名称"></el-input>
      </el-form-item>

      <!-- 单次金额 -->
      <!-- <el-form-item label="单次金额" prop="price" v-if="form.type===1">
        <el-input-number type="number" :min="0" :precision="2" v-model.number="form.price" placeholder="请输入单次金额"></el-input-number>
      </el-form-item> -->

                <!-- 缩略图 -->
      <el-form-item label="列表图片(110*50px)" prop="listImage">
        <el-upload
          class="avatar-uploader"
          action="/api/upload/image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="form.listImage" :src="form.listImage" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="场馆图片(750*422px)" prop="venueImage">
        <el-upload
          action="/api/upload/image"
          list-type="picture-card"
          :file-list="imgs"
          :on-remove="handleImgRemove"
          :on-success="handleImgSuccess">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>

      <!-- 营业时间 -->
      <!-- <el-form-item label="营业时间" prop="businessTime">
        <el-input v-model="form.businessTime" placeholder="请输入营业时间"></el-input>
      </el-form-item> -->

      <!-- 营业时间 -->
        <el-form-item label="营业时间" prop="businessTime" style="width:1000px">
          <el-select style="width:100px" v-model="form.businessStartDate">
            <el-option label="周一" :value="1"></el-option>
            <el-option label="周二" :value="2"></el-option>
            <el-option label="周三" :value="3"></el-option>
            <el-option label="周四" :value="4"></el-option>
            <el-option label="周五" :value="5"></el-option>
            <el-option label="周六" :value="6"></el-option>
            <el-option label="周日" :value="7"></el-option>
          </el-select>至
          <el-select style="width:100px" v-model="form.businessEndDate">
            <el-option label="周一" :value="1"></el-option>
            <el-option label="周二" :value="2"></el-option>
            <el-option label="周三" :value="3"></el-option>
            <el-option label="周四" :value="4"></el-option>
            <el-option label="周五" :value="5"></el-option>
            <el-option label="周六" :value="6"></el-option>
            <el-option label="周日" :value="7"></el-option>
          </el-select>
          <el-time-picker
            style="width:200px"
            is-range
            v-model="timeData"
            value-format="HH:mm"
            format="HH:mm"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="请选择营业时间"
            @change="timeChange">
          </el-time-picker>
        </el-form-item>

      <el-form-item label="门店GPS位置" prop="address" :required="true">
        <div style="color:red">*请点击地图选择一个位置，用于小程序前端导航</div>
        <div id="container" class="map" tabindex="0" style="width:900px;margin-top:10px"></div>
      </el-form-item>

      <el-form-item label="门店详细地址" prop="address" :required="true">
        <el-input v-model="form.address" placeholder="请输入门店详细地址"/>
      </el-form-item>

      <!-- 联系人 -->
      <el-form-item label="联系人" prop="contact">
        <el-input v-model="form.contact" placeholder="请输入联系人"></el-input>
      </el-form-item>

      <!-- 联系人号码 -->
      <el-form-item label="联系人号码" prop="phone">
        <el-input v-model.number="form.phone" placeholder="请输入联系人号码"></el-input>
      </el-form-item>

      <!-- 场馆介绍 -->
      <el-form-item label="场馆介绍" prop="description">
        <tinymce :height="300" v-model="form.description" id='tinymce' style="width:900px"></tinymce>
      </el-form-item>

      <!--会员卡说明-->
      <el-form-item label="会员卡说明" prop="cardContent">
        <div style="color:red;margin-bottom: 5px;">*说明建议不超过200字</div>
        <tinymce :height="300" v-model="form.cardContent" id='cardContent' style="width:900px"></tinymce>
      </el-form-item>
      <div v-for="(item, i) in form.priceList" :key="i" >
        <el-form-item label="金额" prop="price" style="width:1000px">
          <el-input-number v-model="item.price" :min="0" :precision="2"  placeholder="请输入单次金额"></el-input-number>
            <el-time-picker
              style="width:200px"
              is-range
              v-model="item.priceDate"
              value-format="HH:mm"
              format="HH:mm"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="请选择营业时间"
              @change="priceTimeChange">
            </el-time-picker>
            <el-button style="font-size: 13px;background-color: rgba(245,108,108,.1);border-color: rgba(245,108,108,.2); color:#f56c6c;"  @click="handleDelete(i)">删除</el-button>
        </el-form-item>
        
      </div>
        <el-button style="font-size: 13px;" type="success" @click="changePrice" v-if="form.type==1">添加时间段价格</el-button>
        <el-dialog title="价格设置" :visible.sync="dialogFormVisible" size="tiny">
            <el-form-item label="金额" prop="price">
            <el-input-number v-model="form.price" :min="0" :precision="2"  placeholder="请输入单次金额"></el-input-number>
          </el-form-item>
          <el-form-item label="时间段" prop="starTime">
              <el-time-picker
                style="width:200px"
                is-range
                v-model="form.priceDate"
                value-format="HH:mm"
                format="HH:mm"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="请选择营业时间"
                @change="priceTimeChange">
              </el-time-picker>
          </el-form-item>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="savePrice">确 定</el-button>
          </div>
        </el-dialog>
    </el-form>
  </div>
</div>
</template>

<script>
import Sticky from "@/components/Sticky";
import { find, save } from "@/api//venue";
import moment from "moment";
import { findDataList } from "@/api/venue/type";
import Tinymce from "@/components/Tinymce";
import waves from "@/directive/waves.js"; // 水波纹指令
import Pagination from "@/components/Pagination";
import { Notification } from "element-ui";
import { findPrice,checkTime } from "@/api//venue/price";

let marker = undefined;
let longitude = undefined;
let latitude = undefined;
let geocoder = undefined;
export default {
  components: { Tinymce, Pagination, Notification, Sticky },
  directives: {
    waves
  },
  data() {
    var checkBusinessTime = (rule, value, callback) => {
      if (this.form.businessStartDate >= this.form.businessEndDate) {
        return callback(new Error("请选择正确的营业时间"));
      }
      if (!this.timeData) {
        return callback(new Error("请选择营业时间"));
      }
      callback();
    };
    return {
      dialogFormVisible: false,
      form: {
        id: undefined,
        name: "",
        address: "",
        longitude: "",
        latitude: "",
        type: 1,
        listImage: "",
        venueImage: [],
        businessTime: "",
        contact: "",
        businessStartTime: "",
        businessEndTime: "",
        businessEndDate: 7,
        businessStartDate: 1,
        phone: "",
        description: "",
        platformId: "",
        cardContent: "",
        priceList:[],
        priceListStr:"",
        price: 0,
        starTime : '',
        endTime:'',
        priceDate: undefined,
      },
      imgs: [],
      timeData: undefined,
      priceDate: undefined,
      types: [],
      typeDesc: undefined,
      dialogVisible: false,
      map: "",
      onSubmit: false,

      // 表单验证规则
      rules: {
        name: [
          { required: true, message: "请输入场馆名称", trigger: "blur" },
          { min: 3, message: "名称不能少于3个字符", trigger: "blur" }
        ],
        description: [
          { required: true, message: "请输入场馆介绍", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入联系电话" },
          { pattern: /^1[34578]\d{9}$/, message: "手机号格式错误" }
        ],
        address: [
          { required: true, message: "请输入地址信息", trigger: "blur" },
          { max: 100, message: "信息长度不能超过200个字符", trigger: "blur" }
        ],
        listImage: [
          { required: true, message: "请上传列表图片", trigger: "blur" }
        ],
        venueImage: [
          { type: "array", required: true, message: "请上传场馆图片" },
          { type: "array", min: 1, message: "请上传场馆图片" }
        ],
        businessTime: [
          { validator: checkBusinessTime, trigger: "blur", required: true }
        ],
        cardContent: [
          { required: true, message: "请输入会员卡说明", trigger: "blur" }
        ]
      }
    };
  },
  mounted: function() {
    this.init();
  },
  created() {
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id;
      this.findById(this.form.id);
      //查询场馆对应的价格
      this.findPrice(this.form.id);
    }
    if (this.$route.query.type) {
      this.form.type = this.$route.query.type;
    }
    this.loadVenueType();
  },
  methods: {
    timeChange(date) {
      if (date) {
        this.form.businessStartTime = date[0];
        this.form.businessEndTime = date[1];
      }
    },
    priceTimeChange(date) {
      if (date) {
        this.form.starTime = date[0];
        this.form.endTime = date[1];
      }
    },
    init() {
      var myLatlng = new qq.maps.LatLng(31.249548981590582, 121.45591735839844);
      var myOptions = {
        zoom: 12,
        center: myLatlng,
        mapTypeId: qq.maps.MapTypeId.ROADMAP
      };
      this.map = new qq.maps.Map(
        document.getElementById("container"),
        myOptions
      );
      qq.maps.event.addListener(this.map, "click", function(event) {
        console.log(event);
        if (marker) {
          marker.setMap(null);
        }
        marker = new qq.maps.Marker({
          position: event.latLng,
          draggable: true,
          map: this
        });
        geocoder.getAddress(event.latLng);
      });
      var _that = this;
      geocoder = new qq.maps.Geocoder({
        complete: function(result) {
          console.log(result);
          _that.form.address = result.detail.address;
        }
      });
    },
    /**
     * 查询场馆
     */
    findById(id) {
      find(id).then(response => {
        this.form.name = response.venue.name;
        this.form.address = response.venue.address;
        this.form.longitude = response.venue.longitude;
        this.form.latitude = response.venue.latitude;
        this.form.type = response.venue.type;
        this.form.listImage = response.venue.listImage;
        this.form.businessTime = response.venue.businessTime;
        this.form.contact = response.venue.contact;
        this.form.phone = response.venue.phone;
        this.form.description = response.venue.description;
        this.form.platformId = response.venue.platformId;
        this.form.businessStartDate = response.venue.businessStartDate;
        this.form.businessEndDate = response.venue.businessEndDate;
        this.form.businessStartTime = response.venue.businessStartTime;
        this.form.businessEndTime = response.venue.businessEndTime;
        this.form.cardContent = response.venue.cardContent;
        this.timeData = [
          response.venue.businessStartTime,
          response.venue.businessEndTime
        ];
        response.venue.images.forEach(element => {
          this.imgs.push({ name: element, url: element });
          this.form.venueImage.push(element);
        });
        this.map.panTo(
          new qq.maps.LatLng(this.form.latitude, this.form.longitude)
        );
        marker = new qq.maps.Marker({
          position: new qq.maps.LatLng(this.form.latitude, this.form.longitude),
          draggable: true,
          map: this.map
        });
      });
    },
    /**
     * 查询场馆对应的价格
     */
    findPrice(id) {
      findPrice(id).then(response => {
         response.price.forEach(price => {
           this.form.priceDate = [
            price.starTime,
            price.endTime
          ]
          this.form.priceList.push({
             price: price.price,
             priceDate: this.form.priceDate,
             starTime : this.form.priceDate[0],
             endTime : this.form.priceDate[1],
             });
             
        });
      });
    },

    /**
     * 保存场馆
     */
    handleSave() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false;
        }
        if (!marker) {
          Notification.error({
            title: "提示",
            message: "请点击地图选择场馆具体位置",
            duration: 2000
          });
          return;
        }
        this.onSubmit = true;
        this.form.latitude = marker.position.lat;
        this.form.longitude = marker.position.lng;
        this.form.priceListStr=JSON.stringify(this.form.priceList);
        save(this.form)
          .then(response => {
            this.$router.go(-1);
          })
          .finally(() => {
            this.onSubmit = false;
          });
      });
    },
     /**
     * 保存价格
     */
    savePrice() {
      var flag = true
      //  if (this.form.price <= 0) {
      //   this.$message({
      //     message: '价格必须大于0',
      //     type: 'warning'
      //   })
      //   flag = false
      //   return
      // }
      if (this.form.endTime < this.form.startTime) {
        this.$message({
          message: '结束时间必须在开始时间之后！',
          type: 'warning'
        })
        flag = false
        return
      }
      if (!this.form.priceDate) {
        this.$message({
          message: '请选择时间！',
          type: 'error'
        })
        flag = false
        return
      }
      if (!flag) { return }

      if (this.$route.query.id) {
        this.form.id = this.$route.query.id
        this.form.starTime = this.form.priceDate[0];
        this.form.endTime = this.form.priceDate[1];
        // checkTime(this.form.id,this.form.starTime,this.form.priceDate[1])
      }
      this.form.priceList.push({
        price: this.form.price,
        priceDate: this.form.priceDate,
        starTime : this.form.priceDate[0],
        endTime : this.form.priceDate[1],
      })
      this.dialogFormVisible = false
    },
    /**
     * 取消
     */
    handleCancel() {
      this.$router.go(-1);
    },
    /**
     * 展示场馆类型描述
     */
    displayTypeInfo(id) {
      for (var i in this.types) {
        if (id === this.types[i].id) {
          this.typeDesc = this.types[i].desc;
        }
      }
    },
    /**
     * 加载场馆类型
     */
    loadVenueType() {
      findDataList().then(response => {
        this.types = response.venueTypes;
      });
    },

    beforeAvatarUpload(file) {
      // const isLt2M = file.size / 1024 / 1024 < 2
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      // return isLt2M
    },
    // 处理头像上传成功
    handleAvatarSuccess(res, file) {
      this.form.listImage = res.img;
    },
    // 处理banner上传成功
    handleImgSuccess(res, file) {
      this.form.venueImage.push(res.img);
    },
    handleImgRemove(file, fileList) {
      var img = file.url;
      for (var i in this.form.venueImage) {
        if (this.form.venueImage[i] === img) {
          this.form.venueImage.splice(i, 1);
        }
      }
    },
     changePrice(venueId) {
      this.form.price = 0;
      this.form.priceDate = undefined;
      this.form.starTime = '';
      this.form.endTime = '';
      this.dialogFormVisible = true
      },
      /**
     * 删除价格
     */
    handleDelete(row) {
      this.form.priceList.splice(row, 1)
    }
  }
};
</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: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
.info {
  color: #909399;
}
.map {
  height: 500px;
  width: 100%;
  float: left;
}
</style>
