<template>
  <div>
    <el-row>
      <el-form ref="form" :model="oilSiteInfo" :rules="rules" label-width="230px" :size="$store.getters.size">
        <el-row>
          <el-col :span="10">
            <el-form-item label="油站名称" prop="siteName">
              <el-input v-model="oilSiteInfo.siteName" placeholder="请输入油站名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="油站简称" prop="siteAbbr">
              <el-input v-model="oilSiteInfo.siteAbbr" placeholder="请输入油站简称" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="省市区" prop="addrCode">
              <el-cascader
                v-model="addrCode"
                placeholder="请选择"
                :size="$store.getters.size"
                style="width: 100%"
                :options="areaTree"
                :props="{value:'id', label:'areaName', children:'childList'}"
                filterable
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="油站负责人" prop="businessLeader">
              <el-select
                v-model="oilSiteInfo.businessLeader"
                clearable
                filterable
                remote
                reserve-keyword
                placeholder="油站负责人姓名或联系方式"
                :remote-method="userRemoteMethod"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.phone+'('+(item.nickName?item.nickName+'-':'')+item.userCode+')'"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="联系人姓名" prop="siteContacts">
              <el-input v-model="oilSiteInfo.siteContacts" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="手机/座机" prop="siteContactPhone">
              <el-input v-model="oilSiteInfo.siteContactPhone" clearable />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="20">
            <el-col :span="8">
              <el-form-item
                label="油站品牌"
                prop="siteBrand"
              >
                <el-select v-model="oilSiteInfo.siteBrand" clearable>
                  <el-option
                    v-for="item in optionsBrand"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item
                label="油站类型"
                prop="siteType"
              >
                <el-select v-model="oilSiteInfo.siteType" clearable>
                  <el-option
                    v-for="item in optionsSiteType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="油站性质"
                prop="siteNature"
              >
                <el-select v-model="oilSiteInfo.siteNature" clearable>
                  <el-option label="自营油站" :value="1" />
                  <el-option label="渠道油站" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-col :span="8">
              <el-form-item
                label="油站等级"
                prop="siteLevel"
              >
                <el-select v-model="oilSiteInfo.siteLevel" clearable>
                  <el-option label="一级油站" value="A" />
                  <el-option label="二级油站" value="B" />
                  <el-option label="三级油站" value="C" />
                  <el-option label="四级油站" value="D" />
                  <el-option label="五级油站" value="E" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item
                label="是否为高速"
                prop="highSpeedMark"
              >
                <el-select v-model="oilSiteInfo.highSpeedMark" clearable>
                  <el-option label="非高速" :value="0" />
                  <el-option label="高速油站" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="支付方式"
                prop="payMethod"
              >
                <el-select v-model="oilSiteInfo.payMethod" clearable>
                  <el-option label="普通支付方式" :value="1" />
                  <el-option label="联名卡支付" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-col :span="8">
              <el-form-item
                label="油站渠道"
                prop="siteChannel"
              >
                <el-select v-model="oilSiteInfo.siteChannel" clearable>
                  <el-option
                    v-for="item in options11"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="使用类型"
                prop="siteCustomerMark"
              >
                <el-select v-model="oilSiteInfo.siteCustomerMark" clearable>
                  <el-option label="个人油站" :value="1" />
                  <el-option label="公用油站" :value="2" />
                  <el-option label="企业油站" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="21">
            <el-col :span="8">
              <el-form-item
                label="司机二维码支付"
                prop="qrcodePay"
              >
                <el-switch
                  v-model="oilSiteInfo.qrcodePay"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="扫描油站二维码支付"
                prop="qrcodeSitePay"
              >
                <el-switch
                  v-model="oilSiteInfo.qrcodeSitePay"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="司机主动支付"
                prop="activePay"
              >
                <el-switch
                  v-model="oilSiteInfo.activePay"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="提示文案" prop="detailContent">
              <el-input style="width:80%" v-model="oilSiteInfo.detailContent" placeholder="油站详情提示文案" type="textarea" clearable />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>

          <el-container>
            <!-- <el-aside width="310px"> -->
            <el-row style="width:30%;">
              <el-col>
                <el-form-item label="经度" prop="longitude">
                  <el-input v-model="oilSiteInfo.longitude" placeholder="经度" clearable />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="纬度" prop="latitude">
                  <el-input v-model="oilSiteInfo.latitude" placeholder="纬度" clearable />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="详细地址" prop="address">
                  <el-input v-model="oilSiteInfo.address" type="textarea" placeholder="详细地址" clearable />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item>
                  <el-button plain @click="queryByAddress()">搜索</el-button>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- </el-aside> -->
            <el-main>
              <div v-show="isShowMap" id="container_af" class="mymap" />

            </el-main>
          </el-container>
          <el-row>
            <el-col :span="12">
              <!-- <el-form-item label="油站照片" prop="siteImages">
                <el-upload
                  :action="updateFileUrl"
                  :data="{'ossKey':'xingyou','pathKey':'OTHER','encrypt':'PUBLIC'}"
                  list-type="picture-card"
                  :before-upload="imgCompress"
                  :on-preview="headPhotoPreview"
                  :on-remove="headPhotoRemove"
                  :on-success="headPhotoSuccess"
                  :headers="headers"
                  :limit="1"
                  :file-list="fileList"
                >
                  <i class="el-icon-plus" />
                </el-upload>
                <el-dialog :visible.sync="showSiteImages">
                  <img width="100%" :src="siteImages" alt="">
                </el-dialog>
              </el-form-item> -->

              <el-form-item label="油站照片" prop="siteImages">
                <el-upload
                  :action="updateFileUrl"
                  :data="{'ossKey':'xingyou','pathKey':'other','encrypt':'PUBLIC'}"
                  list-type="picture-card"
                  :before-upload="imgCompress"
                  :on-preview="headPhotoPreview"
                  :on-remove="headPhotoRemove"
                  :on-success="headPhotoSuccess"
                  :headers="headers"
                  :limit="1"
                  :file-list="fileList"
                >
                  <i class="el-icon-plus" />
                </el-upload>
                <el-dialog :visible.sync="showSiteImages">
                  <img width="60%" height="60%" :src="siteImages" alt="">
                </el-dialog>
              </el-form-item>

            </el-col>
          </el-row>

        </el-row>

        <el-col :span="24" style="text-align: right">
          <el-button @click="close">取消</el-button>
          <el-button
            type="primary"
            @click="submit"
          >提交</el-button>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>
import oilSiteInfoApi from '@/api/user/oilSiteInfo'
import AreaCodeApi from '@/api/base/areaCode'
import AMap from 'AMap'// 在页面中引入高德地图
import GaodeApi from '@/api/gaode/gaode'
import { imgCompress } from '@/utils'
import utils from '@/utils/encode'
import { getToken } from '@/utils/auth'
import sysCustomerInfoApi from '@/api/user/sysCustomerInfo'
const JSESSIONID = utils.uuid()
export default {
  props: {
    oilSiteInfo: {
      type: Object,
      longitude: 116.397428,
      latitude: 39.90923,
      default() {

      }
    }
  },
  data() {
    return {
      userList: [],
      imgCompress,
      headers: {
        'dataSources': 'WEB',
        'Authorization': getToken(),
        'JSESSIONID': JSESSIONID,
        'token': utils.bcrypt(JSESSIONID)
      },
      fileList: [],
      gridNum: {
        row: {
          gutter: 2
        },
        cols: {
          xs: 24,
          sm: 24,
          md: 12,
          lg: 12,
          xl: 6
        }

      },
      areaTree: [],
      addrCode: [], // 省市区code
      options11: [
        { value: 'XOIL', label: '星油' }
      ],
      optionsBrand: [{ value: '1', label: '中国石油' },
        { value: '2', label: '中国石化' },
        { value: '3', label: '壳牌' },
        { value: '4', label: '民营' },
        { value: '5', label: '中海油' },
        { value: '6', label: '京博' },
        { value: '7', label: '中化石油' },
        { value: '9', label: '山东高速' },
        { value: '10', label: '陕西延长壳牌' },
        { value: '11', label: '山西延长壳牌' },
        { value: '12', label: '河南延长壳牌' },
        { value: '8', label: '其他' }

      ],
      rules: {
        siteName: [
          { required: true, message: '油站名称不能为空', trigger: 'blur' }
        ],
        siteCustomerMark: [
          { required: true, message: '适用类型不能为空', trigger: 'change' }
        ],
        siteNature: [
          { required: true, message: '油站性质不能为空', trigger: 'change' }
        ],
        siteChannel: [
          { required: true, message: '油站渠道不能为空', trigger: 'change' }
        ],
        siteType: [
          { required: true, message: '油站类型不能为空', trigger: 'change' }
        ],
        siteLevel: [
          { required: true, message: '油站等级不能为空', trigger: 'change' }
        ],
        longitude: [
          { required: true, message: '经度不能为空', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '纬度不能为空', trigger: 'blur' }
        ],
        highSpeedMark: [
          { required: true, message: '高速不能为空', trigger: 'change' }
        ],
        payMethod: [
          { required: true, message: '支付方式不能为空', trigger: 'change' }
        ]
      },
      optionsSiteType: [{ value: '1', label: '加油站' },
        { value: '2', label: '加气站' }

      ],
      updateFileUrl: process.env.VUE_APP_UPLOAD_URL,
      siteImages: '', // 油站照片
      siteLicenseImages: '', // 营业执照照片
      // 正向地理解析对象
      geography: {
        address: null
      },
      showSiteImages: false,
      sitelicenseNoImages: false,
      affirmData: { // 默认经纬度
        longitude: 116.397428,
        latitude: 39.90923
      },
      isShowMap: true // 高德地图div默认展示
    }
  },
  watch: {
    oilSiteInfo: {
      handler(newVal, oldVal) {
        if (newVal.longitude !== oldVal.longitude || newVal.latitude !== oldVal.latitude || newVal.id !== oldVal.id) {
          this.loadmap()
        }
        if (newVal.provinceCode !== oldVal.provinceCode || newVal.cityCode !== oldVal.cityCode || newVal.areaCode !== oldVal.areaCode || newVal.id !== oldVal.id) { this.addrCode = [parseInt(this.oilSiteInfo.provinceCode), parseInt(this.oilSiteInfo.cityCode), parseInt(this.oilSiteInfo.areaCode)] }
        if (newVal.siteImages !== oldVal.siteImages) {
          this.siteImages = newVal.siteImages
          this.fileList = []
          this.fileList.push({ name: '油站照片', url: this.oilSiteInfo.siteImages })
        }
      },
      deep: true // true 深度监听
    }
  },
  created() {
    if (this.oilSiteInfo.businessLeader) {
      sysCustomerInfoApi.get(this.oilSiteInfo.businessLeader).then(res => {
        if (res.data == null) {
          this.userList = []
        } else {
          this.userList = [res.data]
        }
      })
    }

    if (this.oilSiteInfo.siteImages) {
      this.siteImages = this.oilSiteInfo.siteImages
      this.fileList.push({ name: '油站照片', url: this.oilSiteInfo.siteImages })
      this.oilSiteInfo.siteImages = undefined
    }
    AreaCodeApi.getTree().then(res => {
      this.areaTree = res.data
    })
    this.addrCode = [parseInt(this.oilSiteInfo.provinceCode), parseInt(this.oilSiteInfo.cityCode), parseInt(this.oilSiteInfo.areaCode)]
  },
  mounted() {
    this.loadmap() // 加载地图和相关组件
  },
  methods: {
    userRemoteMethod(value) { // 远程搜索
    if (value) {
      sysCustomerInfoApi.liekQuery(value).then(res => {
        this.userList = res.data
      })
    }
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.update(this.oilSiteInfo)
        }
      })
    },
    update() {
      // 更新
      this.setCodeName()
      this.oilSiteInfo.longitude = this.oilSiteInfo.longitude
      this.oilSiteInfo.latitude = this.oilSiteInfo.latitude
      oilSiteInfoApi.update(this.oilSiteInfo).then(res => {
        this.$message.success(res.msg)
        this.$emit('closeDialog')
        this.$emit('getByPage')
      })
    },
    close() {
      console.log('关闭页面')
      this.$emit('closeDialog')
    },
    headPhotoRemove(file, fileList) { // 油站照片删除
      this.oilSiteInfo.siteImages = undefined
      this.siteImages = undefined
    },
    headPhotoPreview(file) { // 油站照片预览
      this.showSiteImages = true
    },
    headPhotoSuccess(res) { // 油站照片上传成功
      this.siteImages = res.data.publicUrl
      this.oilSiteInfo.siteImages = res.data.publicUrl
    },
    loadmap() {
      this.oilSiteInfo.longitude = this.oilSiteInfo.longitude
      this.oilSiteInfo.latitude = this.oilSiteInfo.latitude

      console.log(this.affirmData, 'data')
      // 地图示例
      var map = new AMap.Map('container_af', {
        zoom: 16,
        resizeEnable: true,
        center: [this.oilSiteInfo.longitude, this.oilSiteInfo.latitude] // 中心点坐标
      })
      // 创建一个 Marker 实例：
      var marker = new AMap.Marker({
        position: new AMap.LngLat(this.oilSiteInfo.longitude, this.oilSiteInfo.latitude), // 经纬度对象，也可以是经纬度构成的一维数组
        title: '确认位置'
      })
      // 将创建的点标记添加到已有的地图实例：
      map.add(marker)
      console.log('amap', map, marker)
      map.on('click', (e) => {
        this.oilSiteInfo.longitude = e.lnglat.getLng()
        this.oilSiteInfo.latitude = e.lnglat.getLat()
        // 每点击一次就将坐标点定位在点击处
        marker.setPosition(e.lnglat)

        var that = this

        AMap.plugin('AMap.Geocoder', function() {
          var geocoder = new AMap.Geocoder({
            city: '010'// 城市，默认：“全国”
          })
          geocoder.getAddress(e.lnglat, function(status, result) {
            if (status == 'complete') {
              that.oilSiteInfo.address = result.regeocode.formattedAddress
              console.log(result.regeocode.formattedAddress)
            } else {
              that.$message.error('无法获取地址')
            }
          })
        })

        console.log('e', e)
      })
    }, // 正向地理解析
    queryByAddress() {
      if (this.oilSiteInfo.address) {
        this.geography.address = this.oilSiteInfo.address
        console.log('this.gaodraohy：' + this.geography.address)
        GaodeApi.geography(this.geography).then(res => {
          if (res.code === 20000) {
            if (res.data.geocodes.length > 0) {
              // console.log('经纬度', res.data.geocodes[0].location)
              this.oilSiteInfo.longitude = res.data.geocodes[0].location.split(',')[0]
              this.oilSiteInfo.latitude = res.data.geocodes[0].location.split(',')[1]
              // 根据地址搜索经纬度后重新加载地图
              this.loadmap()
            }
          }
        })
      }
    },
    setCodeName() {
      this.oilSiteInfo.provinceCode = this.addrCode[0]
      this.oilSiteInfo.cityCode = this.addrCode[1]
      this.oilSiteInfo.areaCode = this.addrCode[2]

      this.areaTree.forEach(item => {
        if (item.id === this.addrCode[0]) {
          this.oilSiteInfo.provinceName = item.areaName
          console.log(this.oilSiteInfo.provinceName)
        }
        if (item.childList) {
          item.childList.forEach(itemm => {
            if (itemm.id === this.addrCode[1]) {
              this.oilSiteInfo.cityName = itemm.areaName
              console.log(this.oilSiteInfo.cityName)
            }
            if (itemm.childList) {
              itemm.childList.forEach(itm => {
                if (itm.id === this.addrCode[2]) {
                  this.oilSiteInfo.areaName = itm.areaName
                  console.log(this.oilSiteInfo.areaName)
                  return
                }
              })
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped>
aside {
  background: none;
}
.mymap {
  width: 76%;
  height: 380px;
  display: flex;
  float: left;
}
.image-vessl {
  color: seashell !important;
}
.el-main {
  padding: 0;
  margin-left:20px;
}

</style>
