<template>
  <div class="reform-bg">
    <div class="reform-warp">
      <div class="reform-content" style="padding: 10px">
        <el-form ref="form" :model="form" :rules="rules" label-width="200px">
          <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-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="股份监管部门" prop="MANAGER_DEPARTMENT_ID">
                <Treeselect
                  :options="treeData"
                  :normalizer="normalizergfjg"
                  :flat="true"
                  :default-expand-level="0"
                  :props="defaultProps"
                  v-model="form.MANAGER_DEPARTMENT_ID"
                  multiple
                  placeholder="请选择部门"
                  no-options-text="暂无数据"
                  no-children-text="暂无数据"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="基层单位监管部门" prop="COMPETENT_DEPT_ID">
                <Treeselect
                  :options="treeDataSupervise"
                  :normalizer="normalizergfjg"
                  :flat="true"
                  :default-expand-level="0"
                  :props="defaultProps"
                  v-model="form.COMPETENT_DEPT_ID"
                  multiple
                  placeholder="请选择基层单位监管部门"
                  no-options-text="暂无数据"
                  no-children-text="暂无数据"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="股份主管部门" prop="MAIN_DEPARTMENT">
                <Treeselect
                  :options="treeData"
                  :normalizer="normalizer"
                  v-model="form.MAIN_DEPARTMENT"
                  placeholder="请选择部门"
                  no-options-text="暂无数据"
                  no-children-text="暂无数据"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="基层单位主管部门" prop="SUPERVISE_DEPARTMENT_ID">
                <Treeselect
                  :options="treeDataSupervise"
                  :normalizer="normalizer"
                  v-model="form.SUPERVISE_DEPARTMENT_ID"
                  placeholder="请选择基层单位主管部门"
                  no-options-text="暂无数据"
                  no-children-text="暂无数据"
                  @select="selectValue"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <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="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-select v-model="form.INDUSTRY" style="width: 100%">
                  <el-option v-for="item in industryList" :key="item.BIANMA" :label="item.NAME" :value="item.BIANMA"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="集团单位" prop="CORP_TYPE">
                <el-select v-model="form.CORP_TYPE" style="width: 100%">
                  <el-option v-for="item in corpTypeList" :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="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>
            <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>
            <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>
            <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>
            <el-col :span="12">
              <el-form-item label="用工形式" prop="EMPLOYMENT_FORM">
                <Treeselect
                  :options="employmentTypeList"
                  :normalizer="normalizer"
                  v-model="form.EMPLOYMENT_FORM"
                  placeholder="请选择用工形式"
                  no-options-text="暂无数据"
                  no-children-text="暂无数据"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选取形式" prop="SELECT_FORMS">
                <el-select v-model="form.SELECT_FORMS" multiple 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>
        <div style="text-align: center">
          <el-button :loading="submitButtonLoading" 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>
              </div>
            </bm-control>
          </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 Treeselect from '@riophae/vue-treeselect'

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

        }
      ).then((data) => {
        if (data.pd) {
          callback(new Error('相关方单位名称重复'))
        }
        callback()
      }).catch((e) => {
        callback()
      })
    }
    return {
      submitButtonLoading: false,
      dialogFormMap: false,
      loadingMap: true,
      zoom: 10,
      clientHeight: 600,
      addressKeyword: '',
      BMap: '',
      pointLngLat: '',
      map: '',
      LONGITUDE: '',
      LATITUDE: '',
      treeData: [],
      normalizergfjg(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.nodes,
          isDisabled: node.pId === '0'
        }
      },
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.nodes
        }
      },
      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')).NAME,
      treeDataSupervise: [],
      form: {
        CREATOR: JSON.parse(sessionStorage.getItem('user')).USER_ID,
        OPERATOR: JSON.parse(sessionStorage.getItem('user')).USER_ID,
        MAIN_DEPARTMENT: null,
        MANAGER_DEPARTMENT_ID: null, // 股份监管部门
        COMPETENT_DEPT_ID: null, // 基层单位监管部门
        SUPERVISE_DEPARTMENT_ID: null,
        SUPERVISE_CORPINFO_ID: '',
        RELEVANT_UNIT_NAME: '',
        SOCIAL_CODE: '',
        LOCAL: '',
        INDUSTRY: '',
        BUSINESS_ADDRESS: '',
        LONGITUDE: '',
        LATITUDE: '',
        LEGAL_PERSON: '',
        CONTACT_PERSON: '',
        CONTACT_TEL: '',
        EMPLOYMENT_FORM: null,
        SELECT_FORM: '',
        SELECT_FORMS: [],
        FLOATING_PERCENT: '',
        COMPANY_AREA: '',
        POSSESSION: [],
        PROVINCE: '',
        CITY: '',
        COUNTY: '',
        VILLAGE: '',
        INDUSTRYALL: ''
      },
      hylxList: [], // 国民经济行业分类 (GB-T4754-2017)
      dialogImageUrl: '', // 上传图片预览
      dialogVisible: false,
      operationTypeList: [], // 作业类型词典
      employmentTypeList: [], // 用工形式数据
      selectFormList: [], // 选取形式数据
      industryList: [], // 行业类型
      corpTypeList: [], // 集团单位
      rules: {
        MAIN_DEPARTMENT: [{ required: true, message: '请选择主管部门', trigger: 'blur' }],
        INDUSTRY: [{ required: false, message: '请选择所属行业', trigger: 'blur' }],
        CORP_TYPE: [{ required: true, message: '请选择集团单位', trigger: 'blur' }],
        RELEVANT_UNIT_NAME: [
          { required: true, message: '相关方单位名称不能为空', trigger: 'blur' },
          { validator: hasName, trigger: 'blur' }
        ],
        CONTACT_TEL: [
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: '请输入正确的手机号码'
          }
        ]
      }
    }
  },
  created() {
    this.getDict()
    this.getTreeList()
  },
  mounted() {},
  methods: {
    selectValue(value, node, extra) {
      this.form.SUPERVISE_CORPINFO_ID = value.CORPINFO_ID
    },
    async getAreaDict(DICTIONARIES_ID) {
      const { list } = await requestFN(
        '/xgf/dictionaries/getAreaLevels',
        {
          DICTIONARIES_ID
        }
      )
      return list
    },
    cascaderChange(e) {
      const newVal = e[e.length - 1]
      if (newVal === '1' || newVal === '2' || newVal === '3' || newVal === '4') {
        this.$message({
          message: '请选择正确的属地...',
          type: 'error'
        })
        this.form.POSSESSION.pop()
      }
    },
    // 加载级联的方法
    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(
        '/department/listTreeManageAndCorp1/',
        {}
      ).then((data) => {
        const treeData = this.listTransTree(JSON.parse(data.zTreeNodes), 'id', 'pId', 'nodes')
        this.treeData = this.removeEmptyChildren(treeData)
      }).catch((e) => {
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          this.submitButtonLoading = true
          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.COMPANY_AREA = this.$refs.POSSESSION.getCheckedNodes()[0].pathLabels ? this.$refs.POSSESSION.getCheckedNodes()[0].pathLabels.join(',') : ''
          }
          this.form.SELECT_FORM = this.form.SELECT_FORMS.join(',')
          this.form.SELECT_FORM = this.form.SELECT_FORMS.join(',')
          if (this.form.COMPETENT_DEPT_ID) {
            this.form.COMPETENT_DEPT_ID = this.form.COMPETENT_DEPT_ID.join(',')
          }
          if (this.form.MANAGER_DEPARTMENT_ID) {
            this.form.MANAGER_DEPARTMENT_ID = this.form.MANAGER_DEPARTMENT_ID.join(',')
          }
          requestFN(
            '/relevantunits/saveCorpInfo',
            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
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    back() {
      this.$parent.activeName = 'CorpInfoList'
    },
    // 获取数据字典数据
    getDict: function() {
      requestFN(
        '/department/listTree/', {}
      ).then((data) => {
        const treeData = this.listTransTree(JSON.parse(data.zTreeNodes), 'id', 'pId', 'nodes')
        this.treeDataSupervise = this.removeEmptyChildren(treeData)
      }).catch((e) => {
      })

      requestFN(
        '/xgf/dictionaries/listSelectTree',
        {
          DICTIONARIES_ID: '720992d898bf4fd7b44bf0ba1f1bbb88'
        }
      ).then((data) => {
        const employmentTypeList = this.listTransTree(JSON.parse(data.zTreeNodes), 'id', 'pId', 'nodes')
        this.employmentTypeList = this.removeEmptyChildren(employmentTypeList)
      })
      requestFN(
        '/xgf/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '9ce2e9a4636b4d41b460ce16c346d497'
        }
      ).then((data) => {
        this.selectFormList = data.list
      })
      requestFN(
        '/xgf/dictionaries/getLevels',
        {
          DICTIONARIES_ID: 'f2598ba72e864eadabf0ca4b664d26b9'
        }
      ).then((data) => {
        this.industryList = data.list
      })
      requestFN(
        '/xgf/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '37d8385931f14bb0b962082cf6bb3395'
        }
      ).then((data) => {
        this.corpTypeList = 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)
    }
  }
}

</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>
