<template>
  <div class="app-container">
    <el-form :model="form" ref="form" :rules="rules" label-width="120px">
      <h3>基础信息</h3>
      <el-form-item label="商户名称" prop="businessName">
        <el-input v-model="form.businessName" placeholder="请输入商户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商家分类" prop="businessCategoryList">
        <el-select v-model="form.businessCategoryList" multiple placeholder="请选择商家分类" clearable style="width: 100%">
          <el-option v-for="(v,i) in shopTypeList" :key="i" :label="v.name" :value="v.categoryId" />
        </el-select>
        <div class="hint">*分类可多选</div>
      </el-form-item>
      <el-form-item label="商家位置" prop="location">
        <el-input v-model="form.location" placeholder="请输入商家位置" maxlength="150" clearable @keyup.enter.native="handleQuery" />
        <div class="hint">*例如：光谷商圈、街道口、徐东商圈</div>
      </el-form-item>
      <el-form-item label="所在城市" prop="provinces">
        <!-- <el-input v-model="form.name" placeholder="请输入商户名称" clearable  @keyup.enter.native="handleQuery" /> -->
        <el-cascader ref="refSubCat" v-model="form.provinces" placeholder="请选择所在城市" :options="areaTrea" :props="{ expandTrigger: 'hover' }" @change="handleChange" style="width: 100%"></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入详细地址" maxlength="100" clearable @keyup.enter.native="getgetAddressFun" />
      </el-form-item>
      <el-form-item label="经纬度" prop="longitudeLatitude">
        <el-input v-model="form.longitudeLatitude" disabled placeholder="请输入经纬度" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <div id="container1" class="map-box"></div> -->
      <GDMap ref="gdMapRef" :defaultMarker="defaultMarker" @change="mapchange" />
      <el-form-item label="经营主体名称" prop="entityName">
        <el-input v-model="form.entityName" placeholder="请输入经营主体名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="税号" prop="taxNumber">
        <el-input v-model="form.taxNumber" placeholder="请输入税号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="负责人" prop="contactPerson">
        <el-input v-model="form.contactPerson" placeholder="请输入负责人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="11" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客服电话" prop="customerServicePhone">
        <el-input v-model="form.customerServicePhone" placeholder="请输入客服电话" maxlength="11" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商家介绍" prop="description">
        <editor v-model="form.description" :min-height="192" />
      </el-form-item>
      <h3>商家图片</h3>
      <el-form-item label="店铺logo" prop="logo">
        <imageUpload v-model="form.logo" :limit="1" unique="logo" />
      </el-form-item>
      <el-form-item label="店铺列表图片" prop="image">
        <imageUpload v-model="form.image" :limit="1" unique="image" />
      </el-form-item>
      <el-form-item label="店铺内页图片" prop="innerImages">
        <imageUpload v-model="form.innerImages" unique="innerImages" :limit="5" />
      </el-form-item>
      <h3>运营配置</h3>
      <el-form-item label="推荐状态" prop="hotStatus">
        <el-switch v-model="form.hotStatus"> </el-switch>
      </el-form-item>
      <el-form-item label="营业时间" prop="businessHours">
        <el-input v-model="form.businessHours" placeholder="请输入营业时间" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商家序号" prop="orderIndex">
        <el-input-number v-model="form.orderIndex" :min="1" label="排序" :precision="0"></el-input-number>
        <div class="hint">*数字越大在越前面，排序有限需要，其次是创建时间</div>
      </el-form-item>
      <el-form-item label="营业状态" prop="businessStatus">
        <el-select v-model="form.businessStatus" placeholder="请输入状态" clearable style="width: 240px">
          <el-option label="正常" :value="true" />
          <el-option label="停业" :value="false" />
        </el-select>
        <div class="hint">*如果选择已停业，则不需要根据营业时间计算营业状态</div>
      </el-form-item>
      <div class="flex-bet">
        <h3>商品分类</h3>
        <div><el-button type="primary" size="mini" @click="addBusinessProductCategory">新增</el-button></div>
      </div>
      <el-form-item label="分类名称">
        <draggable v-model="form.businessProductCategoryList" :options="{ group: 'typeLabel' }">
          <div class="flex" v-for="(v,i) in form.businessProductCategoryList" :key="i">
            <el-input v-model="v.categoryName" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
            <div><el-button size="mini" type="danger" @click="deleteBusinessProductCategory(i)">删除</el-button></div>
          </div>
        </draggable>
        <div class="hint">*可拖动排序</div>
      </el-form-item>
      <h3>页面分享配置</h3>
      <el-form-item label="分享标题" prop="shareTitle">
        <el-input style="width: 470px;" v-model="form.shareTitle" placeholder="" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="分享图片" prop="shareImage">
        <imageUpload v-model="form.shareImage" unique="shareImage" :limit="1" />
      </el-form-item>
      <el-form-item label="">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import GDMap from '@/components/gdMap/index'
import { cnAreaTree, businessCategoryList, getLocation, getAddress, businessAdd, businessInfo, businessEdit } from '@/api/shop'
import AMapLoader from '@amap/amap-jsapi-loader';
import qqmapPlus from 'qqmap-plus';
import draggable from 'vuedraggable';
export default {
  components: {
    draggable,
    GDMap
  },
  data () {
    return {
      form: {
        businessName: undefined,
        categoryId: undefined,
        location: undefined,
        provinces: undefined,
        address: undefined,
        longitudeLatitude: undefined,
        entityName: undefined,
        taxNumber: undefined,
        contactPerson: undefined,
        contactPhone: undefined,
        customerServicePhone: undefined,
        description: undefined,
        logo: undefined,
        image: undefined,
        innerImages: undefined,
        businessHours: undefined,
        orderIndex: 1,
        shelvedStatus: true,
        businessStatus: true,
        provinceCode: undefined,
        provinceName: undefined,
        cityCode: undefined,
        hotStatus: false,
        businessProductCategoryList: [{}],
        shareImage: undefined,
        shareTitle: undefined
      },
      rules: {
        businessName: [
          { required: true, message: '请输入商户名称', trigger: 'change' }
        ],
        categoryId: [
          { required: true, message: '请选择商家分类', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请输入商家位置', trigger: 'change' }
        ],
        provinces: [
          { required: true, message: '请选择所在城市', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'change' }
        ],
        longitudeLatitude: [
          { required: true, message: '请选择经纬度', trigger: 'change' }
        ],
        contactPerson: [
          { required: true, message: '请输入负责人', trigger: 'change' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'change' }
        ],
        customerServicePhone: [
          { required: true, message: '请输入客服电话', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入商家介绍', trigger: 'change' }
        ],
        logo: [
          { required: true, message: '请上传店铺logo', trigger: 'change' }
        ],
        image: [
          { required: true, message: '请上传店铺列表图片', trigger: 'change' }
        ],
        innerImages: [
          { required: true, message: '请上传店铺内页图片', trigger: 'change' }
        ],
        orderIndex: [
          { required: true, message: '请输入商家序号', trigger: 'change' }
        ],
        businessStatus: [
          { required: true, message: '请选择营业状态', trigger: 'change' }
        ],
        businessCategoryList: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
      },
      areaTrea: [],
      shopTypeList: [],
      map: null,
      markers: [],
      lnglat: [],
      geocoder: null,
      buttonLoading: false,
      // 地图回显
      defaultMarker: {
        location: {}
      }
    }
  },
  mounted () {
    this.getCnAreaTree();
    this.getShopTypeList();
    if (this.$route.query.businessId) {
      this.getDetails(this.$route.query.businessId)
    } else {
      // this.initMap()
      this.$refs.gdMapRef.initAMap();
    }
    document.documentElement.scrollTop = 0
  },
  methods: {
    getCnAreaTree () {
      cnAreaTree().then(res => {
        this.areaTrea = res.data?.children
      })
    },
    addBusinessProductCategory () {
      this.form.businessProductCategoryList.push({})
    },
    deleteBusinessProductCategory (index) {
      this.form.businessProductCategoryList.splice(index, 1)
    },
    getShopTypeList () {
      businessCategoryList().then(res => {
        this.shopTypeList = res.data
      })
    },
    // 省市区选择
    handleChange (value) {
      this.form.provinces = value;
      this.form.provinceCode = value[0];
      this.form.provinceName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[0];
      this.form.cityCode = value[1];
      this.form.cityName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[1];
      this.form.areaCode = value[2];
      this.form.areaName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[2];
    },
    getDetails (id) {
      businessInfo(id).then(res => {
        res.data.provinces = [res.data.provinceCode, res.data.cityCode, res.data.areaCode];
        res.data.longitudeLatitude = res.data.longitude + ',' + res.data.latitude;
        res.data.innerImages = res.data.innerImages.join(',');
        if (res.data.businessCategoryList && res.data.businessCategoryList.length > 0) {
          res.data.businessCategoryList = res.data.businessCategoryList.map(item => {
            return item.categoryId
          })
        } else {
          res.data.businessCategoryList = []
        }
        this.defaultMarker = {
          location: {
            lng: res.data.longitude,
            lat: res.data.latitude
          },
          address: res.data.address,
        }
        this.form = res.data;
        let param = {
          lat: res.data.latitude,
          long: res.data.longitude
        }
        // this.initMap(param)
        this.$refs.gdMapRef.initAMap()
      })
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let formCopy = JSON.parse(JSON.stringify(this.form))
          if (formCopy.businessProductCategoryList && formCopy.businessProductCategoryList.length > 0) {
            let arr = []
            formCopy.businessProductCategoryList.forEach((item, index) => {
              if (item.categoryName) {
                item.orderIndex = formCopy.businessProductCategoryList.length - index;
                arr.push(item);
              }
            })
            formCopy.businessProductCategoryList = arr
          }
          if (formCopy.businessCategoryList && formCopy.businessCategoryList.length > 0) {
            formCopy.businessCategoryList = formCopy.businessCategoryList.map(item => {
              return { categoryId: item }
            })
          }
          formCopy.innerImages = formCopy.innerImages.split(',')
          formCopy.updateTime = undefined;
          formCopy.createTime = undefined;
          this.buttonLoading = true;
          if (this.form.businessId != null) {
            businessEdit(formCopy).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel()
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            businessAdd(formCopy).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel()
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    // 取消按钮
    cancel () {
      this.$router.go(-1)
    },
    // 表单重置
    reset () {
      this.form = {
        businessName: undefined,
        categoryId: undefined,
        location: undefined,
        provinces: undefined,
        address: undefined,
        longitudeLatitude: undefined,
        entityName: undefined,
        taxNumber: undefined,
        contactPerson: undefined,
        contactPhone: undefined,
        customerServicePhone: undefined,
        description: undefined,
        logo: undefined,
        image: undefined,
        innerImages: undefined,
        businessHours: undefined,
        orderIndex: 1,
        shelvedStatus: true,
        businessStatus: true,
        provinceCode: undefined,
        provinceName: undefined,
        cityCode: undefined,
        businessProductCategoryList: [{}]
      };
      this.resetForm("form");
    },
    mapchange (e) {
      console.log(e);
      this.form.address = e.address;
      this.form.longitudeLatitude = e.location.lng + ',' + e.location.lat;
      this.form.latitude = e.location.lat;
      this.form.longitude = e.location.lng;

    },
    //地图
    initMap (obj = {}) {
      var that = this;
      // EXUBZ-5PT6U-ZF5VL-2BM27-ZOST7-VYFIP
      // KNZBZ-YSB3S-QGNOH-6UN4N-LVGUZ-OJFPQ
      // KNZBZ-YSB3S-QGNOH-6UN4N-LVGUZ-OJFPQ
      // TBYBZ-WT2W6-4RXSK-E234N-BH7S7-VGBJ4
      let key = "KNZBZ-YSB3S-QGNOH-6UN4N-LVGUZ-OJFPQ"
      qqmapPlus.init(key, () => {
        if (obj.lat) {
          that.form.longitude = obj.long;
          that.form.latitude = obj.lat;
        } else {
          obj.long = that.form.longitude = 114.30656433105469;
          obj.lat = that.form.latitude = 30.588281906904278;
        }
        var myLatlng = new qq.maps.LatLng(obj.lat, obj.long);
        var myOptions = {
          zoom: 16,
          center: myLatlng,
          mapTypeId: qq.maps.MapTypeId.ROADMAP
        };
        that.map = new qq.maps.Map(document.getElementById('container1'), myOptions);
        var marker = new qq.maps.Marker({
          position: myLatlng,
          map: that.map
        });
        // 获取点击后的地址
        qq.maps.event.addListener(that.map, 'click', function (event) {
          if (marker) {
            marker.setMap(null);
            marker = null;
          }
          // that.$refs.formRef.clearValidate();
          // 获取点击后的地图坐标
          that.form.longitude = event.latLng.getLng();
          that.form.latitude = event.latLng.getLat();
          that.$set(that.form, 'longitudeLatitude', event.latLng.getLng() + ',' + event.latLng.getLat());
          marker = new qq.maps.Marker({
            position: new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng()),
            map: that.map
          });
          getLocation(event.latLng.getLat() + ',' + event.latLng.getLng()).then(res => {
            that.form.address = res.data.address + res.data.formatted_addresses.rough
          })
        });
      });
    },
    // initAMap (obj = {}) {
    //   let that = this;
    //   AMapLoader.load({
    //     key: 'b687ba2e44f3a44c09e51bea6ac5b434',
    //     version: '2.0',
    //     plugins: [
    //       'AMap.Scale',
    //       'AMap.ToolBar',
    //       'AMap.ControlBar',
    //       'AMap.Geocoder',
    //       'AMap.Marker',
    //       'AMap.CitySearch',
    //       'AMap.Geolocation',
    //       'AMap.AutoComplete',
    //       'AMap.InfoWind'
    //     ]
    //   })
    //     .then((AMap) => {
    //       if (obj.lat) {
    //         that.form.longitude = obj.long;
    //         that.form.latitude = obj.lat;
    //       } else {
    //         that.form.longitude = 114.418836;
    //         that.form.latitude = 30.479715;
    //         obj.long = 114.418836;
    //         obj.lat = 30.479715;
    //       }
    //       this.map = new AMap.Map('container1', {
    //         resizeEnable: true,
    //         viewMode: '2D',
    //         zoomEnable: true,
    //         dragEnable: true,
    //         doubleClickZoom: true,
    //         zoom: 12,
    //         center: [that.form.longitude, that.form.latitude]
    //       });
    //       this.setMarker([that.form.longitude, that.form.latitude]);
    //       this.map.on('click', this.clickMapHandler);
    //     })
    //     .catch((e) => {
    //       console.log(e);
    //     });
    // },
    // //  添加标记
    // setMarker (lnglat) {
    //   console.log('位置', lnglat); // lnglat=[经度,纬度]
    //   let marker = new AMap.Marker({
    //     position: lnglat
    //   });
    //   marker.setMap(this.map);
    //   this.removeMarker();
    //   this.markers.push(marker); // 在data中记录标记点
    // },
    // // 删除之前后的标记点
    // removeMarker () {
    //   // 判断是否存被标记的点，有--->移除
    //   if (this.markers) {
    //     this.map.remove(this.markers);
    //   }
    // },
    // // 通过坐标获得地址
    // getAddressCode () {
    //   var that = this;
    //   var lat = parseFloat(this.form.latitude);
    //   var lng = parseFloat(this.form.longitude);
    //   let location = lng + ',' + lat;
    //   getAddressByLat(location).then((res) => {
    //     that.form.address = res.data.formatted_address;
    //     this.$forceUpdate();
    //   });
    // },
    // // 点击地图事件获取经纬度，并添加标记
    // clickMapHandler (e) {
    //   this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
    //   // 获取点击后的地图坐标
    //   this.form.longitude = e.lnglat.getLng();
    //   this.form.latitude = e.lnglat.getLat();
    //   this.$set(this.form, 'addressLocal', e.lnglat.getLat() + ',' + e.lnglat.getLng());
    //   this.setMarker(this.lnglat);
    //   this.getAddressCode();
    // },
  }
}
</script>

<style lang='scss' scoped>
.el-form {
  width: 800px;
}
.hint {
  font-size: 12px;
  color: red;
}
.map-box {
  width: calc(100% - 120px);
  height: 300px;
  margin-bottom: 30px;
  box-sizing: border-box;
  margin-left: 120px;
}
.flex {
  display: flex;
  margin-bottom: 10px;
  .el-button {
    margin-left: 10px;
  }
}
h3 {
  width: 120px;
  font-weight: 700;
  text-align: right;
}
.flex-bet {
  display: flex;
  justify-content: space-between;
}
</style>