<template>
<!-- 此处为老的油站入住 -->
  <div style="padding:75px 10px;padding-bottom:6%">
    <div style="width:69.5%;position: fixed;top: 0;left: 0;background: #fff;
    padding: 10px 0px;
    width: 69.5%;
    z-index: 1;">
      <div style="display: flex;
    align-items: center;padding-left: 20px;line-height: 28px;">
      <span>油站入驻</span>
      </div>
      <el-divider style="width:100%"></el-divider>
    </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
                ref="refSubCat"
                v-model="addrCode"
                placeholder="请选择"
                :size="$store.getters.size"
                style="width: 100%"
                :options="areaTree"
                @change='changeTrees'
                @active-item-change='changetrees'
                :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 label="中国石油" :value="1" />
                  <el-option label="中国石化" :value="2" />
                  <el-option label="壳牌" :value="3" />
                  <el-option label="民营" :value="4" />
                  <el-option label="中海油" :value="5" />
                  <el-option label="京博" :value="6" />
                  <el-option label="中化石油" :value="7" />
                  <el-option label="山东高速" :value="9" />
                  <el-option label="陕西延长壳牌" :value="10" />
                  <el-option label="山西延长壳牌" :value="11" />
                  <el-option label="河南延长壳牌" :value="12" />
                  <el-option label="其他" :value="8" />
                </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 label="加油站" :value="1" />
                  <el-option label="加气站" :value="2" />
                </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-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-row>

        <el-row>
          <el-row>
            <h2>认证信息</h2>
            <hr>
            <br>
            <br>
          </el-row>

          <el-row>
            <el-col :span="10">
              <el-form-item label="法人姓名" prop="legalName">
                <el-input v-model="oilSiteInfo.legalName" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="法人联系电话" prop="legalPhone">
                <el-input v-model="oilSiteInfo.legalPhone" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">

              <el-form-item label="法人身份证" prop="legalIdcard">
                <el-input v-model="oilSiteInfo.legalIdcard" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="银行卡号" prop="bankCardNo">
                <el-input v-model="oilSiteInfo.bankCardNo" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="10">

              <el-form-item label="收款账户名称" prop="bankCardName">
                <el-input v-model="oilSiteInfo.bankCardName" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="开户行银名称" prop="bankName">
                <el-input v-model="oilSiteInfo.bankName" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="10">

              <el-form-item label="账户性质：公户、个人账户" prop="bankNature">
                <el-input v-model="oilSiteInfo.bankNature" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="开户所属银行" prop="bankDeposit">
                <el-input v-model="oilSiteInfo.bankDeposit" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="10">
              <el-form-item label="营业许可证号" prop="licenseNo">
                <el-input v-model="oilSiteInfo.licenseNo" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="gridNum.row.gutter">
            <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"
                >
                  <i class="el-icon-plus" />
                </el-upload>
                <el-dialog :visible.sync="showSiteImages" :modal="false">
                  <img width="100%" :src="siteImages" alt="">
                </el-dialog>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="营业执照照片" prop="sitelicenseNoImages">
                <el-upload
                  :action="updateFileUrl"
                  :data="{'ossKey':'xingyou','pathKey':'other','encrypt':'PUBLIC'}"
                  list-type="picture-card"
                  :before-upload="imgCompress"
                  :on-preview="sitelicenseNoImagePreview"
                  :on-remove="sitelicenseNoImageRemove"
                  :on-success="sitelicenseNoImageSuccess"
                  :headers="headers"
                  :limit="1"
                >
                  <i class="el-icon-plus" />
                </el-upload>
                <el-dialog :visible.sync="sitelicenseNoImages" :modal="false">
                  <img width="100%" :src="siteImages" alt="">
                </el-dialog>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="24" style="text-align: center;pandding:3% 3%;" class="showbttoms">
            <el-button @click="close">取消</el-button>
            <el-button
              type="primary"
              @click="submit"
            >提交</el-button>
          </el-col>
        </el-row></el-form>
    </el-row>
  </div>
</template>
<script>
import AreaCodeApi from '@/api/base/areaCode'
import oilSiteInfoApi from '@/api/user/oilSiteInfo'
import { imgCompress } from '@/utils'
import utils from '@/utils/encode'
import { getToken } from '@/utils/auth'
import AMap from 'AMap'// 在页面中引入高德地图
import GaodeApi from '@/api/gaode/gaode'
import sysCustomerInfoApi from '@/api/user/sysCustomerInfo'
const JSESSIONID = utils.uuid()

export default {
  data() {
    return {
      userList: [],
      imgCompress,
      headers: {
        'dataSources': 'WEB',
        'Authorization': getToken(),
        'JSESSIONID': JSESSIONID,
        'token': utils.bcrypt(JSESSIONID)
      },
      gridNum: {
        row: {
          gutter: 2
        },
        cols: {
          xs: 24,
          sm: 24,
          md: 12,
          lg: 12,
          xl: 6
        }
      },
      updateFileUrl: process.env.VUE_APP_UPLOAD_URL,
      siteImages: '', // 油站照片
      siteLicenseImages: '', // 营业执照照片
      // 正向地理解析对象
      geography: {
        address: null
      },
      showSiteImages: false,
      sitelicenseNoImages: false,
      affirmData: { // 默认经纬度
        lon: 116.397428,
        lat: 39.90923
      },
      isShowMap: true, // 高德地图div默认展示
      oilSiteInfo: {
        provinceCode: undefined,
        cityCode: undefined,
        areaCode: undefined,
        address: '',
        longitude: 116.397428,
        latitude: 39.90923
      },
      areaTree: [],
      addrCode: [], // 省市区code
      options11: [
        { value: 'XOIL', 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' }
        ]
      }
    }
  },
  computed: {
  },
  created() {
    // sysCustomerInfoApi.findAll().then(res => {
    //   this.userList = res.data
    // })
    AreaCodeApi.getTree().then(res => {
      this.areaTree = res.data
    })
    this.oilSiteInfo = { ...this.oilSiteInfo }
    this.addrCode = [parseInt(this.oilSiteInfo.provinceCode), parseInt(this.oilSiteInfo.cityCode), parseInt(this.oilSiteInfo.areaCode)]
    console.log('++--++--++--++--',this.addrCode)
  },
  mounted() {
    this.loadMap() // 加载地图和相关组件
  },
  methods: {
    userRemoteMethod(value) { // 远程搜索
    if (value) {
      sysCustomerInfoApi.liekQuery(value).then(res => {
        this.userList = res.data
      })
    }
    },

    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
    },

    sitelicenseNoImageRemove(file, fileList) { // 营业执照删除
      this.oilSiteInfo.licenseImage = undefined
      this.siteLicenseImages = undefined
    },
    sitelicenseNoImagePreview(file) { // 营业执照
      this.sitelicenseNoImages = true
    },
    sitelicenseNoImageSuccess(res) { // 营业执照上传成功
      console.log('success')
      this.siteLicenseImages = res.data.publicUrl
      this.oilSiteInfo.licenseImage = res.data.publicUrl
      console.log(this.siteLicenseImages)
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.save(this.oilSiteInfo)
        }
      })
    },
    save() {
      // 保存
      this.setCodeName()
      this.oilSiteInfo.longitude = this.oilSiteInfo.longitude
      this.oilSiteInfo.latitude = this.oilSiteInfo.latitude
      oilSiteInfoApi.save(this.oilSiteInfo).then(res => {
        this.$message.success(res.msg)
        this.$emit('closeDialog')
        this.$emit('getByPage')
        this.$refs['form'].resetFields()
        this.addrCode = []
      })
    },
    changetrees(){
      console.log('lostss')
    },
    setCodeName() {
      console.log('进入这里')
      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
                }
              })
            }
          })
        }
      })
    },
     changeTrees(e){
      console.log(e)
    },
    close() {
      this.$emit('closeDialog')
    },
    loadMap() {
      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)
      var that = this
      AMap.plugin('AMap.Geocoder', function() {
        var geocoder = new AMap.Geocoder({
          city: '010'// 城市，默认：“全国”
        })
        let lnglat = [that.oilSiteInfo.longitude,that.oilSiteInfo.latitude]
        geocoder.getAddress(lnglat, function(status, result) {
          if (status === 'complete'&&result.regeocode) {
            that.oilSiteInfo.address = result.regeocode.formattedAddress;
          }else{
            that.$message.error('根据经纬度查询地址失败')
          }
        });
      })
      map.on('click', (e) => {
        this.oilSiteInfo.longitude = e.lnglat.getLng()
        this.oilSiteInfo.latitude = e.lnglat.getLat()
        // 每点击一次就将坐标点定位在点击处
        marker.setPosition(e.lnglat)
        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
            } else {
              that.$message.error('无法获取地址')
            }
          })
        })
      })
    }, // 正向地理解析
    queryByAddress() {
      var that = this
      if (that.oilSiteInfo.address&&that.oilSiteInfo.longitude&&that.oilSiteInfo.latitude){
        that.$message.error('经纬度和详细地址须有一项为空')
        return;
      }else if (this.oilSiteInfo.longitude&&this.oilSiteInfo.latitude){
        that.loadMap()
      }else if(that.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()

              AMap.plugin('AMap.Geocoder', function() {
                var geocoder = new AMap.Geocoder({
                  city: '010'// 城市，默认：“全国”
                })
                console.log(res.data.geocodes[0].location)
                geocoder.getAddress(res.data.geocodes[0].location, function(status, result) {
                  if (status == 'complete') {
                    that.oilSiteInfo.address = result.regeocode.formattedAddress
                    console.log(result.regeocode.formattedAddress)
                  } else {
                    that.$message.error('无法获取地址')
                  }
                })
              })
            }
          }
        })
      }
    }
  }
}
</script>
<style scoped>
.showbttoms{
  position: fixed;
    bottom: 0%;
    width: 69.5%;
    background: #fff;
    padding: 20px 15px;
    border-top: 1px solid #e6e6e6;
    text-align: right !important;
}
aside {
  background: none;
}
.mymap {
  width: 76%;
  height: 380px;
  display: flex;
  float: left;
}
.image-vessl {
  color: seashell !important;
}
.el-main {
  padding: 0;
  margin-left:20px;
}

.el-divider--horizontal{
  margin: 10px 0;
  }
</style>
