<!--
@name: 待审核-地址解析
@author: 张泽贤
@time: 2022-04-12
-->
<template>
  <p-card :bordered="false" v-show="showType > 0" class="full-card-panel">
    <a-space slot="title">
      <a-icon type="arrow-left" style="color: #1990ff" @click="back" />
      地址解析
    </a-space>
    <a-space slot="extra">
      <p-button type="primary" :disabled="!current" @click="onSave" :icon="confirmLoading ? 'loading' : ''"> 保存</p-button>
      <p-button @click="back">返回</p-button>
    </a-space>
    <p-grid-form style="margin-bottom: 20px" ref="gird" layout="inline" :span="6" :labelCol="{ span: 7 }" :wrapperCol="{ span: 15 }" @submit="onSearch" :items="queryFromItems"> </p-grid-form>
    <a-row :gutter="16" style="height: calc(100% - 60px)">
      <a-col :span="14" style="height: 100%">
        <p-table
          ref="masterTable"
          style="margin-bottom: 20px"
          dragle
          bordered
          :row-key="rowKey"
          hasRowSelectCheck
          :remoteUrl="{ method: 'post', url: remoteUrl }"
          :scroll="{ x: true, y: 300 }"
          :data-source="dataSource"
          :selectedRowKeys.sync="selectedRowKeys"
          :pagination="20"
          :remoteData="listParams"
          :rowSelectType="1"
          :autoLoad="false"
          :columns="columns"
          @selectChange="tableClick"
        >
        </p-table>
        <a-tabs v-if="showType > 0" type="card" v-model="tabActive">
          <a-tab-pane key="shipper" tab="发货方">
            <p-form-model ref="shipper" :model="shipper" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from">
              <a-row>
                <a-col :span="12">
                  <p-form-model-item label="当前经度">
                    <p-input v-model="shipper.longitude" readOnly />
                  </p-form-model-item>
                </a-col>
                <a-col :span="12">
                  <p-form-model-item label="当前纬度">
                    <p-input v-model="shipper.latitude" readOnly />
                  </p-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <p-form-model-item label="当前地址" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                    <p-input v-model="shipper.address" readOnly />
                  </p-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="12">
                  <p-form-model-item label="新经度">
                    <p-input v-model="shipper.newLongitude" readOnly />
                  </p-form-model-item>
                </a-col>
                <a-col :span="12">
                  <p-form-model-item label="新纬度">
                    <p-input v-model="shipper.newLatitude" readOnly />
                  </p-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <p-form-model-item label="新地址" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                    <p-input v-model="shipper.newAddress" readOnly />
                  </p-form-model-item>
                </a-col>
              </a-row>
            </p-form-model>
          </a-tab-pane>

          <a-tab-pane key="consignee" tab="收货方">
            <p-form-model ref="consignee" :model="consignee" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from">
              <a-row>
                <a-col :span="12">
                  <p-form-model-item label="当前经度">
                    <p-input v-model="consignee.longitude" readOnly />
                  </p-form-model-item>
                </a-col>
                <a-col :span="12">
                  <p-form-model-item label="当前纬度">
                    <p-input v-model="consignee.latitude" readOnly />
                  </p-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <p-form-model-item label="当前地址" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                    <p-input v-model="consignee.address" readOnly />
                  </p-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="12">
                  <p-form-model-item label="新经度">
                    <p-input v-model="consignee.newLongitude" readOnly />
                  </p-form-model-item>
                </a-col>
                <a-col :span="12">
                  <p-form-model-item label="新纬度">
                    <p-input v-model="consignee.newLatitude" readOnly />
                  </p-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <p-form-model-item label="新地址" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                    <p-input v-model="consignee.newAddress" readOnly />
                  </p-form-model-item>
                </a-col>
              </a-row>
            </p-form-model>
          </a-tab-pane>
        </a-tabs>
      </a-col>
      <a-col :span="10" style="height: 100%">
        <div id="address_map" style="height: 100%"></div>
        <div class="addressAnalysis_right_input">
          <p-input id="address_map_input" v-model="map_searchValue" placeholder="请输入关键字：(选定后搜索)" @focus="map_searchValue = ''" />
        </div>
      </a-col>
    </a-row>
  </p-card>
</template>

<script>
import { axios } from '@/utils/request'
import { setColumns, setQuery } from './config.js'
import { UPCLOUD_RDC_TMS_BUSINESS_SERVICE } from '@/config/serviceSettings.js'
let defaultAddressData = () => {
  return {
    address: '',
    longitude: '',
    latitude: '',
  }
}
export default {
  props: {
    showType: {
      type: Number,
      default: 0,
    },
    remoteUrl: {
      type: String,
    },
    saveUrl: {
      type: String,
      default: UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/shipbill/parse_address',
    },
    searchParams: {
      type: Object,
      default: () => ({}),
    },
    rowKey: {
      type: String,
      default: '_row_count',
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
  },
  computed: {},
  data() {
    return {
      selectedRowKeys: [],
      confirmLoading: false,
      tabActive: 'shipper',
      tabList: [
        {
          key: 'shipper',
          tab: '发货方',
        },
        {
          key: 'consignee',
          tab: '收货方',
        },
      ],
      columns: setColumns(this),
      queryFromItems: setQuery(this),
      searchForm: {
        search: '',
      },
      listParams: {},
      current: null,
      shipper: {
        //发货方
        id: '',
        longitude: '',
        latitude: '',
        address: '',
        newLongitude: '',
        newLatitude: '',
        newAddress: '',
      },
      consignee: {
        //收货方
        id: '',
        longitude: '',
        latitude: '',
        address: '',
        newLongitude: '',
        newLatitude: '',
        newAddress: '',
      },
      myMap: '',
      map_searchValue: undefined,
      geocoder: '',
      isSave: false,
      shipperMarker: '',
      consigneeMarker: '',
      modObject: 'shipper',
    }
  },
  watch: {
    selectedRowKeys(values) {
      if (values.length == 0) {
        this.clearAll()
      }
    },
    tabActive(value) {
      this.modObject = value
      this.locationMap(this.current)
    },
    listParams() {
      this.clearAll()
    },
    searchParams(value) {
      if (Object.keys(value).length) {
        this.listParams = value
      }
    },

    showType(v) {
      if (v > 0) {
        this.resetMap()
        if (v == 2) {
          this.listParams = { ...this.searchParams }
        }
        //  this.setMap(this.addressData)
      } else {
        // this.myMap.destroy()
        this.editForm = {
          ...defaultAddressData(),
          newLongitude: '',
          newLatitude: '',
          newAddress: '',
        }
        this.baseMap = defaultAddressData()
        this.map_searchValue = ''
      }
    },
  },
  mounted() {
    this.info()
    //  this.setMap(this.baseMap)
  },
  methods: {
    resetMap() {
      return this.myMap.setCenter([116.397428, 39.90923])
    },
    info() {
      let _this = this
      this.myMap = new AMap.Map('address_map', {
        resizeEnable: true,
        center: [116.397428, 39.90923],
        zoom: 15,
        keyboardEnable: false,
      })

      this.geocoder = new AMap.Geocoder({
        city: '010', //城市设为北京，默认：“全国”
        radius: 1000, //范围，默认：500
      })
      this.myMap.on('click', this.showInfoClick)

      // 查询输入框
      AMap.plugin(['AMap.AutoComplete', 'AMap.PlaceSearch'], function () {
        var autoOptions = {
          input: 'address_map_input', //使用联想输入的input的id
        }
        var autocomplete = new AMap.AutoComplete(autoOptions)
        var placeSearch = new AMap.PlaceSearch({
          map: _this.myMap,
        })
        AMap.Event.addListener(autocomplete, 'select', function (e) {
          // 针对选中的poi实现自己的功能
          placeSearch.setCity(e.poi.adcode)
          placeSearch.search(e.poi.name)
        })
        AMap.Event.addListener(placeSearch, 'markerClick', function (e) {
          _this.regeoCode([e.data.location.lng, e.data.location.lat])
        })
      })
    },

    clearAll() {
      let arr = ['consignee', 'shipper']
      arr.forEach((baseName) => {
        let baseItem = this[baseName]
        for (let key in baseItem) {
          baseItem[key] = ''
        }
      }, this)
      console.log(this.consignee)
    },
    // 返回
    back() {

      this.resetMap()
      this.$emit('back')
    },
    // 点击地图
    showInfoClick(e) {
      this.regeoCode([e.lnglat.getLng(), e.lnglat.getLat()])
    },
    // 点击地图、回显
    regeoCode(lnglat) {
      let _this = this
      if (this.modObject === 'shipper') {
        this.shipperMarker && this.myMap.remove(this.shipperMarker)
        this.shipperMarker = new AMap.Marker({
          position: new AMap.LngLat(lnglat[0], lnglat[1]),
        })
        this.myMap.add(this.shipperMarker)
      } else if (this.modObject === 'consignee') {
        this.consigneeMarker && this.myMap.remove(this.consigneeMarker)
        this.consigneeMarker = new AMap.Marker({
          position: new AMap.LngLat(lnglat[0], lnglat[1]),
        })
        this.myMap.add(this.consigneeMarker)
      }

      this.myMap.setCenter(lnglat)

      this.geocoder.getAddress(lnglat, function (status, result) {
        if (status === 'complete' && result.regeocode) {
          var regeocode = result.regeocode
          let newAddress = regeocode.formattedAddress.split(regeocode.addressComponent.district)[1]

          if (_this.modObject === 'shipper') {
            _this.shipper = Object.assign(_this.shipper, {
              newLongitude: lnglat[0],
              newLatitude: lnglat[1],
              newAddress: newAddress,
            })
          } else if (_this.modObject === 'consignee') {
            _this.consignee = Object.assign(_this.consignee, {
              newLongitude: lnglat[0],
              newLatitude: lnglat[1],
              newAddress: newAddress,
            })
          } else {
            return
          }

          let info = []
          info.push('地址：' + regeocode.formattedAddress)
          var infoWindow = new AMap.InfoWindow({
            content: info.join('<br/>'),
            offset: new AMap.Pixel(0, -25),
          })
          infoWindow.open(_this.myMap, lnglat)
        } else {
          layer.msg('根据经纬度查询地址失败')
        }
      })
    },
    // 查询
    onSearch(event, form) {
      event.preventDefault()
      this.listParams = { ...this.listParams, ...form.getFieldsValue() }
    },
    // 重置
    onReset() {
      this.searchForm = {
        search: '',
      }
    },
    // 保存
    onSave() {
      let obj = { ...this.current }
      let arr = ['consignee', 'shipper']
      arr.forEach((baseName) => {
        let baseItem = this[baseName]
        obj[baseName + 'Address'] = baseItem.newAddress
        obj[baseName + 'Latitude'] = baseItem.newLatitude
        obj[baseName + 'Longitude'] = baseItem.newLongitude
        // obj[baseName + 'Id'] =  this.current[baseName+'Id']
        // obj[baseName + 'Code'] =  this.current[baseName+'Code']
        // obj[baseName + 'Name'] =  this.current[baseName+'Name']
      }, this)
      // obj.shipbillId = this.current.shipbillId

      this.confirmLoading = true
      return axios
        .post(this.saveUrl, obj)
        .then((response) => {
          this.confirmLoading = false
          this.resetMap()
          if (response.success) {
            this.isSave = true
            this.$message.success(response.message)
            this.$refs.masterTable.reload()
            arr.forEach((baseName) => {
              let baseItem = this[baseName]
              for (let key in baseItem) {
                baseItem[key] = ''
              }
            }, this)
          } else {
            this.$exception(response)
          }
        })
        .catch((e) => {
          this.confirmLoading = false
        })
    },

    checkTabs(key) {
      let current = this[key]
      let { longitude, latitude, address } = current

      if (longitude && latitude) {
        this.regeoCode([longitude, latitude])
      } else if (address) {
        this.map_searchValue = address
        var placeSearch = new AMap.PlaceSearch({
          map: this.myMap,
        })
        placeSearch.search(address)
        AMap.Event.addListener(placeSearch, 'markerClick', function (e) {
          regeoCode([e.data.location.lng, e.data.location.lat])
        })
      } else {
        this.resetMap()
      }
    },
    // 通过带过来的经纬度定位地图
    locationMap(data) {
      if (!data) {
        return this.clearAll()
      }
      // key: 'shipper',
      // tab: '发货方',
      let _this = this
      let { shipperId, shipperAddress, shipperLongitude, shipperLatitude } = data
      let { consigneeId, consigneeAddress, consigneeLongitude, consigneeLatitude } = data
      //收货方
      this.shipper.address = shipperAddress
      this.shipper.longitude = shipperLongitude
      this.shipper.latitude = shipperLatitude
      this.shipper.id = shipperId

      this.consignee.address = consigneeAddress
      this.consignee.longitude = consigneeLongitude
      this.consignee.latitude = consigneeLatitude
      this.consignee.id = consigneeId

      this.checkTabs(this.tabActive)
    },
    // 表格点击
    tableClick(selectedRowKeys, selectedRows) {
      this.current = selectedRows[0] || null
      this.shipper.newLongitude = this.current.shipperLongitude;
      this.shipper.newLatitude = this.current.shipperLatitude;
      this.shipper.newAddress = this.current.shipperAddress;
      this.consignee.newLongitude = this.current.consigneeLongitude;
      this.consignee.newLatitude = this.current.consigneeLatitude;
      this.consignee.newAddress = this.current.consigneeAddress;
      this.locationMap(this.current)
    },
    // 解析对象修改
    modObjectChange(e) {
      if (e.target.value === 'shipper') {
        this.regeoCode([this.shipper.newLongitude, this.shipper.newLatitude])
      } else {
        this.regeoCode([this.consignee.newLongitude, this.consignee.newLatitude])
      }
    },
    getFieldsValue() {
      return this.$refs.gird.form.getFieldsValue()
    },
  },
}
</script>
