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

      <el-form-item label="供应商名称：" prop="compName">
        <el-input v-model="company.compName"></el-input>
      </el-form-item>
      <el-form-item label="供应商类型：">
        <el-input v-model="company.companyType"></el-input>
      </el-form-item>
      <el-form-item label="供应商评级">
        <el-input v-model="company.compLevel"></el-input>
      </el-form-item>
      <el-form-item label="供应商资质">
        <el-input v-model="company.compQual"></el-input>
      </el-form-item>
      <!-- <el-form-item label="企业logo图片">
         <single-upload v-model="company.compLogo"></single-upload>
      </el-form-item> -->
      <el-form-item label="供应商图片">
        <div>请按企业logo,供应商图片,供应商资质图片,公众号二维码图片顺序上传</div>
        <multi-upload v-model="thecompImgs"></multi-upload>
      </el-form-item>
      <!-- <el-form-item label="供应商资质图片">
        <single-upload v-model="company.compQualImgs"></single-upload>
      </el-form-item> -->
      
      <!-- <el-form-item label="公众号二维码图片">
        <single-upload v-model="company.compQr"></single-upload>
      </el-form-item> -->
      <el-form-item label="淘宝店地址">
        <el-input v-model="taobaourl"></el-input>
      </el-form-item>
      <el-form-item label="京东店地址">
        <el-input v-model="jdurl"></el-input>
      </el-form-item>
      <el-form-item label="自主商城地址">
        <el-input v-model="selfurl"></el-input>
      </el-form-item>
      <el-form-item label="是否认证">
        <el-switch          
          :active-value="1"
          :inactive-value="0"
          v-model="company.isCert">
        </el-switch>
      </el-form-item>
      <el-form-item label="生产许可证号">
        <el-input v-model="company.compProdLicenseNum"></el-input>
      </el-form-item>
      <el-form-item label="经营许可证号">
        <el-input v-model="company.compManageLicenseNum"></el-input>
      </el-form-item>
      <el-form-item label="社会信用代码">
        <el-input v-model="company.compSocialCode"></el-input>
      </el-form-item>
      <el-form-item label="联系人">
        <el-input v-model="company.compConPerson"></el-input>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input v-model="company.compConType"></el-input>
      </el-form-item>
      <el-form-item label="对外企业qq">
        <el-input v-model="company.compQq"></el-input>
      </el-form-item>
      <el-form-item label="经营产品">
        <el-input v-model="company.compManageProduct"></el-input>
      </el-form-item>
      <el-form-item label="简介">
        <el-input
          placeholder="请输入内容"
          type="textarea"
          v-model="company.compSum"
          :autosize="true"></el-input>
      </el-form-item>
      <el-form-item label="所在省">
        <el-input v-model="company.provinceId"></el-input>
      </el-form-item>
      <el-form-item label="所在市">
        <el-input v-model="company.cityId"></el-input>
      </el-form-item>
      <el-form-item label="所在县">
        <el-input v-model="company.countyId"></el-input>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input v-model="company.detailAddress"></el-input>
      </el-form-item>
      <el-form-item label="经度（°）">
        <el-input placeholder=""  style="width: 80%;" size="samll" v-model.number="company.longitude"></el-input>
      </el-form-item>
      <el-form-item label="维度（°）">
        <el-input v-model="company.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="company.countyId"></el-input>
      </el-form-item>
      <el-form-item label="其中建档立卡人数">
        <el-input v-model="company.countyId"></el-input>
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" @click="onSubmit('companyFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm('companyFrom')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
  import {createCompany, getCompany, updateCompany} from '@/api/company'
  import SingleUpload from '@/components/Upload/singleUpload'
  import MultiUpload from '@/components/Upload/multiUpload'
  import {BaiduMap,BmNavigation,BmView,BmGeolocation,BmCityList} from 'vue-baidu-map'
  const defaultCompany={
    cityId: "",
    compConNum: "",
    compConPerson: "",
    compConType: null,
    compImgs: null,
    compLevel: null,
    compManageLicenseNum: null,
    compManageProduct: "",
    compName: "",
    compProdLicenseNum: "",
    compQq: "",
    compQual: "",
    compSocialCode: "",
    compStatus: null,
    compSum: "",
    compUrl: null,
    companyType: "",
    countyId: "",
    createId: null,
    createTime: "",
    detailAddress: "",
    files:[],
    id: null,
    isCert: 0,
    latitude: "",
    longitude: "",
    origins: null,
    provinceId: "",
    shops: [],
    townId: null,
    updateId: null,
    updateTime: null,
    villageId: null,
  };
  export default {
    name: 'companyDetail',
    components:{
      SingleUpload,
      MultiUpload,
      BaiduMap,
      BmNavigation,
      BmView,
      BmGeolocation,
      BmCityList,
      
    },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        company:Object.assign({}, defaultCompany),
        jdurl:'',
        taobaourl:'',
        selfurl:'',
        rules: {
          compName: [
            {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, // 设置屏幕高度
      }
    },
    created() {
      if (this.isEdit) {
        getCompany(this.$route.query.id).then(response => {
          this.company = response.data;
          // 商城地址
          let jdshop =  this.company.shops.filter( (item) => {
            return item.shopType == "jd"
          });
          if(jdshop.length>0){this.jdurl = jdshop[0].shopUrl;}   

          let taobaoshop =  this.company.shops.filter( (item) => {
            return item.shopType == "taobao"
          });
          if(taobaoshop.length>0){this.taobaourl = taobaoshop[0].shopUrl;}
          // 商城地址
          console.log('this.company',JSON.parse(JSON.stringify(this.company)));
        });
      }else{
        this.company = Object.assign({},defaultCompany);
      }
    },
    computed: {
      //供应商图片
      thecompImgs:{
        get:function () {
          let pics=[];
          if(this.company.files===undefined||this.company.files==null||this.company.files===''){
            return pics;
          }
          let compImgs = this.company.files;
          for(let i=0;i<compImgs.length;i++){
            pics.push(compImgs[i].fileUrl);
          }
          return pics;
        },
        set:function (newValue) {     
          // console.log('newValue',newValue);
          if (newValue == null || newValue.length === 0) {
            this.company.files = null;
          } else {
            this.company.files = [];
            if (newValue.length >= 1) {              
              for (let i = 0; i < newValue.length; i++) {
                 this.company.files.push({fileUrl:newValue[i],fileType:"company"});
                // this.company.files += newValue[i];
                // if (i !== newValue.length - 1) {
                //   this.company.files += ',';
                // }
              }
            }
          }
        }
      }
    },
    methods: {
      onSubmit(formName) {
        console.log('this.taobaourl',this.taobaourl);
        // 商城地址
        this.company.shops=[];
        if(this.taobaourl.length>0){
          this.company.shops.push({shopType:'taobao',shopUrl:this.taobaourl});
        }

        if(this.jdurl.length>0){
          this.company.shops.push({shopType:'jd',shopUrl:this.jdurl});
        }

        // 商城地址
        console.log('this.company',JSON.parse(JSON.stringify(this.company)))
        // return false;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              if (this.isEdit) {
                updateCompany(this.$route.query.id, this.company).then(response => {
                  this.$refs[formName].resetFields();
                  this.$message({
                    message: '修改成功',
                    type: 'success',
                    duration:1000
                  });
                  setTimeout(() =>{
                    this.$router.back();
                  },1000);
                });
              } else {
                createCompany(this.company).then(response => {
                  this.$refs[formName].resetFields();
                  this.company = Object.assign({},defaultCompany);
                  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.company = Object.assign({},defaultCompany);
      },
      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.company.provinceId = rs.addressComponents.province;
            _this.company.cityId = rs.addressComponents.city;
            _this.company.countyId = rs.addressComponents.district;
            _this.company.detailAddress = rs.address;
          });
            this.company.longitude = e.point.lng;
            this.company.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>


