<template>
  <div v-loading="dialogLoading" :element-loading-text="loadingText">
    <el-row :gutter="15" style="margin-bottom: 80px; width: 90%; margin-left: 5%">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px" label-position="top">
        <el-col :span="12">
          <el-form-item label="门店名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入门店名称" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="门店免洗额度" prop="balance">
            <el-input v-model="formData.balance" placeholder="请输入门店免洗额度" :disabled="isEditMode" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="门店编码" prop="code">
            <el-input v-model="formData.code" :maxlength="4" @input="handleInput" :disabled="isEditMode"
                      placeholder="请输入门店编码" clearable :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="门店类型" prop="storeType">
            <el-select v-model="formData.storeType" placeholder="请选择门店类型" @change="changeStoreType"
                       :disabled="isEditMode" :style="{ width: '100%' }">
              <el-option v-for="(item, index) in storeTypeOptions" :key="index" :label="item.label" :value="item.value"
                         :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属工厂" prop="factoryId">
            <el-select v-model="formData.factoryId" placeholder="请选择所属工厂" :disabled="isEditMode"
                       :style="{ width: '100%' }">
              <el-option v-for="item in factorys" :label="item.factoryName" :value="item.id"
                         :key="item.factoryName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="门店状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择门店状态" :style="{ width: '100%' }">
              <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.label" :value="item.value"
                         :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>


        <!-- <el-col :span="8">
            <el-form-item label-width="127px" label="是否打印小票" prop="isPrint">
                <el-select v-model="formData.isPrint" placeholder="请选择是否打印小票" :style="{ width: '100%' }">
                    <el-option v-for="(item, index) in isPrintOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-form-item label-width="127px" label="是否参与结算" prop="isSettlement">
                <el-select v-model="formData.isSettlement" placeholder="请选择是否参与结算" :style="{ width: '100%' }">
                    <el-option v-for="(item, index) in isSettlementOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-form-item label-width="127px" label="条码打印姓名" prop="isCarCodePrintName">
                <el-select v-model="formData.isCarCodePrintName" placeholder="请选择条码是否打印姓名" :style="{ width: '100%' }">
                    <el-option v-for="(item, index) in isCarCodePrintNameOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-form-item label-width="127px" label="小票打印姓名" prop="isPrintName">
                <el-select v-model="formData.isPrintName" placeholder="请选择小票是否打印客户姓名" :style="{ width: '100%' }">
                    <el-option v-for="(item, index) in isPrintNameOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-form-item label-width="127px" label="小票打印数量" prop="printNum">
                <el-input-number v-model="formData.printNum" placeholder="请输入小票打印数量" :min="0" :step-strictly="true" :style="{ width: '100%' }"> </el-input-number>
            </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label-width="113px" label="负责人姓名" prop="contactName">
            <el-input v-model="formData.contactName" placeholder="请输入负责人姓名" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="113px" label="负责人职务" prop="contactPost">
            <el-input v-model="formData.contactPost" placeholder="请输入负责人职务" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="127px" label="负责人身份证" prop="contactIdcard">
            <el-input v-model="formData.contactIdcard" placeholder="请输入负责人身份证" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="113px" label="负责人电话" prop="contactWorkTel">
            <el-input v-model="formData.contactWorkTel" placeholder="请输入负责人电话" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="113px" label="负责人手机" prop="contactPhone">
            <el-input v-model="formData.contactPhone" placeholder="请输入负责人手机" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="113px" label="负责人传真" prop="contactFax">
            <el-input v-model="formData.contactFax" placeholder="请输入负责人传真" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="113px" label="负责人邮箱" prop="contactEmail">
            <el-input v-model="formData.contactEmail" placeholder="请输入负责人邮箱" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="113px" label="负责人邮编" prop="contactZipCode">
            <el-input v-model="formData.contactZipCode" placeholder="请输入负责人邮编" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="8">
            <el-form-item label-width="106px" label="负责人QQ" prop="contactQq">
                <el-input v-model="formData.contactQq" placeholder="请输入负责人QQ" clearable :style="{ width: '100%' }"> </el-input>
            </el-form-item>
        </el-col> -->

        <el-col :span="8">
          <el-form-item label="开店时间" prop="openDate">
            <el-date-picker v-model="formData.openDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            :style="{ width: '100%' }" placeholder="请选择开店时间" clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="127px" label="开始营业时间" prop="businessStartTime">
            <el-time-picker v-model="formData.businessStartTime" format="HH:mm" value-format="HH:mm"
                            :picker-options="{ selectableRange: '00:00:00-23:59:59' }" :style="{ width: '100%' }"
                            placeholder="请选择开始营业时间" clearable></el-time-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="127px" label="结束营业时间" prop="businessEndTime">
            <el-time-picker v-model="formData.businessEndTime" format="HH:mm" value-format="HH:mm"
                            :picker-options="{ selectableRange: '00:00:00-23:59:59' }" :style="{ width: '100%' }"
                            placeholder="请选择结束营业时间" clearable></el-time-picker>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="所属省份" prop="provinceId">
            <el-select size="small" style="width: 200px" v-model="formData.provinceId" placeholder="请选择省份（直辖市）"
                       v-on:change="changeProvince()">
              <el-option v-for="item in provinces" :label="item.areaName" :value="item.areaId"
                         :key="item.areaName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属城市" prop="cityId">
            <el-select size="small" style="width: 200px; margin-left: 10px" v-model="formData.cityId"
                       placeholder="请选择城市" v-on:change="changeCity">
              <el-option v-for="item in citys" :label="item.areaName" :value="item.areaId"
                         :key="item.areaName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属地区" prop="areaId">
            <el-select size="small" style="width: 200px; margin-left: 10px" v-model="formData.areaId"
                       placeholder="请选择区（县）" v-on:change="changeArea">
              <el-option v-for="item in areas" :label="item.areaName" :value="item.areaId"
                         :key="item.areaName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="搜索地址" prop="address">
            <el-autocomplete style="width: 100%" popper-class="autoAddressClass" v-model="formData.address"
                             :fetch-suggestions="querySearchAsync" :trigger-on-focus="false" placeholder="详细地址"
                             @select="handleSelect" clearable>
              <template slot-scope="{ item }">
                <em class="el-icon-search fl mgr10" />
                <div style="overflow: hidden">
                  <div class="title" style="display: table-cell">{{ item.title }}</div>
                  <span class="address ellipsis">{{ item.address }}</span>
                </div>
              </template>
            </el-autocomplete>
            <div id="baidu-map-container"
                 style="width: 100%; margin-top: 20px; margin-bottom: 20px; height: 400px"></div>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="门牌号" prop="addressDetail">
            <el-input v-model="formData.addressDetail" placeholder="请输入门牌号" clearable :style="{ width: '100%' }"
                      size="medium"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="企业性质" prop="companyType">
            <el-input v-model="formData.companyType" placeholder="请输入企业性质" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="办公面积" prop="officeArea">
            <el-input v-model="formData.officeArea" oninput="value=value.replace(/[^0-9]/g,'')"
                      placeholder="请输入办公面积" clearable :style="{ width: '100%' }">
              <template slot="append">（平米）</template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="企业业务" prop="companyDetail">
            <el-input v-model="formData.companyDetail" type="textarea" placeholder="请输入企业业务" clearable
                      :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="门店图片" prop="companyPic">
            <el-upload ref="companyPic" :file-list="companyPicfileList" :action="companyPicAction"
                       :before-upload="companyPicBeforeUpload" :on-success="companyPicUploadSuccess"
                       :on-remove="companyPicOnRemove" list-type="picture" accept="image/*">
              <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的文件</div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="营业执照" prop="companyLicencePic">
            <el-upload ref="companyLicencePic" :file-list="companyLicencePicfileList" :action="companyLicencePicAction"
                       :before-upload="companyLicencePicBeforeUpload" :on-success="companyLicencePicUploadSuccess"
                       :on-remove="companyLicencePicOnRemove" list-type="picture" accept="image/*">
              <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的文件</div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="同城配送门店id" prop="wxStoreId">
            <el-input v-model="formData.wxStoreId" placeholder="请输入微信同城配送门店id" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" style="margin-left: 5%">提交</el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </div>
  </div>
</template>
<script>
import { getStore, addStore, updateStore } from '@/api/system/store'
import { listArea } from '@/api/system/area'
import { listFactory } from '@/api/system/factory'

export default {
  components: {},
  props: [],
  data() {
    return {
      dialogLoading: true,
      loadingText: '查询中',
      formData: {
        code: undefined,
        name: undefined,
        factoryId: undefined,
        storeType: '0',
        status: '0',
        isPrint: '0',
        isSettlement: '0',
        isCarCodePrintName: '0',
        isPrintName: '0',
        printNum: 0,
        contactName: undefined,
        contactPost: undefined,
        contactIdcard: undefined,
        contactWorkTel: undefined,
        contactPhone: undefined,
        contactFax: undefined,
        contactEmail: undefined,
        contactZipCode: undefined,
        officeArea: 0,
        openDate: null,
        businessStartTime: '09:00:00',
        businessEndTime: '17:30:00',
        companyType: undefined,
        contactQq: undefined,
        companyDetail: undefined,
        companyPic: null,
        companyLicencePic: null,
        province: '', // 省
        city: '', // 市
        area: '', // 区
        address: '',
        addressDetail: '',
        wxStoreId: ''
      },
      rules: {
        code: [
          {
            required: true,
            message: '请输入门店编码',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入门店名称',
            trigger: 'blur'
          }
        ],
        factoryId: [
          {
            required: true,
            message: '请选择所属工厂',
            trigger: 'change'
          }
        ],
        contactName: [
          {
            required: true,
            message: '请输入负责人姓名',
            trigger: 'blur'
          }
        ],
        contactPost: [
          {
            required: true,
            message: '请输入负责人职务',
            trigger: 'blur'
          }
        ],
        contactIdcard: [
          {
            required: true,
            trigger: 'blur',
            validator: this.checkIdCardNumber
          }
        ],
        contactPhone: [
          {
            required: true,
            trigger: 'blur',
            validator: this.checkPhone
          }
        ],
        contactEmail: [
          {
            trigger: 'blur',
            validator: this.checkEmail
          }
        ],
        openDate: [
          {
            required: true,
            message: '请选择开店时间',
            trigger: 'change'
          }
        ],
        businessStartTime: [
          {
            required: true,
            message: '请选择开始营业时间',
            trigger: 'change'
          }
        ],
        businessEndTime: [
          {
            required: true,
            message: '请选择结束营业时间',
            trigger: 'change'
          }
        ],
        companyType: [
          {
            required: true,
            message: '请输入企业性质',
            trigger: 'blur'
          }
        ],

        companyDetail: [
          {
            required: true,
            message: '请输入企业业务',
            trigger: 'blur'
          }
        ],
        provinceId: [
          {
            required: true,
            message: '请选择所属省份',
            trigger: 'change'
          }
        ],
        cityId: [
          {
            required: true,
            message: '请选择所属城市',
            trigger: 'change'
          }
        ],
        areaId: [
          {
            required: true,
            message: '请选择所属地区',
            trigger: 'change'
          }
        ],
        address: [
          {
            required: true,
            message: '请输入具体地址',
            trigger: 'blur'
          }
        ]
      },
      storeTypeOptions: [
        {
          label: '直营店',
          value: '0'
        },
        {
          label: '加盟店',
          value: '1'
        }
      ],
      statusOptions: [
        {
          label: '正常',
          value: '0'
        },
        {
          label: '禁用',
          value: '1'
        }
      ],
      isPrintOptions: [
        {
          label: '是',
          value: '0'
        },
        {
          label: '否',
          value: '1'
        }
      ],
      isSettlementOptions: [
        {
          label: '是',
          value: '0'
        },
        {
          label: '否',
          value: '1'
        }
      ],
      isCarCodePrintNameOptions: [
        {
          label: '是',
          value: '0'
        },
        {
          label: '否',
          value: '1'
        }
      ],
      isPrintNameOptions: [
        {
          label: '是',
          value: '0'
        },
        {
          label: '否',
          value: '1'
        }
      ],
      companyPicfileList: [],
      companyLicencePicfileList: [],
      companyPicAction: `${process.env.VUE_APP_BASE_API}` + '/common/uploadOSS',
      companyLicencePicAction: `${process.env.VUE_APP_BASE_API}` + '/common/uploadOSS',
      provinces: [],
      citys: [],
      areas: [],
      factorys: [],
      isEditMode: false,
      isEditFactory: false
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getProvince(1)
    this.getFactoryList()
  },
  async mounted() {
    await this.loadBMap('muIMwle2eOkTHf453rwRNgMa0W83j2PX') //加载引入BMap
    this.initBaiduMap()
  },
  methods: {
    /** 获取所属工厂 */
    getFactoryList() {
      listFactory().then((response) => {
        this.factorys = response.rows
      })
    },
    checkTel(rule, value, callback) {
      const regex = /^\d{3}-\d{3}-\d{4}$/ // 电话正则表达式
      if (!regex.test(value)) {
        callback(new Error('请输入正确的电话号'))
      } else {
        callback()
      }
    },
    checkEmail(rule, value, callback) {
      const regex = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/ // 邮箱正则表达式
      if (!regex.test(value) && value != '') {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    },
    checkPhone(rule, value, callback) {
      const regex = /^1[0-9]{10}$/ // 手机号正则表达式
      if (!regex.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    },
    checkIdCardNumber(rule, value, callback) {
      const regex = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/ // 身份证正则表达式
      if (!regex.test(value)) {
        callback(new Error('请输入正确的身份证号码'))
      } else {
        callback()
      }
    },
    changeStoreType() {
      if (this.formData.storeType === '0') {
        this.formData.factoryId = 1
        this.isEditFactory = true
      } else {
        this.isEditFactory = false
        this.formData.factoryId = null
      }
    },
    handleInput() {
      if (this.inputValue.length > 4) {
        this.inputValue = this.inputValue.slice(0, 4)
      }
      this.inputValue = this.inputValue.replace(/\D/g, '')
    },
    setInitData(storeId) {
      this.id = storeId
      this.companyPicList = []
      this.companyLicencePicList = []
      if (storeId != undefined && storeId != '') {
        this.dialogLoading = true
        this.loadingText = '查询中'
        getStore(this.id)
          .then((res) => {
            this.formData = res.data
            this.isEditMode = true
            //获取所属城市和所属地区
            this.getProvince(2, this.formData.provinceId)
            this.getProvince(3, this.formData.cityId)
            this.dialogLoading = false
            //地图定位
            var point = new BMap.Point(this.formData.longitude, this.formData.latitude)
            this.map.centerAndZoom(point, 19)
            this.mk = new BMap.Marker(point, {
              enableDragging: true
            }) //创建一个图像标注实例，enableDragging：是否启用拖拽，默认为false
            this.map.addOverlay(this.mk) //将覆盖物添加到地图中

            if (this.formData.companyPic) {
              this.companyPicfileList = [
                {
                  url: this.formData.companyPic
                }
              ]
            }
            if (this.formData.companyLicencePic) {
              this.companyLicencePicfileList = [
                {
                  url: this.formData.companyLicencePic
                }
              ]
            }
            this.resetForm('elForm')
          })
          .catch((e) => {
            this.dialogLoading = false
            this.$message.error(e.data.msg)
          })
      } else {
        this.dialogLoading = false
        this.formData.factoryId = 1
        this.isEditFactory = true
      }
    },
    /** 获取省份 */
    getProvince(level, parentId) {
      let provinceParams = {
        level: level,
        parentId: parentId
      }
      listArea(provinceParams).then((response) => {
        if (level === 1) {
          this.provinces = response.data
        } else if (level === 2) {
          this.citys = response.data
        } else {
          this.areas = response.data
        }
      })
    },
    /** 获取城市 */
    changeProvince() {
      let cityParams = {
        parentId: this.formData.provinceId
      }
      const selectedOption = this.provinces.find((option) => option.areaId === this.formData.provinceId)
      this.formData.provinceName = selectedOption ? selectedOption.areaName : null
      listArea(cityParams).then((response) => {
        this.citys = response.data
      })
      if (this.formData.cityId != null) {
        this.formData.cityId = null
        this.formData.areaId = null
        this.areas = []
      }
    },
    /** 获取区县 */
    changeCity() {
      let cityParams = {
        parentId: this.formData.cityId
      }
      const selectedOption = this.citys.find((option) => option.areaId === this.formData.cityId)
      this.formData.cityName = selectedOption ? selectedOption.areaName : null
      listArea(cityParams).then((response) => {
        this.areas = response.data
      })
      if (this.formData.areaId != null) {
        this.formData.areaId = null
      }
    },
    /** 获取区县 */
    changeArea() {
      const selectedOption = this.areas.find((option) => option.areaId === this.formData.areaId)
      this.formData.areaName = selectedOption ? selectedOption.areaName : null
    },
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) return
        // TODO 提交表单
        // TODO 提交表单
        console.log(this.formData)

        if (this.companyPicfileList && this.companyPicfileList.length > 0) {
          this.formData.companyPic = this.companyPicfileList[0].url
        } else {
          this.formData.companyPic = ''
        }
        if (this.companyLicencePicfileList && this.companyLicencePicfileList.length > 0) {
          this.formData.companyLicencePic = this.companyLicencePicfileList[0].url
        } else {
          this.formData.companyLicencePic = ''
        }

        if (this.formData.hasOwnProperty('addrPoint')) {
          this.formData.longitude = this.formData.addrPoint.lng
          this.formData.latitude = this.formData.addrPoint.lat
        }

        this.dialogLoading = true
        this.loadingText = '保存中'
        if (this.id == undefined || this.id == '') {
          addStore(this.formData)
            .then((res) => {
              this.$message('添加成功')
              this.dialogLoading = false
              this.$emit('closeDialog')
              this.$root.$emit('refreshList')
            })
            .catch((e) => {
              this.dialogLoading = false
              this.$message.error(e.data.msg)
            })
        } else {
          updateStore(this.formData)
            .then((res) => {
              this.$message('保存成功')
              this.dialogLoading = false
              this.$emit('closeDialog')
              this.$root.$emit('refreshList')
            })
            .catch((e) => {
              this.dialogLoading = false
              this.$message.error(e.data.msg)
            })
        }
      })
    },
    closeDialog() {
      var ctx = this
      this.$confirm('是否关闭表单，关闭后数据将丢失？')
        .then(function() {
          ctx.$emit('closeDialog')
        })
        .then(() => {
        })
        .catch(() => {
        })
    },
    onOpen() {
    },
    onClose() {
      this.$refs['elForm'].resetFields()
    },
    close() {
      this.$emit('update:visible', false)
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    companyPicBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    companyPicUploadSuccess(response, file, fileList) {
      this.companyPicfileList = fileList
      if (this.companyPicfileList.length > 1) {
        this.companyPicfileList.splice(0, 1)
      }
      this.companyPicfileList[0].url = this.companyPicfileList[0].response.data.src
    },
    companyPicOnRemove(file, fileList) {
      this.companyPicfileList = fileList
    },
    companyLicencePicBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    companyLicencePicUploadSuccess(response, file, fileList) {
      this.companyLicencePicfileList = fileList
      if (this.companyLicencePicfileList.length > 1) {
        this.companyLicencePicfileList.splice(0, 1)
      }
      this.companyLicencePicfileList[0].url = this.companyLicencePicfileList[0].response.data.src
    },
    companyLicencePicOnRemove(file, fileList) {
      this.companyLicencePicfileList = fileList
    },
    // 初始化百度地图
    initBaiduMap() {
      var that = this
      this.map = new BMap.Map('baidu-map-container', {
        enableMapClick: false
      }) //新建地图实例，enableMapClick:false ：禁用地图默认点击弹框
      var point = new BMap.Point(113.30765, 23.12005)
      this.map.centerAndZoom(point, 19)
      this.mk = new BMap.Marker(point, {
        enableDragging: true
      }) //创建一个图像标注实例，enableDragging：是否启用拖拽，默认为false
      this.map.addOverlay(this.mk) //将覆盖物添加到地图中
      this.mk.addEventListener('dragend', function(e) {
        that.getAddrByPoint(e.point) //拖拽结束后调用逆地址解析函数，e.point为拖拽后的地理坐标
      })
      var navigationControl = new BMap.NavigationControl({
        //创建一个特定样式的地图平移缩放控件
        anchor: BMAP_ANCHOR_TOP_RIGHT, //靠右上角位置
        type: BMAP_NAVIGATION_CONTROL_SMALL //SMALL控件类型
      })
      this.map.addControl(navigationControl) //将控件添加到地图
      var geolocationControl = new BMap.GeolocationControl({
        anchor: BMAP_ANCHOR_BOTTOM_LEFT
      }) //创建一个地图定位控件
      geolocationControl.addEventListener('locationSuccess', function(e) {
        //绑定定位成功后事件
        that.getAddrByPoint(e.point) //定位成功后调用逆地址解析函数
      })
      geolocationControl.addEventListener('locationError', function(e) {
        //绑定定位失败后事件
        console.log(e.message)
      })
      this.map.addControl(geolocationControl) //将控件添加到地图
      this.map.addEventListener('click', function(e) {
        //给地图绑定点击事件
        that.getAddrByPoint(e.point) //点击后调用逆地址解析函数
      })
      this.geolocation()
    },
    /**
     * 浏览器定位函数
     */
    geolocation() {
      var that = this
      var geolocation = new BMap.Geolocation()
      geolocation.getCurrentPosition(
        function(res) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            that.getAddrByPoint(res.point) //当成功时，调用逆地址解析函数
          } else {
            console.log('failed' + this.getStatus()) //失败时，弹出失败状态码
          }
        },
        {
          enableHighAccuracy: true
        }
      ) //enableHighAccuracy：是否要求浏览器获取最佳效果，默认为false
    },
    /** 逆向解析地址 point */
    getAddrByPoint(point) {
      var that = this
      var geco = new BMap.Geocoder()
      geco.getLocation(point, function(res) {
        console.log(res) //内容见下图
        that.mk.setPosition(point) //重新设置标注的地理坐标
        that.map.panTo(point) //将地图的中心点更改为给定的点
        that.addressInfo.address = res.address //记录该点的详细地址信息
        that.addressInfo.addrPoint = point //记录当前坐标点
      })
    },
    querySearchAsync(str, cb) {
      var options = {
        onSearchComplete: function(res) {
          //检索完成后的回调函数
          var s = []
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < res.getCurrentNumPois(); i++) {
              s.push(res.getPoi(i))
            }
            cb(s) //获取到数据时，通过回调函数cb返回到<el-autocomplete>组件中进行显示
          } else {
            cb(s)
          }
        }
      }
      var local = new BMap.LocalSearch(this.map, options) //创建LocalSearch构造函数
      local.search(str) //调用search方法，根据检索词str发起检索
    },
    handleSelect(item) {
      this.formData.address = item.address + item.title //记录详细地址，含建筑物名
      this.formData.addrPoint = item.point //记录当前选中地址坐标
      this.map.clearOverlays() //清除地图上所有覆盖物
      this.mk = new BMap.Marker(item.point) //根据所选坐标重新创建Marker
      this.map.addOverlay(this.mk) //将覆盖物重新添加到地图中
      this.map.panTo(item.point) //将地图的中心点更改为选定坐标点
    },
    /**
     * 确认选择
     */
    confirmSelect() {
      this.$emit('confirmMapAddress', this.addressInfo)
      this.openMap = false
    },

    /**
     * 取消选择
     */
    cancel() {
      this.$emit('cancelMap')
    },
    /**
     * 动态加载百度地图api函数
     * @param {String} ak  百度地图AK，必传
     */
    loadBMap(ak) {
      return new Promise(function(resolve, reject) {
        if (typeof window.BMap !== 'undefined') {
          resolve(window.BMap)
          return true
        }
        window.onBMapCallback = function() {
          resolve(window.BMap)
        }
        let script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = 'https://api.map.baidu.com/api?v=3.0&ak=' + ak + '&callback=onBMapCallback'
        script.onerror = reject
        document.head.appendChild(script)
      })
    }
  }
}
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>
