<template>
  <el-form
    ref="ruleForm"
    v-loading="loading"
    :model="ruleForm"
    status-icon
    :rules="rulesThis"
    :size="'small'"
    label-width="100px"
    class="supplierAdd"
  >
    <el-row>
      <el-col :span="24">
        <div class="supplierAdd-title" style="margin: 6px 0 0 10px">基础信息</div></el-col>
      <el-col :span="6">
        <el-form-item label="供应商" prop="supplier">
          <el-select
            v-model="ruleForm.supplier"
            style="width: 100%"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="供应商"
          >
            <el-option
              v-for="item in []"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="门店名称" prop="storeName">
          <el-input
            v-model="ruleForm.storeName"
            style="width: 100%"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="门店名称"
          />
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="门店类型" prop="storeType">
          <el-select
            v-model="ruleForm.storeType"
            style="width: 100%"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="门店类型"
          >
            <el-option
              v-for="item in typeoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item
          label="门店主图"
          prop="storeImage"
          :disabled="id == 'view'"
          class="activity-upload"
        >
          <div v-if="ruleForm.storeImage" class="img-find">
            <img
              v-viewer
              :src="ruleForm.storeImage"
              class="avatar hover fl"
              style="width: 50px; height: 50px"
            >
            <el-link
              v-if="type !== 'view'"
              class="fl"
              :underline="false"
              type="warning"
              style="margin: 0 0 0 16px"
              @click="deleteimg()"
            >删除</el-link>
          </div>
          <div v-else class="btnupload" style="position: relative">
            <i class="el-icon-plus avatar-uploader-icon" />
            <file-upload
              v-if="type !== 'view'"
              class="Upload"
              :disabled="id == 'view'"
              :accept="'.jpg,.png,.jpeg'"
              :multiple="true"
              :uploadcondition="beforeAvatarUpload"
              @UploadErrorEvent="UploadErrorEventsupplier_img"
              @UploadSuccessEvent="UploadSuccessEventsupplier_img"
            />
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="门店地址" prop="storeAddr">
          <div id="map" />
        </el-form-item>
      </el-col>
      <el-col :span="24"><div class="supplierAdd-title">联系人信息</div></el-col>
      <el-col :span="8">
        <el-form-item label="姓名" prop="contactor">
          <el-input
            v-model="ruleForm.contactor"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="姓名"
            maxlength="20"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="ruleForm.mobile"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="手机号"
            maxlength="20"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="电子邮箱" prop="email">
          <el-input
            v-model="ruleForm.email"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="电子邮箱"
            maxlength="50"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="职位" prop="position">
          <el-input
            v-model="ruleForm.position"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="职位"
            maxlength="20"
          />
        </el-form-item>
      </el-col>
    </el-row>

     <el-row class="flex-end">
      <el-button type="primary" @click="save" size="mini">保存</el-button>
     </el-row>
  </el-form>
</template>
<script>
import asyncRequest from '@/apis/service/serviceParam/supplierStore'
import Map from 'ol/Map'; //地图初始化
import * as source from 'ol/source';
import Feature from "ol/Feature"
import Point from "ol/geom/Point"
import TileLayer from 'ol/layer/Tile';
import * as olProj from "ol/proj"
import * as style from "ol/style"
import * as layer from "ol/layer"
import 'ol/ol.css';
import View from 'ol/View';
import resToken from '@/mixins/resToken'
import {
  isLicense,
  isMobile,
  isqz,
  isSpecialSymbol,
  hasSpace,
  isAddr,
  validEmail
} from '@/utils/validate'


let key = "4c3306473a0aa048196208f774b491a5"

/***
 * @props
 *  供应商   supplier
 *  门店名称 storeName
 *  门店类型 storeType
 *  门店主图 storeImage
 *  门店地址 storeAddr
 *  姓名 contactor
 *  手机号 mobile
 *  电子邮箱 email
 *  职位 position
*/
export default {
  name: 'SupplierAdd',
  mixins: [resToken],
  props: ['showModel', 'id', 'type', 'sitem'],
  data() {
    const validatemobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号不能为空！'))
      } else {
        if (!isMobile(value)) {
          callback(new Error('手机号格式不正确！'))
        } else {
          callback()
        }
      }
    }
    const validateAddr = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('详细地址不能为空！'))
      } else {
        if (hasSpace(value)) {
          callback(new Error('不能出现/回车/换行符！'))
        } else if (isSpecialSymbol(value)) {
          callback(new Error('不能使用英文特殊字符！'))
        } else if (isAddr(value)) {
          callback()
        } else {
          callback(new Error('详细地址填写不规范！'))
        }
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('邮箱不能为空！'))
      } else {
        if (!validEmail(value)) {
          callback(new Error('邮箱格式不正确！'))
        } else {
          callback()
        }
      }
    }
    return {
      map: null,
      feature:null,
      loading: false,
      hand_name: '',
      typeoptions: [
        { value: '0', label: '正式供应商' },
        { value: '1', label: '临时供应商' }
      ],
      title: '添加供应商',
      showModelThis: this.showModel,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      ruleForm: {
      supplier:"",
        storeName:"",
        storeType:"",
        storeImage:"",
        storeAddr:[],
        contactor:"",
        mobile:"",
        email:"",
        position:"",
      },
      rulesThis: this.rules,
      rules: {
        supplier: [{ required: true, message: '请选择供应商', trigger: 'change' }],
        storeName: [{ required: true, message: '请输入门店名称', trigger: 'change' }],
        storeType: [{ required: true, message: '请选择门店类型', trigger: 'change' }],
        storeImage: [{ required: true, message: '请上传门店主图', trigger: 'change' }],
        storeAddr: [{ required: true, message: '请选择门店地址', trigger: 'change',validator(rule,value,callback){
          console.log(value)
          if ((!Array.isArray(value) && !value) || (Array.isArray(value) && value.length === 0)) {
            callback(new Error('门店地址不能为空！'))
          } else {
            callback()
          }
        }}],
        contactor: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        mobile: [{ required: true, validator: validatemobile, trigger: 'blur' }],
        email: [{ required: true, validator: validEmail, trigger: 'blur' }],
        position: [{ required: true, message: '职位不能为空', trigger: 'blur' }],
      }
    }
  },
  mounted() {
    this.initMap()
    this.registerMapEvent()
    this.initForm()
  },
  methods: {
    initMap(){
      this.map = new Map({
        layers:[
          new TileLayer({
            source: new source.XYZ({
                url: 'http://t{0-7}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=' + key
            })
          }),
          new TileLayer({
            source: new source.XYZ({
                url: "http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=" + key
            })
          }),
        ],
        target:"map",
        view: new View({
          projection: 'EPSG:4326',
          center: [115.7, 39.4],
          zoom: 16
        })
      })


      const iconFeature = new Feature();
      const feature = new Feature({
        geometry: new Point([0, 0])
      })

      feature.setStyle(this.createLabelStyle())

      const vectorSource  = new source.Vector({
        features:[iconFeature,feature]
      })
      const vectorLayer = new layer.Vector({
        source: vectorSource,
      })

      this.feature = feature
      this.map.addLayer(vectorLayer)
    },
    createLabelStyle() {
      return new style.Style({
        image: new style.Icon({
          anchor: [95,45],
          scale: 0.2, // 图标缩小显示
          anchorOrigin: 'bottom-right', // 标注样式的起点位置
          anchorXUnits: 'pixels', // X方向单位：分数
          anchorYUnits: 'pixels', // Y方向单位：像素
          offsetOrigin: 'bottom-left', // 偏移起点位置的方向
          opacity: 1, // 透明度
          src: 'dian.png'  //图标的URL
        }),
        text: new style.Text({
          textAlign: 'center',            //位置
          textBaseline: 'middle',         //基准线
          font: 'normal 14px 微软雅黑',    //文字样式
          fill: new style.Fill({       //文本填充样式（即文字颜色)
            color: '#000'
          }),
          stroke: new style.Stroke({
            color: '#F00',
            width: 2
          })
        })
      });
    },
    registerMapEvent(){
      this.map.on('click',(evt) => {
        const { coordinate } = evt
        this.ruleForm.storeAddr = [...coordinate]
        this.feature.set('geometry',new Point(coordinate))
      })
    },
    async initForm() {
      this.hand_name = ''
      this.loading = true
      this.resetFormData()
      this.rulesThis = this.rules
      await this.resetForm()
      this.loading = false
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()
          this.resetFormData()
        }
      })
    },
    resetFormData() {
      const {
        id,
        code,
        supplier,
        storeName,
        type,
        category,
        delivery_way,
        supplier_type,
        level,
        pay_type,
        storeImage,
        prove_img,
        contactor,
        mobile,
        position,
        registercode,
        name,
        nature,
        addr,
        legaler,
        registertime,
        scope,
        personid,
        person,
        telephone,
        email
      } = this.sitem

      this.hand_name = person || ''
      this.ruleForm = {
        storeName:"",
        storeType:"",
        storeImage:"",
        storeAddr:[],
        contactor:"",
        mobile:"",
        email:"",
        position:"",
      }
    },
    closeImg(index) {
      this.ruleForm.prove_img.splice(index, 1)
      this.$refs.ruleForm.validateField('prove_img')
    },
    async save() {
      try{
        await this.$refs.ruleForm.validate()
        //TODO....
      }catch(err){
        console.log(err)
      }
    },
    deleteimg() {
      this.ruleForm.storeImage = ''
      this.$refs.ruleForm.validateField('storeImage')
    },
    // 图片上传成功
    async UploadSuccessEventsupplier_img(data) {
      await this.UploadSuccessEvent(1, data)
    },
    // 图片上传成功
    async UploadSuccessEventgood_info_img(data) {
      await this.UploadSuccessEvent(3, data)
    },
    // 图片上传成功
    async UploadSuccessEvent(type, data) {
      const { url } = data
      if (url === 'noToken') {
        await this.logout()
      } else {
        if (type === 1) {
          this.ruleForm.storeImage = url
          this.$refs.ruleForm.validateField('storeImage')
        } else if (type === 2) {
          this.ruleForm.good_img = url
          this.$refs.ruleForm.validateField('good_img')
        } else {
          this.ruleForm.prove_img.push(url)
          this.$refs.ruleForm.validateField('prove_img')
        }
        this.$message.success('图片上传成功!')
      }
    },
    // 图片上传失败
    UploadErrorEventsupplier_img(res) {
      this.imgUploadError(1, res)
    },
    // 图片上传失败
    UploadErrorEventgood_info_img(res) {
      this.imgUploadError(3, res)
    },
    imgUploadError(type, res) {
      if (res !== 'break') {
        this.$message.error('图片上传失败!')
        this.$refs.ruleForm.validateField(
          type === 1 ? 'storeImage' : type === 2 ? 'good_img' : 'good_info_img'
        )
      }
    },
    // 判断图片规格
    beforeAvatarUpload(file) {
      let isJPG = false
      if (
        file.type === 'image/jpg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpeg'
      ) {
        isJPG = true
      }
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!isJPG) {
        this.$message.error('图片格式不正确！')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 1MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
.supplierAdd {
  .good_info_img_div {
    ul {
      width: 100%;
      li {
        float: left;
        width: 55px;
        height: 55px;
        padding: 0 5px 0 0;
        .img-show-li-div {
          width: 50px;
          height: 50px;
          border: 1px solid #dfe4ed;
          background: #dfe4ed;
          position: relative;
          img.img-show {
            width: 100%;
            height: 100%;
            position: relative;
            display: inline-block;
          }
          i.el-icon-close {
            position: absolute;
            z-index: 2;
            top: 0;
            right: 0;
            color: #dfe4ed;
          }
          &:hover {
            i.el-icon-close {
              cursor: pointer;
              color: #6954f0;
            }
          }
        }
      }
    }
  }
  .supplierAdd-title {
    border-left: 5px solid #006eff;
    margin: 6px 0 25px 10px;
    width: 100%;
    box-sizing: border-box;
    padding: 0 0 0 10px;
  }
}

#map{
  width: 100%;
  height: 400px;

  cursor: pointer;
}
</style>
