<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" :disabled="pageType == 'show' || pageType == 'check'"
          placeholder="请输入商户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="商家分类" prop="businessCategoryList">
        <el-select v-model="form.businessCategoryList" :disabled="pageType=='show'||pageType=='check'" 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" :disabled="pageType=='show'||pageType=='check'" 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" :disabled="pageType == 'show' || pageType == 'check'" 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" :disabled="pageType == 'show' || pageType == 'check'" 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" :readonly="pageType == 'show' || pageType == 'check'" :defaultMarker="defaultMarker"
        @change="mapchange" />
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input v-model="form.enterpriseName" :disabled="pageType == 'show' || pageType == 'check'"
          placeholder="请输入企业名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="统一信用代码" prop="uscCode">
        <el-input v-model="form.uscCode" :disabled="pageType == 'show' || pageType == 'check'" placeholder="请输入税号"
          clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="经营范围" prop="businessScope">
        <el-input v-model="form.businessScope" :disabled="pageType == 'show' || pageType == 'check'"
          placeholder="请输入负责人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客服电话" prop="customerServicePhone">
        <el-input v-model="form.customerServicePhone" :disabled="pageType == 'show' || pageType == 'check'"
          placeholder="请输入客服电话" maxlength="11" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商家介绍" prop="description">
        <el-input type="textarea" v-model="form.description" :disabled="pageType == 'show' || pageType == 'check'"
          placeholder="请输入商家介绍" maxlength="500" clearable @keyup.enter.native="handleQuery" :autosize="{ minRows: 1 }"
          show-word-limit resize="none" />
        <!-- <editor v-model="form.description" :disabled="pageType=='show'||pageType=='check'" :min-height="192" /> -->
      </el-form-item>
      <h3>商家图片</h3>
      <el-form-item label="店铺列表图片" prop="image">
        <imageUpload v-model="form.image" :disabled="pageType == 'show' || pageType == 'check'" :limit="1"
          unique="image" />
      </el-form-item>
      <el-form-item label="店铺内页图片" prop="innerImages">
        <imageUpload v-model="form.innerImages" :disabled="pageType == 'show' || pageType == 'check'"
          unique="innerImages" :limit="5" />
      </el-form-item>
      <h3>运营配置</h3>
      <!-- <el-form-item label="推荐状态" prop="hotStatus">
        <el-switch v-model="form.hotStatus" :disabled="pageType=='show'||pageType=='check'"> </el-switch>
      </el-form-item> -->
      <el-form-item label="营业时间" prop="businessHours">
        <el-input v-model="form.businessHours" :disabled="pageType == 'show' || pageType == 'check'"
          placeholder="请输入营业时间" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商家序号" prop="orderIndex">
        <el-input-number v-model="form.orderIndex" :disabled="pageType == 'show' || pageType == 'check'" :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" :disabled="pageType == 'show' || pageType == 'check'"
          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 v-if="pageType!='show'&&pageType!='check'"><el-button type="primary" size="mini" @click="addBusinessProductCategory">新增</el-button></div>
      </div> -->
      <!-- <el-form-item label="分类名称">
        <draggable :disabled="pageType=='show'||pageType=='check'" v-model="form.businessProductCategoryList" :options="{ group: 'typeLabel' }">
          <div class="flex" v-for="(v,i) in form.businessProductCategoryList" :key="i">
            <el-input :disabled="pageType=='show'||pageType=='check'" v-model="v.categoryName" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
            <div v-if="pageType!='show'&&pageType!='check'"><el-button size="mini" type="danger" @click="deleteBusinessProductCategory(i)">删除</el-button></div>
          </div>
        </draggable>
        <div class="hint" v-if="pageType!='show'&&pageType!='check'">*可拖动排序</div>
      </el-form-item> -->
      <!-- <h3>页面分享配置</h3>
      <el-form-item label="分享标题" prop="shareTitle">
        <el-input style="width: 470px;" :disabled="pageType=='show'||pageType=='check'" v-model="form.shareTitle" placeholder="" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="分享图片" prop="shareImage">
        <imageUpload v-model="form.shareImage" :disabled="pageType=='show'||pageType=='check'" unique="shareImage" :limit="1" />
      </el-form-item> -->
      <div v-if="pageType == 'check' || pageType == 'show' || pageType == 'infoReview'">
        <h3>审核</h3>
        <el-form-item label="审核" prop="auditStatus">
          <el-radio-group v-model="form.auditStatus" :disabled="pageType == 'show'">
            <el-radio :label="AuditStatusEnum.AUDIT_APPROVED">审核通过</el-radio>
            <el-radio :label="AuditStatusEnum.AUDIT_REJECTED">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="理由" :prop="form.auditStatus === AuditStatusEnum.AUDIT_REJECTED ? 'auditResult' : ''">
          <el-input type="textarea" :rows="3" maxlength="50" placeholder="" v-model="form.auditResult"
            :disabled="pageType == 'show'" />
        </el-form-item>
      </div>
      <el-form-item label="">
        <el-button :loading="buttonLoading" v-if="pageType == 'check' || pageType == 'infoReview'" type="primary"
          @click="checkSubmitForm">确 定</el-button>
        <el-button :loading="buttonLoading" v-if="pageType != 'check' && pageType != 'show' && pageType != 'infoReview'"
          type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel()">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { AuditStatusEnum } from '@/utils/statusEnum.js'
import GDMap from '@/components/gdMap/index'
import { cnAreaTree, businessCategoryList, getLocation, businessUpdateRecordAudit, businessAdd, businessInfo, businessEdit, businessApplyInfo, businessApplyAudit, businessUpdateRecordInfo } from '@/api/shop'
import AMapLoader from '@amap/amap-jsapi-loader';
import qqmapPlus from 'qqmap-plus';
import draggable from 'vuedraggable';
export default {
  props: {
    pageClass: {
      type: 'popup' | 'page',
      default: 'page'
    }
  },
  components: {
    draggable,
    GDMap
  },
  data() {
    return {
      AuditStatusEnum,
      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' }
        ],
        auditStatus: [
          { required: true, message: '请选择审核状态', trigger: 'change' }
        ],
        auditResult: [
          { required: true, message: '请输入理由', trigger: 'change' }
        ]
      },
      areaTrea: [],
      shopTypeList: [],
      map: null,
      markers: [],
      lnglat: [],
      geocoder: null,
      buttonLoading: false,
      // 地图回显
      defaultMarker: {
        location: {}
      },
      pageType: undefined
    }
  },
  mounted() {
    this.getCnAreaTree();
    this.getShopTypeList();
    console.log("this.$route.query == mounted")
    if (this.pageClass == 'page') {
      if (this.$route.query.type) {
        this.pageType = this.$route.query.type
      }
      if (this.$route.query.businessId) {
        let businessId = this.$route.query.businessId;
        this.getDetails(businessId)
      } else if (this.$route.query.businessAuditId) {
        let businessAuditId = this.$route.query.businessAuditId;
        this.getDetails(businessAuditId)
      } else if (this.$route.query.recordId) {
        this.getDetails(this.$route.query.recordId)
      } else {
        // this.initMap()
        this.$refs.gdMapRef.initAMap();
      }
    }

    document.documentElement.scrollTop = 0
  },
  methods: {
    handlePopup(params) {
      if (params.type) {
        this.pageType = params.type
      }
      if (params.businessId) {
        console.log("params == ", 1)
        this.getDetails(params.businessId)
      } else if (params.businessAuditId) {
        console.log("params == ", 2)
        this.getDetails(params.businessAuditId)
      } else if (params.recordId) {
        console.log("params == ", 3)
        this.getDetails(params.recordId)
      } else {
        // this.initMap()
        this.$refs.gdMapRef.initAMap();
      }
    },

    getCnAreaTree() {
      cnAreaTree().then(res => {
        this.areaTrea = res.data?.children
      })
    },
    addBusinessProductCategory() {
      if (!this.form.businessProductCategoryList || this.form.businessProductCategoryList.length == 0) {
        this.form.businessProductCategoryList = [{}]
      } else {
        this.form.businessProductCategoryList.push({})
      }
      this.$forceUpdate()
    },
    deleteBusinessProductCategory(index) {
      this.form.businessProductCategoryList.splice(index, 1);
      this.$forceUpdate()
    },
    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) {
      console.log("id == ", id)
      let apiFun = businessInfo;
      if (this.pageType == 'show' || this.pageType == 'check') {
        apiFun = businessApplyInfo
      } else if (this.pageType == 'infoReview') {
        apiFun = businessUpdateRecordInfo
      }
      apiFun(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 = []
        }
        // if (!res.data.businessProductCategoryList || res.data.businessProductCategoryList.length <= 0) {
        //   res.data.businessProductCategoryList = [{}]
        // }
        this.defaultMarker = {
          location: {
            lng: res.data.longitude,
            lat: res.data.latitude
          },
          address: res.data.address,
        }
        this.form = res.data;
        if (this.pageType == 'infoReview' || this.pageType == 'check') {
          this.form.auditResult = undefined;
        }
        // let param = {
        //   lat: res.data.latitude,
        //   long: res.data.longitude
        // }
        // this.initMap(param)
        this.$refs.gdMapRef.initAMap()
      })
    },
    checkSubmitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let param = {
            auditStatus: this.form.auditStatus,
            auditResult: this.form.auditResult
          }
          let url = '';
          if (this.pageType == 'check') {
            param.businessAuditId = this.form.businessAuditId;
            url = businessApplyAudit;
          } else {
            param.recordId = this.form.recordId;
            url = businessUpdateRecordAudit;
          }
          url(param).then(res => {
            this.$modal.msgSuccess("审核成功");
            this.cancel(true)
          })
        }
      })
    },
    /** 提交按钮 */
    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) {
            businessEdit(formCopy).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel(true)
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            businessAdd(formCopy).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel(true)
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    // 取消按钮
    cancel(isRefresh = false) {
      if (this.pageClass == 'page') {
        this.$router.go(-1)
      } else {
        this.$emit('callback', isRefresh)
      }
    },
    // 表单重置
    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>