<template>
  <div class="reform-bg">
    <div class="reform-warp">
      <div class="reform-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="200px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="主管部门" prop="MAIN_DEPARTMENT">
                <SelectTree
                  ref="treeSelect"
                  :clearable="false"
                  :options="treeData"
                  :props="defaultProps"
                  :node-key="'id'"
                  v-model="form.MAIN_DEPARTMENT"
                  placeholder="请选择主管部门"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户人" prop="CREATOR">
                <el-input id="CREATOR" ref="CREATOR" v-model="CREATOR_NAME" maxlength="50" placeholder="开户人" title="开户人" disabled/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="相关方单位名称" prop="RELEVANT_UNIT_NAME">
                <el-input id="RELEVANT_UNIT_NAME" ref="RELEVANT_UNIT_NAME" v-model="form.RELEVANT_UNIT_NAME" maxlength="255" placeholder="这里输入相关方单位名称..." title="相关方单位名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="统一社会信用代码" prop="SOCIAL_CODE">
                <el-input id="SOCIAL_CODE" ref="SOCIAL_CODE" v-model="form.SOCIAL_CODE" maxlength="255" placeholder="这里输入统一社会信用代码..." title="统一社会信用代码"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="属地" prop="POSSESSION">
                <el-cascader id="POSSESSION" ref="POSSESSION" v-model="form.POSSESSION" :options="areaList" :props="areaProps" placeholder="请选择省市县" style="width: 100%" @change="cascaderChange"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属行业" prop="INDUSTRY">
                <!-- <el-cascader
                  ref="industryCascader"
                  v-model="form.INDUSTRYALL"
                  :options="hylxList"
                  :props="industryProps"
                  style="width: 100%;"
                />-->
                <el-select v-model="form.INDUSTRY" style="width: 100%">
                  <el-option v-for="item in industryList" :key="item.DICTIONARIES_ID" :label="item.NAME" :value="item.DICTIONARIES_ID"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="经度" prop="LONGITUDE">
                <el-input v-model="form.LONGITUDE" placeholder="请输入内容" disabled @focus="handleMap" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纬度" prop="LATITUDE">
                <div style="display: flex">
                  <el-input v-model="form.LATITUDE" placeholder="请输入内容" disabled style="width: 100%" @focus="handleMap"/>
                  <el-button style="margin-left:10px" @click="handleMap">
                    <span class="svg-container">
                      <svg-icon icon-class="international" />
                    </span>
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="企事业单位经营地址" prop="BUSINESS_ADDRESS">
                <el-input id="BUSINESS_ADDRESS" ref="BUSINESS_ADDRESS" v-model="form.BUSINESS_ADDRESS" maxlength="255" placeholder="这里输入企事业单位经营地址..." title="企事业单位经营地址"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="法人" prop="LEGAL_PERSON">
                <el-input id="LEGAL_PERSON" ref="LEGAL_PERSON" v-model="form.LEGAL_PERSON" maxlength="255" placeholder="这里输入法人..." title="法人"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="CONTACT_PERSON">
                <el-input id="CONTACT_PERSON" ref="CONTACT_PERSON" v-model="form.CONTACT_PERSON" maxlength="255" placeholder="这里输入联系人..." title="联系人"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="CONTACT_TEL">
                <el-input id="CONTACT_TEL" ref="CONTACT_TEL" v-model="form.CONTACT_TEL" maxlength="255" placeholder="这里输入联系电话..." title="联系电话"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用工形式" prop="EMPLOYMENT_FORM">
                <el-select v-model="form.EMPLOYMENT_FORM" style="width: 100%;">
                  <el-option v-for="item in employmentTypeList" :key="item.BIANMA" :label="item.NAME" :value="item.BIANMA" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选取形式" prop="SELECT_FORM">
                <el-select v-model="form.SELECT_FORM" style="width: 100%;">
                  <el-option v-for="item in selectFormList" :key="item.BIANMA" :label="item.NAME" :value="item.BIANMA" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="流动人员比例(%)" prop="FLOATING_PERCENT">
            <el-input id="FLOATING_PERCENT" ref="FLOATING_PERCENT" v-model="form.FLOATING_PERCENT" maxlength="255" placeholder="这里输入流动人员比例..." title="流动人员比例"/>
          </el-form-item>
        </el-form>
        <div style="text-align: center">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="back">取消</el-button>
        </div>
        <!-- 坐标选择 -->
        <el-dialog :visible.sync="dialogFormMap" title="编辑坐标" width="800px" class="dy-dialog">
          <baidu-map
            v-loading="loadingMap"
            :zoom="zoom"
            :scroll-wheel-zoom="true"
            :style="{height: clientHeight+'px'}"
            @click="getClickInfo"
            @ready="handler">
            <bm-view style="width: 100%; height:100%; flex: 1" />
            <bm-control ref="control" :offset="{width: 10, height: 10}" anchor="BMAP_ANCHOR_TOP_LEFT">
              <div class="map-flex">

                <div class="map-lable">关键词：</div>
                <div style="flex:1;">
                  <el-autocomplete v-model="addressKeyword" :fetch-suggestions="querySearch" :trigger-on-focus="false" placeholder="请输入详细地址" style="width:100%" @select="handleSelect" />
                </div>
                <!--            <el-input v-model="addressKeyword" style="width: 200px" placeholder="请输入内容" />-->
                <!--            <el-button slot="append" icon="el-icon-search" @click="mapNameChange"/>-->
              </div>
            </bm-control>
            <!--        <bm-local-search :keyword="addressKeyword" :auto-viewport="true"/>-->
          </baidu-map>
          <div slot="footer" class="dialog-footer">
            <span>经度：</span>
            <el-input v-model="LONGITUDE" style="width: 200px" placeholder="请输入内容" disabled />
            <span>纬度：</span>
            <el-input v-model="LATITUDE" style="width: 200px" placeholder="请输入内容" disabled />
            <el-button @click="dialogFormMap = false">取 消</el-button>
            <el-button type="primary" @click="setPosition">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import waves from '@/directive/waves' // waves directive
import { requestFN } from '@/utils/request'
import DeptSelectTree from '@/components/DeptSelectTree'
import SelectTree from '@/components/SelectTree'
// import { upload } from '@/utils/upload'

export default {
  components: { Pagination, DeptSelectTree, SelectTree },
  directives: { waves },
  data() {
    var hasName = (rule, value, callback) => {
      requestFN(
        '/corpinfo/hasName',
        {
          RELEVANT_UNIT_NAME: value,
          CORPINFO_ID: ''

        }
      ).then((data) => {
        if (data.pd) {
          callback(new Error('相关方单位名称重复'))
        }
        callback()
      }).catch((e) => {
        callback()
      })
    }
    var hasSocialCode = (rule, value, callback) => {
      requestFN(
        '/corpinfo/hasSocialCode',
        {
          SOCIAL_CODE: value,
          CORPINFO_ID: ''

        }
      ).then((data) => {
        if (data.pd) {
          callback(new Error('统一社会信用代码重复'))
        }
        callback()
      }).catch((e) => {
        callback()
      })
    }
    return {
      dialogFormMap: false,
      loadingMap: true,
      zoom: 10,
      clientHeight: 600,
      addressKeyword: '',
      BMap: '',
      pointLngLat: '',
      map: '',
      LONGITUDE: '',
      LATITUDE: '',
      treeData: [],
      areaList: [],
      industryProps: {
        lazy: true,
        lazyLoad: this.lazyLoad,
        value: 'id',
        id: 'id',
        label: 'label',
        children: 'children',
        checkStrictly: false
      },
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      areaProps: {
        lazy: true,
        lazyLoad: async(node, resolve) => {
          const resData = await this.getAreaDict(
            (node.data && node.data.DICTIONARIES_ID) || 'e725d2a91b8248f4b8f49889038df7de'
          )
          const { level } = node
          resolve(
            resData.map((item) => {
              return {
                DICTIONARIES_ID: item.DICTIONARIES_ID,
                BIANMA: item.BIANMA,
                NAME: item.NAME,
                leaf: level >= 3
              }
            })
          )
        },
        value: 'BIANMA',
        id: 'DICTIONARIES_ID',
        label: 'NAME',
        children: 'children',
        checkStrictly: true
      },
      CREATOR_NAME: JSON.parse(sessionStorage.getItem('user')).USERNAME,
      form: {
        CREATOR: JSON.parse(sessionStorage.getItem('user')).USER_ID,
        OPERATOR: JSON.parse(sessionStorage.getItem('user')).USER_ID,
        MAIN_DEPARTMENT: '',
        RELEVANT_UNIT_NAME: '',
        SOCIAL_CODE: '',
        LOCAL: '',
        INDUSTRY: '',
        BUSINESS_ADDRESS: '',
        LONGITUDE: '',
        LATITUDE: '',
        LEGAL_PERSON: '',
        CONTACT_PERSON: '',
        CONTACT_TEL: '',
        EMPLOYMENT_FORM: '',
        SELECT_FORM: '',
        FLOATING_PERCENT: '',
        COMPANY_AREA: '',
        POSSESSION: [],
        PROVINCE: '',
        CITY: '',
        COUNTY: '',
        VILLAGE: '',
        INDUSTRYALL: ''
      },
      hylxList: [], // 国民经济行业分类 (GB-T4754-2017)
      dialogImageUrl: '', // 上传图片预览
      dialogVisible: false,
      operationTypeList: [], // 作业类型词典
      employmentTypeList: [], // 用工形式数据
      selectFormList: [], // 选取形式数据
      industryList: [], // 行业类型
      rules: {
        MAIN_DEPARTMENT: [{ required: true, message: '请选择主管部门', trigger: 'blur' }],
        RELEVANT_UNIT_NAME: [
          { required: true, message: '相关方单位名称不能为空', trigger: 'blur' },
          { validator: hasName, trigger: 'blur' }
        ],
        SOCIAL_CODE: [
          { required: true, message: '统一社会信用代码不能为空', trigger: 'blur' },
          {
            pattern: /^[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}$/,
            message: '请输入正确的统一社会信用代码'
          },
          { validator: hasSocialCode, trigger: 'blur' }
        ],
        // LOCAL: [{ required: true, message: '请选择属地', trigger: 'blur' }],
        // INDUSTRY: [{ required: true, message: '请选择所属行业', trigger: 'blur' }],
        BUSINESS_ADDRESS: [{ required: true, message: '企事业单位经营地址不能为空', trigger: 'blur' }],
        LONGITUDE: [{ required: true, message: '请选择经度', trigger: 'blur' }],
        LATITUDE: [{ required: true, message: '请选择纬度', trigger: 'blur' }],
        LEGAL_PERSON: [{ required: true, message: '法人不能为空', trigger: 'blur' }],
        CONTACT_PERSON: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        CONTACT_TEL: [
          { required: true, message: '联系电话不能为空', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确的手机号码'
          }
        ],
        EMPLOYMENT_FORM: [{ required: true, message: '用工形式不能为空', trigger: 'blur' }],
        SELECT_FORM: [{ required: true, message: '选取形式不能为空', trigger: 'blur' }],
        POSSESSION: [{ required: true, message: '属地不能为空', trigger: 'blur' }],
        FLOATING_PERCENT: [
          { required: true, message: '流动人员比例不能为空', trigger: 'blur' },
          { min: 1, max: 3, message: '请输入1-100的数字', trigger: 'blur' },
          {
            pattern: /^(([1-9][0-9]?)([.,][0-9]{0,2})?|100([.,]0{1,2})?)$/,
            message: '请输入1-100的数字'
          }
        ]
      }
    }
  },
  created() {
    // this.listLoading = false
    // this.getList()
    this.getDict()
    this.getTreeList()
  },
  mounted() {
    // this.getNextTickData()
  },
  methods: {
    async getAreaDict(DICTIONARIES_ID) {
      const { list } = await requestFN(
        '/dictionarisearea/getLevels',
        {
          DICTIONARIES_ID
        }
      )
      return list
    },
    cascaderChange(e) {
      // console.log('e', e)
      const newVal = e[e.length - 1]
      // console.log('选中', newVal[newVal.length - 1])
      if (newVal === '1' || newVal === '2' || newVal === '3' || newVal === '4') {
        this.$message({
          message: '请选择正确的属地...',
          type: 'error'
        })
        this.form.POSSESSION.pop()
        // console.log('移除', this.corpStateForm.REGULATORY_DEPARTMENT_ARR)
      }
    },
    // 加载级联的方法
    lazyLoad(nodeValue, resolve) {
      if (nodeValue.data && (!nodeValue.children || nodeValue.children.length == 0)) {
        this.getDictByDicId(nodeValue.data.id).then(data => {
          resolve(data)
        })
      } else {
        resolve(null)
      }
    },
    getClickInfo(e) {
      this.LONGITUDE = e.point.lng
      this.LATITUDE = e.point.lat
    },
    handleMap() {
      this.dialogFormMap = true
      this.LATITUDE = this.form.LATITUDE
      this.LONGITUDE = this.form.LONGITUDE
    },
    getTreeList() {
      requestFN(
        '/corpinfo/getRegulatoryDepList',
        {}
      ).then((data) => {
        this.treeData = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.POSSESSION && this.form.POSSESSION.length > 0) {
            this.form.PROVINCE = this.form.POSSESSION[0] || ''
            this.form.CITY = this.form.POSSESSION[1] || ''
            this.form.COUNTY = this.form.POSSESSION[2] || ''
            this.form.VILLAGE = this.form.POSSESSION[3] || ''
            // this.form.STREET = this.form.POSSESSION[4] || ''
            this.form.COMPANY_AREA = this.$refs.POSSESSION.getCheckedNodes()[0].pathLabels ? this.$refs.POSSESSION.getCheckedNodes()[0].pathLabels.join(',') : ''
          }
          /* if (this.form.INDUSTRYALL && this.form.INDUSTRYALL.length > 0) {
            this.form.CORP_TYPE = this.form.INDUSTRYALL[0] || ''
            this.form.CORP_TYPE2 = this.form.INDUSTRYALL[1] || ''
            this.form.CORP_TYPE3 = this.form.INDUSTRYALL[2] || ''
            this.form.CORP_TYPE4 = this.form.INDUSTRYALL[3] || ''
            this.form.CORP_TYPE_NAME = this.$refs.industryCascader.getCheckedNodes()[0].pathLabels ? this.$refs.industryCascader.getCheckedNodes()[0].pathLabels.join('/') : ''
          } */
          this.listLoading = true
          requestFN(
            '/corpinfo/saveData',
            this.form
          ).then((data) => {
            if (data.result == 'exist') {
              this.$message({
                message: '用户名已存在，请重新填写...',
                type: 'error'
              })
            } else {
              this.$message({
                message: '保存成功！',
                type: 'success'
              })
              this.form = {}
              this.$parent.activeName = 'CorpInfoList'
            }
            this.listLoading = false
            // this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    back() {
      this.$parent.activeName = 'CorpInfoList'
    },
    // 获取数据字典数据
    getDict: function() {
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '720992d898bf4fd7b44bf0ba1f1bbb88'
        }
      ).then((data) => {
        this.employmentTypeList = data.list
      })
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '9ce2e9a4636b4d41b460ce16c346d497'
        }
      ).then((data) => {
        this.selectFormList = data.list
      })
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: 'f2598ba72e864eadabf0ca4b664d26b9'
        }
      ).then((data) => {
        this.industryList = data.list
      })
    },
    // 地图相关
    mapOpen() {
      this.top = this.getScrollTop()
      if (this.top) {
        this.setScrollTop(0)
      }
    },
    getScrollTop() {
      let scrollTop = 0
      if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop
      } else if (document.body) {
        scrollTop = document.body.scrollTop
      }
      return scrollTop
    },
    setScrollTop(top) {
      if (!isNaN(top)) {
        if (document.documentElement && document.documentElement.scrollTop !== undefined) {
          document.documentElement.scrollTop = top
        } else if (document.body) {
          document.body.scrollTop = top
        }
      }
    },
    // 关闭地图后调用
    mapClose() {
      this.setScrollTop(this.top)
      this.top = 0
      this.showMap = false
    },
    // 地图初始化
    handler({ BMap, map }) {
      this.mapOpen()
      this.BMap = BMap
      this.map = map
      this.loadingMap = true
      var geolocation = new BMap.Geolocation()
      const myGeo = new BMap.Geocoder()
      var $this = this
      // 调用百度地图api 中的获取当前位置接口
      geolocation.getCurrentPosition(function(r) {
        myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), function(result) {
          if (result) {
            $this.loadingMap = false
            $this.$set($this, 'pointLngLat', { lng: result.point.lng, lat: result.point.lat })
            map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放,默认关闭
            $this.setCenter({ BMap, map })
          }
        })
      })
    },
    // 搜索地图
    querySearch(queryString, cb) {
      var options = {
        onSearchComplete: function(results) {
          if (local.getStatus() === 0) {
            // 判断状态是否正确
            var s = []
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              var x = results.getPoi(i)
              var item = { value: x.address + x.title, point: x.point }
              s.push(item)
              cb(s)
            }
          } else {
            cb()
          }
        }
      }
      var local = new this.BMap.LocalSearch(this.map, options)
      local.search(queryString)
    },
    handleSelect(item) {
      var { point } = item
      this.map.clearOverlays() // 清除地图上所有覆盖物
      this.map.centerAndZoom(point, this.zoom)
      const marker = new this.BMap.Marker(point) // 创建标注
      this.map.addOverlay(marker) // 将标注添加到地图中
      marker.enableDragging() // 可拖拽
      this.LONGITUDE = point.lng
      this.LATITUDE = point.lat
    },
    setPosition() {
      this.dialogFormMap = false
      this.form.LATITUDE = this.LATITUDE
      this.form.LONGITUDE = this.LONGITUDE
    },
    // 设置打开中心位置
    setCenter({ BMap, map }) {
      var lng = ''
      var lat = ''
      if (this.form.LONGITUDE == '' || this.form.LATITUDE == '') {
        lng = '119.525971'
        lat = '39.894727'
      } else {
        lng = this.form.LONGITUDE
        lat = this.form.LATITUDE
      }
      var point = new BMap.Point(lng, lat)
      const zoom = map.getZoom()
      setTimeout(() => {
        map.centerAndZoom(point, zoom)
      }, 0)
      // var marker = new BMap.Marker(point) // 创建标注
      // map.addOverlay(marker) // 将标注添加到地图中
    }
  }
}

</script>

<style lang="scss" scoped>
.map-flex {
  display: flex;
  width: 500px;
  align-items :center
}
.tools {
  text-align: right;
}
.dialogContent {
  .title {
    text-align: center;
  }
  .tableFooter {
    width: 80%;
    display: flex;
    justify-content: space-between;
    padding: 15px 0;
  }
}
</style>
