<template>
  <div class="app-container" v-loading="dialogLoading" :element-loading-text="loadingText">
    <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="120px">
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-card class="box-card" shadow="never">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="门店名称" prop="name">
                  <el-input v-model="formData.name" placeholder="请输入门店名称" clearable />
                </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
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="门店类型" prop="storeType">
                  <el-select
                    v-model="formData.storeType"
                    placeholder="请选择门店类型"
                    @change="changeStoreType"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="(item, index) in storeTypeOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    />
                  </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-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-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="门店免洗额度" prop="balance">
                  <el-input
                    v-model="formData.balance"
                    placeholder="请输入门店免洗额度"
                    :disabled="isEditMode"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="box-card" shadow="never">
            <div slot="header">
              <span>负责人信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="负责人姓名" prop="contactName">
                  <el-input
                    v-model="formData.contactName"
                    placeholder="请输入负责人姓名"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="手机号码" prop="contactPhone">
                  <el-input
                    v-model="formData.contactPhone"
                    placeholder="请输入负责人手机"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="负责人职务" prop="contactPost">
                  <el-input
                    v-model="formData.contactPost"
                    placeholder="请输入负责人职务"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="身份证号" prop="contactIdcard">
                  <el-input
                    v-model="formData.contactIdcard"
                    placeholder="请输入负责人身份证"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话" prop="contactWorkTel">
                  <el-input
                    v-model="formData.contactWorkTel"
                    placeholder="请输入负责人电话"
                    clearable
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="电子邮箱" prop="contactEmail">
                  <el-input
                    v-model="formData.contactEmail"
                    placeholder="请输入负责人邮箱"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-tab-pane>

        <!-- 营业信息 -->
        <el-tab-pane label="营业信息" name="business">
          <el-card class="box-card" shadow="never">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="开店时间" prop="openDate">
                  <el-date-picker
                    v-model="formData.openDate"
                    type="date"
                    placeholder="请选择开店时间"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item 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' }"
                    placeholder="请选择开始营业时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item 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' }"
                    placeholder="请选择结束营业时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="企业性质" prop="companyType">
                  <el-input
                    v-model="formData.companyType"
                    placeholder="请输入企业性质"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="办公面积" prop="officeArea">
                  <el-input
                    v-model="formData.officeArea"
                    placeholder="请输入办公面积"
                    clearable
                  >
                    <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"
                    :rows="3"
                    placeholder="请输入企业业务"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="box-card" shadow="never">
            <div slot="header">
              <span>图片信息</span>
            </div>
            <el-row :gutter="20">
              <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-card"
                    accept="image/*"
                  >
                    <i class="el-icon-plus"></i>
                    <div class="el-upload__tip" slot="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-card"
                    accept="image/*"
                  >
                    <i class="el-icon-plus"></i>
                    <div class="el-upload__tip" slot="tip">只能上传不超过 2MB 的图片文件</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-tab-pane>

        <!-- 地址信息 -->
        <el-tab-pane label="地址信息" name="address">
          <el-card class="box-card" shadow="never">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="所在地区">
                  <el-row :gutter="10">
                    <el-col :span="8">
                      <el-form-item prop="provinceId">
                        <el-select
                          v-model="formData.provinceId"
                          placeholder="请选择省份"
                          @change="changeProvince"
                          style="width: 100%"
                        >
                          <el-option
                            v-for="item in provinces"
                            :label="item.areaName"
                            :value="item.areaId"
                            :key="item.areaName"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item prop="cityId">
                        <el-select
                          v-model="formData.cityId"
                          placeholder="请选择城市"
                          @change="changeCity"
                          style="width: 100%"
                        >
                          <el-option
                            v-for="item in citys"
                            :label="item.areaName"
                            :value="item.areaId"
                            :key="item.areaName"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item prop="areaId">
                        <el-select
                          v-model="formData.areaId"
                          placeholder="请选择区县"
                          @change="changeArea"
                          style="width: 100%"
                        >
                          <el-option
                            v-for="item in areas"
                            :label="item.areaName"
                            :value="item.areaId"
                            :key="item.areaName"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="详细地址" prop="address">
                  <el-autocomplete
                    class="address-input"
                    v-model="formData.address"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="请输入详细地址"
                    @select="handleSelect"
                    clearable
                    style="width: 100%"
                  >
                    <template slot-scope="{ item }">
                      <div class="address-suggestion">
                        <i class="el-icon-location-outline"></i>
                        <div class="suggestion-content">
                          <div class="title">{{ item.title }}</div>
                          <div class="address">{{ item.address }}</div>
                        </div>
                      </div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <div id="baidu-map-container" class="map-container"></div>
              </el-col>
              <el-col :span="24">
                <el-form-item label="门牌号" prop="addressDetail">
                  <el-input
                    v-model="formData.addressDetail"
                    placeholder="请输入门牌号"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="同城配送门店" prop="wxStoreId">
                  <el-input
                    v-model="formData.wxStoreId"
                    placeholder="请输入微信同城配送门店id"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-tab-pane>
      </el-tabs>

      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;

  .box-card {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .map-container {
    width: 100%;
    height: 400px;
    margin: 20px 0;
    border-radius: 4px;
    overflow: hidden;
  }

  .address-suggestion {
    display: flex;
    align-items: flex-start;
    padding: 8px 0;

    i {
      margin-right: 8px;
      margin-top: 4px;
      color: #409EFF;
    }

    .suggestion-content {
      flex: 1;

      .title {
        font-weight: 500;
        margin-bottom: 4px;
      }

      .address {
        font-size: 13px;
        color: #909399;
      }
    }
  }
}

.dialog-footer {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-upload--picture-card) {
  width: 148px;
  height: 148px;
  line-height: 148px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 148px;
  height: 148px;
}

:deep(.el-tabs__nav-wrap) {
  background-color: #fff;
  padding: 0 20px;
}

:deep(.el-tabs__item) {
  height: 40px;
  line-height: 40px;
}
</style>

<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: '查询中',
      activeTab: 'basic',
      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'
          }
        ],
        storeType: [
          {
            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'
          }
        ],

        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>
