<template>
  <el-card class="form-container" shadow="never">
    <el-form :model="origin" :rules="rules" ref="originFrom" label-width="150px">
      <el-form-item label="供应商：" prop="compId">
        <el-select
          filterable
          v-model="origin.compId"
          @change="handleSupplierChange"
          placeholder="请选择供应商"
          style="width: 100%;"
        >
          <el-option
            v-for="item in supplierOptList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <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"
          :rows="5"
          v-model="origin.summary"
          :autosize="true"></el-input>
      </el-form-item>
      <el-form-item label="产出物" v-if="isEdit">
        <div style="text-align: right;"><el-button size="mini" class="btn-add" @click="handleAddOriginProduct()">添加产出物</el-button></div>
        <div class="table-container">
          <el-table ref="roleTable"
                :data="origin.productlist"
                style="width: 100%;"
                v-loading="originProductListLoading" border>
              <el-table-column label="产出物名称" width="100px" show-overflow-tooltip align="center">
                <template slot-scope="scope">{{scope.row.productName}}</template>
              </el-table-column>
              <el-table-column label="面积（亩）"  show-overflow-tooltip align="center">
                <template slot-scope="scope">{{scope.row.plantArea}}</template>
              </el-table-column>
              <el-table-column label="产出物总产量（吨）" show-overflow-tooltip align="center">
                <template slot-scope="scope">{{scope.row.outputNum}}</template>
              </el-table-column>
              <el-table-column label="产出物亩产值（万元）" show-overflow-tooltip align="center">
                <template slot-scope="scope">{{scope.row.outputValue}}</template>
              </el-table-column>
              <el-table-column label="可用状态"  show-overflow-tooltip align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.state ==0">可用</span>
                  <span v-else-if="scope.row.state ==1">禁用</span>
                  <span v-else-if="scope.row.state ==2">删除</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160" align="center">
                <template slot-scope="scope">
                  <el-row>
                  <el-button size="mini"
                            type="text"
                            @click="handleUpdateOriginProduct(scope.$index, scope.row)">
                    编辑
                  </el-button>
                  <el-button size="mini"
                            type="text"
                            @click="handleDeleteOriginProduct(scope.$index, scope.row)">删除
                  </el-button>
                  </el-row>
                </template>
              </el-table-column>
          </el-table>
        </div>
      </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.provinceName"></el-input>
      </el-form-item>
      <el-form-item label="所在市">
        <el-input v-model="origin.cityName"></el-input>
      </el-form-item>
      <el-form-item label="所在县">
        <el-input v-model="origin.countyName"></el-input>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input v-model="origin.detailAddress"></el-input>
      </el-form-item>
      <el-form-item label="经度（°）" prop="longitude">
        <el-input v-model="origin.longitude"></el-input>
      </el-form-item>
      <el-form-item label="维度（°）" prop="latitude">
        <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>
        <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-dialog
      :title="productDialogTitle"
      :visible.sync="productDialogVisible"
      width="40%">
      <el-form ref="originProductForm" :model="originProductlist" :rules="rules" label-width="120px">
        <el-form-item label="产出物名称" prop="productName">
          <el-input v-model="originProductlist.productName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产出物总产量（吨）" prop="outputNum">
          <el-input v-model="originProductlist.outputNum" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产出物亩产值（万元）" prop="outputValue">
          <el-input v-model="originProductlist.outputValue" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产出物种植面积（亩）" prop="plantArea">
          <el-input v-model="originProductlist.plantArea" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否可用">
          <el-select v-model="originProductlist.state" placeholder="0:可用,1:禁用,2:删除">
            <el-option
              v-for="item in originProductlistState"
              :key="item.label"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="originProductlist.remark" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="productDialogVisible = false;originProductlist = {};">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('originProductForm')">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>
<script>
  import {createOrigin, getOrigin, updateOrigin} from '@/api/origin'
  import {originProductList as fetchOriginProductList, createOriginProduct, updateOriginProduct,deleteOriginProduct} from '@/api/origin'
  import {selectCompList} from '@/api/product';
  import SingleUpload from '@/components/Upload/singleUpload'
  import MultiUpload from '@/components/Upload/multiUpload'
  import {bMapTransQQMap,qqMapTransBMap} from '@/utils/index';
  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),
        productDialogTitle:'',
        productDialogVisible:false,
        originProductlist:{},
        originProductlistState:[
          {value: 0,label: '可用'},
          {value: 1,label: '禁用'},
          {value: 2,label: '删除'},
        ],
        supplierOptList: [],
        rules: {
          selectOriginPics:[
            {required: true, message: '请上传生产地图片', trigger: 'blur'}
          ],
          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: '排序必须为数字'}
          ],
          longitude: [
            {required: true, message: '请选择经纬度', trigger: 'blur'}
          ],
          latitude  : [
            {required: true, message: '请选择经纬度', trigger: 'blur'}
          ],
          compId: [{required: true, message: '请选择供应商', trigger: 'blur'}],
          productName: [{required: true, message: '请输入名称', trigger: 'blur'}],
          outputNum: [{required: true, message: '请输入产出物总产量', trigger: 'blur'}],
          outputValue: [{required: true, message: '请输入产出物亩产值', trigger: 'blur'}],
          plantArea: [{required: true, message: '请输入产出物种植面积', trigger: 'blur'}],
        },
        originProductList:[],
        originProductListLoading:false,
        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 = '';
            if (newValue.length >= 1) {
              for (let i = 0; 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() {
      this.getSupplierOptList();
      if (this.isEdit) {
        this.getData();
      }else{
        this.origin = Object.assign({},defaultorigin);
      };
    },
    methods: {
      /** 获取供应商下拉列表 */
      getSupplierOptList() {
        selectCompList().then(response => {
          this.supplierOptList = response.data;
        });
      },
      handleConfirm(formName){
        this.$refs[formName].validate((valid) => {
          console.log('valid',valid);
          if (valid) {
            this.originProductlist.fkOriginId = parseInt( this.$route.query.id);
            if(this.productDialogTitle==="添加产出物"){
              createOriginProduct(this.originProductlist).then(response=>{
                this.$message({
                  message: '添加成功',
                  type: 'success',
                  duration:1000
                });
                this.productDialogVisible = false;
                this.originProductlist = {};
                this.getData();
              });
            }else{
              updateOriginProduct(this.originProductlist.id,this.originProductlist).then(response=>{
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration:1000
                });
                this.productDialogVisible = false;
                this.originProductlist = {};
                this.getData();
              });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });        
      },
      // 新增产出物
      handleAddOriginProduct(){
        this.productDialogTitle = "添加产出物";
        this.productDialogVisible = true;
        console.log('新增产出物');
      },
      // 修改产出物
      handleUpdateOriginProduct(index,data){
        this.productDialogTitle = "编辑产出物";
        this.productDialogVisible = true;
        this.originProductlist = data;
        console.log('修改产出物inex',index);
        console.log('修改产出物data',data);
      },
      // 删除产出物
      handleDeleteOriginProduct(index,data){
        console.log('删除产出物inex',index);
        console.log('删除产出物data',data);

        this.$confirm('是否要删除该产出物', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteOriginProduct(data.id).then(response=>{
            this.$message({
              message: '删除成功',
              type: 'success',
              duration:1000
            });
            this.getData();
          });
        });

      },
      getData(){
        getOrigin(this.$route.query.id).then(response => {
          this.origin = response.data;
          console.log('this.origin',JSON.parse(JSON.stringify(this.origin)));
        });
      },
      onSubmit(formName) {
        // console.log('this.origin',JSON.parse(JSON.stringify(this.origin)))
        // return false;

        if(!this.selectOriginPics || (this.selectOriginPics || []).length==0){
          this.$message({
            message: '请上传生产地图片',
            type: 'error',
            duration:1000
          });
          return;
        }
        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属性值
          // console.log('_this.center',_this.origin);
          if(_this.origin.latitude&&_this.origin.longitude){
            let transqq = qqMapTransBMap(_this.origin.longitude,_this.origin.latitude);
            // console.log('transqq',transqq);
            _this.center = {lng:transqq.lng, lat: transqq.lat};
          };
          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)});
          let myMarker = new BMap.Marker(new BMap.Point(_this.origin.longitude, _this.origin.latitude),{icon: Icon_0});
          map.addOverlay(myMarker);
          _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.provinceName = rs.addressComponents.province;
          _this.origin.cityName = rs.addressComponents.city;
          _this.origin.countyName = rs.addressComponents.district;
          _this.origin.detailAddress = rs.address;
        });
        //转为高德坐标
        let transGaode = bMapTransQQMap(e.point.lng,e.point.lat);
        this.origin.longitude = transGaode.lng;
        this.origin.latitude = transGaode.lat;
        // 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
      },
      handleSupplierChange(val) {
        let supplierInfoObj = {};
        supplierInfoObj = this.supplierOptList.find(item => {
          return item.value === val;
        });
        this.origin.compName = supplierInfoObj.label;
      },
    }
  }
</script>
<style>
.form-container{width: 900px;}
</style>


