<template>
  <el-dialog
    :title="!dataForm.fetchId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="100px"
    >
      <el-form-item label="自提点名称" prop="fetchName" style="width:530px;">
        <el-input v-model="dataForm.fetchName"></el-input>
      </el-form-item>
      <el-form-item label="自提点图片" prop="images">
        <imgs-upload v-model="dataForm.images"></imgs-upload>
      </el-form-item>
      <el-form-item label="电话号码">
        <el-col :span="16">
          <el-col :span="6">
            <el-form-item>
              <el-input
                v-model="dataForm.phonePrefix"
                placeholder="区号"
                maxlength="10"
                @change="checkPhonePrefix"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <span>——</span>
            <!-- <el-link type="info" disabled>——</el-link> -->
          </el-col>
          <el-col :span="14">
            <el-form-item prop="phone">
              <el-input
                v-model="dataForm.phone"
                placeholder="手机/电话号码"
                maxlength="15"
                @change="checkPhone"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="8"></el-col>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">营业</el-radio>
          <el-radio :label="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="省市区" prop="status">
        <el-col :span="6">
          <el-form-item prop="province">
            <el-select v-model="dataForm.provinceId" placeholder="请选择" @change="selectProvince">
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="city">
            <el-select v-model="dataForm.cityId" placeholder="请选择" @change="selectCity">
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="area">
            <el-select v-model="dataForm.areaId" placeholder="请选择" @change="mapLocation(true)">
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="地址" prop="addr">
        <el-input v-model="dataForm.addr" @change="mapLocation">
          <el-button slot="append" icon="el-icon-location" @click="mapLocation">定位</el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <baidu-map
          class="map"
          :scroll-wheel-zoom="false"
          :center="center"
          @moving="syncCenterAndZoom"
          @moveend="syncCenterAndZoom"
          @zoomend="syncCenterAndZoom"
          :zoom="zoom"
        >
          <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
          <bm-marker :position="center" :dragging="false" @click="infoWindowOpen">
            <bm-info-window :show="show" @close="infoWindowClose" @open="infoWindowOpen">自提点所在位置</bm-info-window>
          </bm-marker>
        </baidu-map>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import ImgsUpload from '@/components/imgs-upload'
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        fetchId: null,
        fetchName: null,
        images: null,
        phonePrefix: null,
        phone: null,
        status: 0,
        provinceId: null,
        province: null,
        cityId: null,
        city: null,
        areaId: null,
        area: null,
        addr: null,
        lng: null,
        lat: null
      },
      provinceList: [],
      cityList: [],
      areaList: [],
      show: false,
      center: {
        lng: 113.327955,
        lat: 23.136783
      },
      zoom: 18,
      dataRule: {
        fetchName: [
          { required: true, message: '自提点名称不能为空', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '省份不能为空', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '城市不能为空', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '县/区不能为空', trigger: 'blur' }
        ],
        addr: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机/电话号码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    ImgsUpload
  },
  methods: {
    init (fetchId) {
      this.dataForm.fetchId = fetchId || 0
      this.visible = true
      this.show = false
      this.setCenter()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.$refs.dataForm.resetFields()
        this.cityList = []
        this.areaList = []
        this.dataForm.provinceId = null
        this.dataForm.cityId = null
        this.dataForm.areaId = null
        this.dataForm.phonePrefix = null
        this.listAreaByParentId().then(({ data }) => {
          this.provinceList = data
          if (this.dataForm.fetchId) {
            this.getDataInfo()
          }
        })
      })
    },
    // 获取店铺详情数据
    getDataInfo () {
      this.$http({
        url: this.$http.adornUrl('/admin/fetch/info/' + this.dataForm.fetchId),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.dataForm = data
        this.listAreaByParentId(data.provinceId).then(({ data }) => {
          this.cityList = data
        })
        this.listAreaByParentId(data.cityId).then(({ data }) => {
          this.areaList = data
          this.center = {
            lng: this.dataForm.lng,
            lat: this.dataForm.lat
          }
        })
      })
    },
    listAreaByParentId (pid) {
      if (!pid) pid = 0
      return this.$http({
        url: this.$http.adornUrl(`/admin/area/listByPid`),
        method: 'get',
        params: this.$http.adornParams({ pid })
      })
    },
    // 选择省
    selectProvince (val) {
      this.dataForm.cityId = null
      this.dataForm.city = ''
      // 获取城市的select
      this.listAreaByParentId(val).then(({ data }) => {
        this.cityList = data
      })
      this.mapLocation(true)
    },
    // 选择市
    selectCity (val) {
      this.dataForm.areaId = null
      this.dataForm.area = ''
      // 获取区的select
      this.listAreaByParentId(val).then(({ data }) => {
        this.areaList = data
      })
      this.mapLocation(true)
    },
    // 重置表单
    resetForm () {
      this.$refs.dataForm.resetFields()
    },
    checkPhonePrefix () {
      if (this.dataForm.phonePrefix) {
        var reg = /^[0-9]*$/
        if (!reg.test(this.dataForm.phonePrefix)) {
          this.message('只能输入数字')
          this.dataForm.phonePrefix = null
          return false
        }
      }
    },
    checkPhone () {
      if (this.dataForm.phone) {
        var reg = /^[0-9]*$/
        if (!reg.test(this.dataForm.phone)) {
          this.message('只能输入数字')
          this.dataForm.phone = null
          return false
        }
      }
    },
    // 表单提交
    dataFormSubmit () {
      this.getAreaName()
      this.dataForm.lng = this.center.lng
      this.dataForm.lat = this.center.lat
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/admin/fetch'),
            method: this.dataForm.fetchId ? 'put' : 'post',
            data: this.$http.adornData(this.dataForm)
          }).then(({ data }) => {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          })
        }
      })
    },
    message (msg) {
      this.$message({
        message: msg,
        type: 'error',
        duration: 1500
      })
    },
    /**
     * 初始化地图数据
     */
    setCenter () {
      this.center = null
      this.center = {
        lng: 113.327955,
        lat: 23.136783
      }
      this.zoom = 18
    },
    /**
     * 获取地图移动后回调的位置参数
     */
    syncCenterAndZoom (e) {
      this.setCenter()
      const { lng, lat } = e.target.getCenter()
      this.center.lng = lng
      this.center.lat = lat
      this.zoom = e.target.getZoom()
    },
    /**
     * 通过省市区id,得到省市区名称
     */
    getAreaName () {
      for (let i = 0; i < this.provinceList.length; i++) {
        if (this.provinceList[i].areaId === this.dataForm.provinceId) {
          // 将省名字保存起来
          this.dataForm.province = this.provinceList[i].areaName
        }
      }
      for (let i = 0; i < this.cityList.length; i++) {
        if (this.cityList[i].areaId === this.dataForm.cityId) {
          // 将市名字保存起来
          this.dataForm.city = this.cityList[i].areaName
        }
      }
      for (let i = 0; i < this.areaList.length; i++) {
        if (this.areaList[i].areaId === this.dataForm.areaId) {
          // 将市名字保存起来
          this.dataForm.area = this.areaList[i].areaName
        }
      }
    },
    // 定位地图
    mapLocation (isTrue) {
      let area = ''
      this.getAreaName()
      if (isTrue === true) {
        // 选择省市区时，定位地图
        if (this.dataForm.provinceId) {
          // 省名称
          area = this.dataForm.province
          this.zoom = 6
          console.log('zoom', this.zoom)
          if (this.dataForm.cityId) {
            // 市名称
            area = area + this.dataForm.city
            this.zoom = 10
            if (this.dataForm.areaId) {
              // 区名称
              area = area + this.dataForm.area
              this.zoom = 14
              if (this.dataForm.addr !== null) {
                // 详细地址
                area = this.dataForm.province + this.dataForm.city + this.dataForm.area + this.dataForm.addr
                this.zoom = 18
              }
            }
          }
        }
      } else {
        this.center = null
        if (!this.dataForm.provinceId || !this.dataForm.cityId || !this.dataForm.areaId) {
          this.dataForm.addr = null
          this.errorMsg('请先选择省市区')
          return
        }
        area = this.dataForm.province + this.dataForm.city + this.dataForm.area + this.dataForm.addr
        this.zoom = 18
      }
      this.center = area
    },
    /**
     * 关闭地图说明标签
     */
    infoWindowClose () {
      this.show = false
    },
    /**
     * 打开地图说明标签
     */
    infoWindowOpen () {
      this.show = true
    }
  }
}
</script>
<style lang="scss" >
.map {
  width: 100%;
  height: 500px;
}
</style>
