<template> 
  <el-card class="form-container" shadow="never">
    <el-form :model="origin" :rules="rules" ref="originFrom" label-width="150px">

      <el-form-item label="生产地名称" prop="originName">
        <el-input v-model="origin.originName"></el-input>
      </el-form-item>
      <el-form-item label="生产地面积（亩）">
        <el-input v-model="origin.originArea"></el-input>
      </el-form-item>
      <el-form-item label="生产地图片">
        <multi-upload v-model="selectOriginPics"></multi-upload>
      </el-form-item>
      <el-form-item label="生产地宣传视频">
        <el-input v-model="origin.videoUrl"></el-input>
      </el-form-item>
      <el-form-item label="生产地vr">
        <el-input v-model="origin.vrUrl"></el-input>
      </el-form-item>
      <el-form-item label="实时监控视频">
        <el-input v-model="origin.cameraUrl"></el-input>
      </el-form-item>
      <el-form-item label="人员数">
        <el-input v-model="origin.peopleNum"></el-input>
      </el-form-item>
      <el-form-item label="建立日期（年）">
        <el-input v-model="origin.foundDate"></el-input>
      </el-form-item>
      <el-form-item label="联系人">
        <el-input v-model="origin.linkUser"></el-input>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input v-model="origin.linkPhone"></el-input>
      </el-form-item>
      <el-form-item label="简介">
        <el-input
          placeholder="请输入内容"
          type="textarea"
          v-model="origin.summary"
          :autosize="true"></el-input>
      </el-form-item>
      <el-form-item label="产出物">
        <el-input v-model="origin.isCert"></el-input>
      </el-form-item>
      <el-form-item label="产出物种植面积（亩）">
        <el-input v-model="origin.originArea"></el-input>
      </el-form-item>
      <el-form-item label="产出物总产量（吨）">
        <el-input v-model="origin.compManageLicenseNum"></el-input>
      </el-form-item>
      <el-form-item label="产出物亩产值（万元）">
        <el-input v-model="origin.compSocialCode"></el-input>
      </el-form-item>
      <el-form-item label="所在省">
        <el-input v-model="origin.provinceId"></el-input>
      </el-form-item>
      <el-form-item label="所在市">
        <el-input v-model="origin.cityId"></el-input>
      </el-form-item>
      <el-form-item label="所在县">
        <el-input v-model="origin.countyId"></el-input>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input v-model="origin.detailAddress"></el-input>
      </el-form-item>
      <el-form-item label="经度（°）">
        <el-input v-model="origin.longitude"></el-input>
      </el-form-item>
      <el-form-item label="维度（°）">
        <el-input v-model="origin.latitude"></el-input>
      </el-form-item>
      <el-form-item>
          <baidu-map  class="map" :center="center" :zoom="zoom" @ready="handlermap"
          :scroll-wheel-zoom="true"
          @click="clickEvent"
          ak="33B192o1jPaqOHASGGAIkoMuwi8W76j3">
            <!-- 地图控件位置 -->
              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
              <!-- 获取城市列表 -->
              <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
              <!-- 定位当前位置 -->
              <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT"  :showAddressBar="true" :autoLocation="true" @locationSuccess="getLoctionSuccess" ></bm-geolocation>
              <!-- 地图容器 -->
              <bm-view :style="{width:'100%',height: '500px'}"></bm-view>
          </baidu-map>
      </el-form-item>
      <el-form-item label="供应商名称" >
        <el-input v-model="origin.compName"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit('originFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm('originFrom')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
  import {createOrigin, getOrigin, updateOrigin} from '@/api/origin'
  import SingleUpload from '@/components/Upload/singleUpload'
  import MultiUpload from '@/components/Upload/multiUpload'
  import {BaiduMap,BmNavigation,BmView,BmGeolocation,BmCityList} from 'vue-baidu-map'
  const defaultorigin={
    altitude: null,
    cameraUrl: null,
    cityName: null,
    compId: null,
    compName: "",
    countyName: null,
    createId: null,
    createTime: "",
    detailAddress: null,
    foundDate: null,
    id: null,
    imgUrl: null,
    latitude: null,
    linkPhone: null,
    linkUser: null,
    longitude: null,
    originArea: null,
    originName: "",
    pageNum: 1,
    pageSize: 10,
    peopleNum: null,
    productlist: [],
    provinceName: null,
    remark: null,
    state: 0,
    summary: null,
    updateId: null,
    updateTime: null,
    videoUrl: null,
    vrUrl: null,
  };
  export default {
    name: 'originDetail',
    components:{
      SingleUpload,
      MultiUpload,
      BaiduMap,
      BmNavigation,
      BmView,
      BmGeolocation,
      BmCityList,
    },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        origin:Object.assign({}, defaultorigin),
        rules: {
          originName: [
            {required: true, message: '请输入品牌名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
          logo: [
            {required: true, message: '请输入品牌logo', trigger: 'blur'}
          ],
          sort: [
            {type: 'number', message: '排序必须为数字'}
          ],
        },
        center: {lng: 106.632713, lat: 26.653157},
        zoom: 12,
        mapVisible:false,
        clientHeight:document.documentElement.clientHeight-90, // 设置屏幕高度


      }
    },
    computed: {
      //生产地图片
      selectOriginPics:{

        get:function () {
          let pics=[];
          // if(this.origin.pic===undefined||this.origin.pic==null||this.origin.pic===''){
          //   return pics;
          // }
          // pics.push(this.origin.pic);
          if(this.origin.imgUrl===undefined||this.origin.imgUrl==null||this.origin.imgUrl===''){
            return pics;
          }
          let albumPics = this.origin.imgUrl.split(',');
          for(let i=0;i<albumPics.length;i++){
            pics.push(albumPics[i]);
          }
          return pics;
        },
        set:function (newValue) {
          console.log('newValue',newValue);
          if (newValue == null || newValue.length === 0) {
            // this.origin.pic = null;
            this.origin.imgUrl = null;
          } else {
            // this.origin.pic = newValue[0];
            this.origin.imgUrl = '1';
            if (newValue.length > 1) {
              for (let i = 1; i < newValue.length; i++) {
                this.origin.imgUrl += newValue[i];
                if (i !== newValue.length - 1) {
                  this.origin.imgUrl += ',';                  
                }
              }
            }
          }
          console.log(' this.origin.imgUrl', this.origin.imgUrl);
        }

      }

    },
    created() {
      if (this.isEdit) {
        getOrigin(this.$route.query.id).then(response => {
          this.origin = response.data;
        });
      }else{
        this.origin = Object.assign({},defaultorigin);
      }
    },
    methods: {
      onSubmit(formName) {
        // console.log('this.origin',JSON.parse(JSON.stringify(this.origin)))
        // return false;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              if (this.isEdit) {
                updateOrigin(this.$route.query.id, this.origin).then(response => {
                  this.$refs[formName].resetFields();
                  this.$message({
                    message: '修改成功',
                    type: 'success',
                    duration:1000
                  });
                  setTimeout(() =>{
                    this.$router.back();
                  },1000);
                });
              } else {
                createOrigin(this.origin).then(response => {
                  this.$refs[formName].resetFields();
                  this.origin = Object.assign({},defaultorigin);
                  this.$message({
                    message: '提交成功',
                    type: 'success',
                    duration:1000
                  });
                  setTimeout(() =>{
                    this.$router.back();
                  },1000);
                });
              }
            });

          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.origin = Object.assign({},defaultorigin);
      },
      handlermap ({BMap, map}) {
          let _this = this;	// 设置一个临时变量指向vue实例；
          var geolocation = new BMap.Geolocation();
          geolocation.getCurrentPosition(function(r){
            // console.log(r);
            _this.center = {lng: r.longitude, lat: r.latitude};		// 设置center属性值
            _this.autoLocationPoint = {lng: r.longitude, lat: r.latitude};		// 自定义覆盖物
            _this.initLocation = true;
          },{enableHighAccuracy: true})
            window.map = map;
        },
        //点击地图监听
        clickEvent(e){
          map.clearOverlays();
          let Icon_0 = new BMap.Icon("static/zuobiao.gif", new BMap.Size(64, 64), {anchor: new BMap.Size(18, 32),imageSize: new BMap.Size(36, 36)});
          var myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat),{icon: Icon_0});
          map.addOverlay(myMarker);
          //用所定位的经纬度查找所在地省市街道等信息
          var point = new BMap.Point(e.point.lng, e.point.lat);
          var gc = new BMap.Geocoder();
          let _this = this;
          gc.getLocation(point, function (rs) {
            var addComp = rs.addressComponents;
            // console.log(rs);//地址信息
            _this.origin.provinceId = rs.addressComponents.province;
            _this.origin.cityId = rs.addressComponents.city;
            _this.origin.countyId = rs.addressComponents.district;
            _this.origin.detailAddress = rs.address;
          });
            this.origin.longitude = e.point.lng;
            this.origin.latitude = e.point.lat;
        },
        //定位成功回调
        getLoctionSuccess(point, AddressComponent, marker){
          map.clearOverlays();
          let Icon_0 = new BMap.Icon("/static/zuobiao.gif", new BMap.Size(64, 64), {anchor: new BMap.Size(18, 32),imageSize: new BMap.Size(36, 36)});
          var myMarker = new BMap.Marker(new BMap.Point(point.point.lng, point.point.lat),{icon: Icon_0});
          map.addOverlay(myMarker);
          this.company.longitude = point.point.lng;
          this.company.latitude = point.point.lat;
        },
        findlocation(){
          this.$emit("findlocdata",this.company)
          this.mapVisible = false
        },
        mapShow(){
          this.mapVisible = true
        },
    }
  }
</script>
<style>
</style>


