<template>
  <div v-loading="dialogLoading" :element-loading-text="loadingText">

    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-col :span="12">
          <el-form-item label="工厂名称" prop="factoryName">
            <el-input v-model="formData.factoryName" placeholder="请输入工厂名称" clearable :style="{width: '100%'}" size="medium"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人名称" prop="applyName">
            <el-input v-model="formData.applyName" placeholder="请输入负责人名称" clearable :style="{width: '100%'}" size="medium"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="applyPhone">
            <el-input v-model="formData.applyPhone" placeholder="请输入联系方式" clearable :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号码" prop="applyIdCard">
            <el-input v-model="formData.applyIdCard" placeholder="请输入身份证号码" clearable :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属省份" prop="provinceId">
            <el-select size="small" style="width: 200px" v-model="formData.provinceId" placeholder="请选择省份（直辖市）" v-on:change="changeProvince()">
              <el-option v-for="item in provinces" :label="item.areaName" :value="item.areaId" :key="item.areaName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属城市" prop="cityId">
            <el-select size="small" style="width: 200px;margin-left: 10px" v-model="formData.cityId" placeholder="请选择城市" v-on:change="changeCity">
              <el-option v-for="item in citys" :label="item.areaName" :value="item.areaId" :key="item.areaName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属地区" prop="areaId">
            <el-select size="small" style="width: 200px;margin-left: 10px" v-model="formData.areaId" placeholder="请选择区（县）" v-on:change="changeArea">
              <el-option v-for="item in areas" :label="item.areaName" :value="item.areaId" :key="item.areaName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="搜索地址" prop="address">
            <el-autocomplete style="width:100%;" popper-class="autoAddressClass" v-model="formData.address" :fetch-suggestions="querySearchAsync"
              :trigger-on-focus="false" placeholder="详细地址" @select="handleSelect" clearable>
              <template slot-scope="{ item }">
                <em class="el-icon-search fl mgr10" />
                <div style="overflow:hidden;">
                  <div class="title" style="display:table-cell">{{ item.title }}</div>
                  <span class="address ellipsis">{{ item.address }}</span>
                </div>
              </template>
            </el-autocomplete>
            <div id="baidu-map-container" style="width: 100%;margin-top: 20px;margin-bottom: 20px; height: 400px;"></div>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-col :span="12">
            <el-form-item label="业务区域" prop="bindAreaId">
              <el-select size="small"  v-model="formData.bindAreaId" placeholder="请选择业务区域">
                <el-option v-for="item in bindAreas" :label="item.name" :value="item.id" :key="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门牌号" prop="detailAddress">
              <el-input v-model="formData.detailAddress" placeholder="请输入门牌号" clearable :style="{width: '100%'}" size="medium"></el-input>
            </el-form-item>
          </el-col>

        </el-col>

        <el-col :span="24">
          <el-form-item label="工厂简介" prop="content">
            <el-input v-model="formData.content" type="textarea" placeholder="请输入工厂简介" :rows="5" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="营业执照" prop="businessLicensePic">
            <el-upload ref="businessLicensePic" :file-list="businessLicensePicfileList" :action="businessLicensePicAction"
              :before-upload="businessLicensePicBeforeUpload" :on-success="businessUploadSuccess" :on-remove="businessOnRemove" list-type="picture"
              accept="image/*">
              <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="工厂照片" prop="factoryPic">
            <el-upload ref="factoryPic" :file-list="factoryPicfileList" :action="businessLicensePicAction" :before-upload="factoryPicBeforeUpload"
              :on-success="factoryUploadSuccess" :on-remove="factoryOnRemove" list-type="picture" accept="image/*">
              <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>

      </el-form>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" style="margin-left: 5%">提交</el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request';
import { listStoreArea } from '@/api/system/storeArea'
import {
  getFactory,
  addFactory,
  updateFactory
} from "@/api/system/factory";

export function listArea(query) {
  return request({
    url: '/system/area/list',
    method: 'get',
    params: query
  })
}

export default {
  inheritAttrs: false,
  components: {},
  props: [],
  data() {
    return {
      dialogLoading: true,
      loadingText: '查询中',
      formData: {
        factoryName: undefined,
        applyName: undefined,
        applyPhone: undefined,
        applyIdCard: undefined,
        provinceId: undefined,
        cityId: undefined,
        areaId: undefined,
        content: undefined,
        businessLicensePic: null,
		bindAreaId: null,
        factoryPic: null,
        province: '', // 省
        city: '', // 市
        area: '', // 区
        address: '',
        detailAddress: ''
      },
      rules: {
        factoryName: [{
          required: true,
          message: '请输入工厂名称',
          trigger: 'blur'
        }],
        applyName: [{
          required: true,
          message: '请输入负责人名称',
          trigger: 'blur'
        }],
        applyPhone: [{
          required: true,
          trigger: 'blur',
          validator: this.checkPhone
        }],
        applyIdCard: [{
          required: true,
          trigger: 'blur',
          validator: this.checkIdCardNumber
        }],
        provinceId: [{
          required: true,
          message: '请选择所属省份',
          trigger: 'change'
        }],
        cityId: [{
          required: true,
          message: '请选择所属城市',
          trigger: 'change'
        }],
        areaId: [{
          required: true,
          message: '请选择所属地区',
          trigger: 'change'
        }],
        content: [{
          required: true,
          message: '请输入工厂简介',
          trigger: 'blur'
        }],
        address: [{
          required: true,
          message: '请输入具体地址',
          trigger: 'blur'
        }],

      },
      businessLicensePicAction: `${process.env.VUE_APP_BASE_API}` + '/common/uploadOSS',
      businessLicensePicfileList: [],
      factoryPicAction: `${process.env.VUE_APP_BASE_API}` + '/common/uploadOSS',
      factoryPicfileList: [],
      provinces: [],
	  bindAreas: [],
      citys: [],
      areas: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getProvince(1);
	this.getBindAreas();
  },
  async mounted() {
    await this.loadBMap('muIMwle2eOkTHf453rwRNgMa0W83j2PX') //加载引入BMap
    this.initBaiduMap()
  },
  methods: {
    checkPhone(rule, value, callback) {
      const regex = /^1[0-9]{10}$/; // 手机号正则表达式
      if (!regex.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    },
    checkIdCardNumber(rule, value, callback) {
      const regex = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/; // 身份证正则表达式
      if (!regex.test(value)) {
        callback(new Error('请输入正确的身份证号码'));
      } else {
        callback();
      }

    },
    setInitData(factoryId) {
      this.id = factoryId
      this.businessLicensePicfileList = []
      this.factoryPicfileList = []
      if (factoryId != undefined && factoryId != '') {
        this.dialogLoading = true
        this.loadingText = '查询中'
        getFactory(this.id).then(res => {
          this.formData = res.data
          //获取所属城市和所属地区
          this.getProvince(2, this.formData.provinceId);
          this.getProvince(3, this.formData.cityId);
          this.dialogLoading = false
          //地图定位
          var point = new BMap.Point(this.formData.orgLon, this.formData.orgLat);
          this.map.centerAndZoom(point, 19)
          this.mk = new BMap.Marker(point, {
            enableDragging: true
          }) //创建一个图像标注实例，enableDragging：是否启用拖拽，默认为false
          this.map.addOverlay(this.mk) //将覆盖物添加到地图中

          if (this.formData.businessLicensePic) {
            this.businessLicensePicfileList = [{
              url: this.formData.businessLicensePic
            }]
          }
          if (this.formData.factoryPic) {
            this.factoryPicfileList = [{
              url: this.formData.factoryPic
            }]
          }
          this.resetForm('elForm')
        }).catch(e => {
          this.dialogLoading = false
          this.$message.error(e.data.msg)
        })
      } else {
        this.dialogLoading = false
      }
    },
	//获取绑定的区域
	getBindAreas(){
		listStoreArea({ pageSize: 10000, pageNum: 1, status: '0' }).then((res) => {
                this.bindAreas = res.rows
            })
	},
    /** 获取省份 */
    getProvince(level, parentId) {
      let provinceParams = {
        "level": level,
        "parentId": parentId
      };
      listArea(provinceParams).then(response => {
        if (level === 1) {
          this.provinces = response.data;
        } else if (level === 2) {
          this.citys = response.data;
        } else {
          this.areas = response.data;
        }
      });
    },
    /** 获取城市 */
    changeProvince() {
      let cityParams = {
        "parentId": this.formData.provinceId
      };
      const selectedOption = this.provinces.find(option => option.areaId === this.formData.provinceId);
      this.formData.province = selectedOption ? selectedOption.areaName : null;
      listArea(cityParams).then(response => {
        this.citys = response.data;
      });
      if (this.formData.cityId != null) {
        this.formData.cityId = null;
        this.formData.areaId = null;
        this.areas = [];
      }
    },
    /** 获取区县 */
    changeCity() {
      let cityParams = {
        "parentId": this.formData.cityId
      };
      const selectedOption = this.citys.find(option => option.areaId === this.formData.cityId);
      this.formData.city = selectedOption ? selectedOption.areaName : null;
      listArea(cityParams).then(response => {
        this.areas = response.data;
      });
      if (this.formData.areaId != null) {
        this.formData.areaId = null;
      }
    },
    /** 获取区县 */
    changeArea() {

      const selectedOption = this.areas.find(option => option.areaId === this.formData.areaId);
      this.formData.area = selectedOption ? selectedOption.areaName : null;

    },
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        // TODO 提交表单
        console.log(this.formData);

        if (this.businessLicensePicfileList && this.businessLicensePicfileList.length > 0) {
          this.formData.businessLicensePic = this.businessLicensePicfileList[0].url
        } else {
          this.formData.businessLicensePic = ''
        }
        if (this.factoryPicfileList && this.factoryPicfileList.length > 0) {
          this.formData.factoryPic = this.factoryPicfileList[0].url
        } else {
          this.formData.factoryPic = ''
        }

        if (this.formData.hasOwnProperty('addrPoint')) {
          this.formData.orgLon = this.formData.addrPoint.lng
          this.formData.orgLat = this.formData.addrPoint.lat
        }

        this.dialogLoading = true
        this.loadingText = '保存中'
        if (this.id == undefined || this.id == '') {
          addFactory(this.formData).then(res => {
            this.$message('添加成功')
            this.dialogLoading = false
            this.$emit('closeDialog')
            this.$root.$emit('refreshList');
          }).catch(e => {
            this.dialogLoading = false
            this.$message.error(e.data.msg)
          })
        } else {
          updateFactory(this.formData).then(res => {
            this.$message('保存成功')
            this.dialogLoading = false
            this.$emit('closeDialog')
            this.$root.$emit('refreshList');
          }).catch(e => {
            this.dialogLoading = false
            this.$message.error(e.data.msg)
          })
        }
      })
    },
    closeDialog() {
      var ctx = this
      this.$confirm('是否关闭表单，关闭后数据将丢失？').then(function () {
        ctx.$emit('closeDialog')
      }).then(() => { }).catch(() => { });
    },
    onOpen() { },
    onClose() {
      this.$refs['elForm'].resetFields()
    },
    close() {
      this.$emit('update:visible', false)
    },
    handleConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        this.close()
      })
    },
    businessLicensePicBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    factoryPicBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    businessUploadSuccess(response, file, fileList) {
      this.businessLicensePicfileList = fileList
      if (this.businessLicensePicfileList.length > 1) {
        this.businessLicensePicfileList.splice(0, 1)
      }
      this.businessLicensePicfileList[0].url = this.businessLicensePicfileList[0].response.data.src
      console.log(this.businessLicensePicfileList)
    },
    businessOnRemove(file, fileList) {
      this.businessLicensePicfileList = fileList
    },
    factoryUploadSuccess(response, file, fileList) {
      this.factoryPicfileList = fileList
      if (this.factoryPicfileList.length > 1) {
        this.factoryPicfileList.splice(0, 1)
      }
      this.factoryPicfileList[0].url = this.factoryPicfileList[0].response.data.src
      console.log(this.factoryPicfileList)
    },
    factoryOnRemove(file, fileList) {
      this.factoryPicfileList = fileList
    },
    // 初始化百度地图
    initBaiduMap() {
      var that = this;
      this.map = new BMap.Map("baidu-map-container", {
        enableMapClick: false
      }) //新建地图实例，enableMapClick:false ：禁用地图默认点击弹框
      var point = new BMap.Point(113.30765, 23.12005);
      this.map.centerAndZoom(point, 19)
      this.mk = new BMap.Marker(point, {
        enableDragging: true
      }) //创建一个图像标注实例，enableDragging：是否启用拖拽，默认为false
      this.map.addOverlay(this.mk) //将覆盖物添加到地图中
      this.mk.addEventListener('dragend', function (e) {
        that.getAddrByPoint(e.point) //拖拽结束后调用逆地址解析函数，e.point为拖拽后的地理坐标
      })
      var navigationControl = new BMap.NavigationControl({ //创建一个特定样式的地图平移缩放控件
        anchor: BMAP_ANCHOR_TOP_RIGHT, //靠右上角位置
        type: BMAP_NAVIGATION_CONTROL_SMALL //SMALL控件类型
      })
      this.map.addControl(navigationControl) //将控件添加到地图
      var geolocationControl = new BMap.GeolocationControl({
        anchor: BMAP_ANCHOR_BOTTOM_LEFT
      }) //创建一个地图定位控件
      geolocationControl.addEventListener("locationSuccess", function (e) { //绑定定位成功后事件
        that.getAddrByPoint(e.point) //定位成功后调用逆地址解析函数
      });
      geolocationControl.addEventListener("locationError", function (e) { //绑定定位失败后事件
        console.log(e.message);
      });
      this.map.addControl(geolocationControl) //将控件添加到地图
      this.map.addEventListener('click', function (e) { //给地图绑定点击事件
        that.getAddrByPoint(e.point) //点击后调用逆地址解析函数
      })
      this.geolocation()
    },
    /**
     * 浏览器定位函数
     */
    geolocation() {
      var that = this;
      var geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function (res) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          that.getAddrByPoint(res.point) //当成功时，调用逆地址解析函数
        } else {
          console.log('failed' + this.getStatus()); //失败时，弹出失败状态码
        }
      }, {
        enableHighAccuracy: true
      }) //enableHighAccuracy：是否要求浏览器获取最佳效果，默认为false
    },
    /** 逆向解析地址 point */
    getAddrByPoint(point) {
      var that = this;
      var geco = new BMap.Geocoder();
      geco.getLocation(point, function (res) {
        console.log(res) //内容见下图
        that.mk.setPosition(point) //重新设置标注的地理坐标
        that.map.panTo(point) //将地图的中心点更改为给定的点
        that.addressInfo.address = res.address; //记录该点的详细地址信息
        that.addressInfo.addrPoint = point; //记录当前坐标点
      })
    },
    querySearchAsync(str, cb) {
      var options = {
        onSearchComplete: function (res) { //检索完成后的回调函数
          var s = [];
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < res.getCurrentNumPois(); i++) {
              s.push(res.getPoi(i));
            }
            cb(s) //获取到数据时，通过回调函数cb返回到<el-autocomplete>组件中进行显示
          } else {
            cb(s)
          }
        }
      }
      var local = new BMap.LocalSearch(this.map, options) //创建LocalSearch构造函数
      local.search(str) //调用search方法，根据检索词str发起检索
    },
    handleSelect(item) {
      this.formData.address = item.address + item.title; //记录详细地址，含建筑物名
      this.formData.addrPoint = item.point; //记录当前选中地址坐标
      this.map.clearOverlays() //清除地图上所有覆盖物
      this.mk = new BMap.Marker(item.point) //根据所选坐标重新创建Marker
      this.map.addOverlay(this.mk) //将覆盖物重新添加到地图中
      this.map.panTo(item.point) //将地图的中心点更改为选定坐标点
    },
    /**
     * 确认选择
     */
    confirmSelect() {
      this.$emit("confirmMapAddress", this.addressInfo);
      this.openMap = false;
    },

    /**
     * 取消选择
     */
    cancel() {
      this.$emit('cancelMap')
    },
    /**
     * 动态加载百度地图api函数
     * @param {String} ak  百度地图AK，必传
     */
    loadBMap(ak) {
      return new Promise(function (resolve, reject) {
        if (typeof window.BMap !== 'undefined') {
          resolve(window.BMap)
          return true
        }
        window.onBMapCallback = function () {
          resolve(window.BMap)
        }
        let script = document.createElement('script')
        script.type = 'text/javascript'
        script.src =
          'https://api.map.baidu.com/api?v=3.0&ak=' + ak + '&callback=onBMapCallback'
        script.onerror = reject
        document.head.appendChild(script)
      })
    }
  }
}
</script>

<style>
.el-upload__tip {
    line-height: 1.2;
}
</style>
