<template>
  <div class="app-warp">
    <div class="detail-structure">
      <el-page-header :content="(parentObj.TYPE === 'add' ? '新增' : parentObj.TYPE === 'edit' ? '编辑' : '查看')" @back="goBack"/>
      <div class="detail-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="企业名称" prop="NAME">
                <el-input v-model="form.NAME" placeholder="请输入企业名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="统一社会信用代码" prop="NUMBER">
                <el-input v-model="form.NUMBER" placeholder="请输入统一社会信用代码"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="属地" prop="dependency">
                <el-cascader ref="dependency" v-model="form.dependency" :options="areaList" :props="props" placeholder="请选择属地" style="width: 100%"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="行业类型" prop="INDUSTRY_TYPE">
                <el-cascader
                  ref="cascaderAddr"
                  v-model="form.INDUSTRY_TYPE"
                  :options="industryTypeList"
                  :props="{
                    value: 'INDUSTRYTYPE_ID',
                    label: 'NAME',
                    children: 'nodes',
                    checkStrictly: true
                  }"
                  style="width: 100%;"
                  @change="cascaderChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="parentObj.TYPE == 'add'" label="服务机构" prop="SERVICES">
                <el-select
                  v-model="form.SERVICES"
                  :remote-method="remoteMethod"
                  :loading="employerLoading"
                  style="width: 100%;"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词查找服务机构"
                >
                  <el-option v-for="item in servicesList" :key="item.CORPINFO_ID" :label="item.NAME" :value="item.CORPINFO_ID"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="parentObj.TYPE == 'add'" label="服务有限期" prop="DEADLINE">
                <el-date-picker
                  :picker-options="pickerOptions"
                  v-model="form.DEADLINE"
                  style="width: 100%;"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="企事业单位经营地址" prop="ADDRESS">
                <el-input v-model="form.ADDRESS" placeholder="请输入企事业单位经营地址"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经度/纬度" prop="jinweidu">
                <el-input :value="form.jinweidu" readonly placeholder="点击选择经度/纬度" @click.native="openMap"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主要负责人" prop="COMMANDER">
                <el-input v-model="form.COMMANDER" placeholder="请输入主要负责人"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主要负责人电话" prop="COMMANDER_PHONE">
                <el-input v-model="form.COMMANDER_PHONE" placeholder="请输入主要负责人电话"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="法人" prop="JURIDICAL">
                <el-input v-model="form.JURIDICAL" placeholder="请输入法人"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="法人手机号" prop="JURIDICAL_PHONE">
                <el-input v-model="form.JURIDICAL_PHONE" placeholder="请输入法人手机号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职工人数(人)" prop="EMPLOYEES_NUMBER">
                <el-input v-model.number="form.EMPLOYEES_NUMBER" placeholder="请输入职工人数(人)"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成立时间" prop="ESTABLISHMENT_TIME">
                <el-date-picker
                  v-model="form.ESTABLISHMENT_TIME"
                  style="width: 100%;"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="营业执照" prop="fileF">
                <el-upload
                  :on-preview="handlePreviewIdPhoto"
                  :on-remove="handleRemoveIdPhoto"
                  :on-change="handleChangeIdPhoto"
                  :auto-upload="false"
                  :file-list="form.fileF"
                  :limit="1"
                  :class="{hide:hideUpload}"
                  action="#"
                  accept=".jpg,.jpeg,.png"
                  list-type="picture-card">
                  <i class="el-icon-plus"/>
                </el-upload>
                <el-dialog :visible.sync="uploadVisible" append-to-body>
                  <img :src="CAPTURE" width="100%" alt="">
                </el-dialog>
              </el-form-item>
            </el-col>
<!--            <el-col :span="12">-->
<!--              <el-form-item v-if="parentObj.TYPE == 'add'" label="合同文件" prop="fileP">-->
<!--                <UploadFile :file-list.sync="form.fileP" :limit="1" accept=".pdf"/>-->
<!--              </el-form-item>-->
<!--              <el-form-item v-if="parentObj.TYPE === 'view'" label="合同文件" prop="fileP">-->
<!--                <el-button icon="el-icon-tickets" type="primary" @click="lookPdf">查看</el-button>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
          </el-row>
        </el-form>
        <div class="detail_foot">
          <el-button v-if="parentObj.TYPE !== 'view'" type="primary" @click="confirmDebounce">
            {{ parentObj.TYPE === 'add' ? '立即创建' : '修改' }}
          </el-button>
          <el-button icon="el-icon-arrow-left" @click="goBack">返回</el-button>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="dialogFormEdit" title="请选择位置" width="600px">
      <div class="mb-10" style="display: flex">
        <el-input :value="lng" disabled/>
        <el-input :value="lat" disabled/>
      </div>
      <el-input v-model="addressKeyword" placeholder="请输入关键字" class="mb-10"/>
      <baidu-map v-loading="loadingMap" :zoom="zoom" :scroll-wheel-zoom="true" style="height: 400px;width: 100%" @ready="handler" @click="getPoint">
        <bm-view style="width: 100%; height:100%; flex: 1"/>
        <bm-local-search :keyword="addressKeyword" :auto-viewport="true" style="display: none"/>
      </baidu-map>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="setPoint">确 定</el-button>
      </div>
    </el-dialog>
    <glance-pdf ref="glancePdf"/>
  </div>
</template>

<script>
import { requestFN } from '@/utils/request'
import { upload } from '@/utils/upload'
import { debounce } from 'throttle-debounce'
import UploadFile from '../../../../components/UploadFile'
import glancePdf from '../../../util/glancePdf'

export default {
  components: { UploadFile, glancePdf },
  data() {
    return {
      config: config,
      loading: false,
      form: {
        NAME: '',
        NUMBER: '',
        dependency: [],
        INDUSTRY_TYPE: [],
        ADDRESS: '',
        jinweidu: '',
        LONGITUDE: '',
        LATITUDE: '',
        COMMANDER: '',
        COMMANDER_PHONE: '',
        JURIDICAL: '',
        JURIDICAL_PHONE: '',
        EMPLOYEES_NUMBER: '',
        ESTABLISHMENT_TIME: '',
        fileP: [],
        fileF: [],
        DEADLINE: [],
        CONTRACT: ''
      },
      rules: {
        NAME: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        NUMBER: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
          {
            pattern: /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/,
            message: '请输入正确的统一社会信用代码',
            trigger: 'blur'
          }
        ],
        dependency: [
          { required: true, message: '请选择属地', trigger: 'blur' }
        ],
        ADDRESS: [
          { required: true, message: '请输入企事业单位经营地址', trigger: 'blur' }
        ],
        jinweidu: [
          { required: true, message: '请选择经度/纬度', trigger: 'blur' }
        ],
        COMMANDER: [
          { required: true, message: '请输入主要负责人', trigger: 'blur' }
        ],
        COMMANDER_PHONE: [
          { required: true, message: '请输入主要负责人电话', trigger: 'blur' },
          {
            pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/,
            message: '请输入正确的主要负责人电话',
            trigger: 'blur'
          }
        ],
        JURIDICAL: [
          { required: true, message: '请输入法人', trigger: 'blur' }
        ],
        JURIDICAL_PHONE: [
          { required: true, message: '请输入法人手机号', trigger: 'blur' },
          {
            pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/,
            message: '请输入正确的法人手机号',
            trigger: 'blur'
          }
        ],
        EMPLOYEES_NUMBER: [
          { required: true, message: '请输入职工人数(人)', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        ESTABLISHMENT_TIME: [
          { required: true, message: '请选择成立时间', trigger: 'blur' }
        ],
        INDUSTRY_TYPE: [
          { required: true, message: '请选择行业类型', trigger: 'blur' }
        ],
        SERVICES: [
          { required: true, message: '请选择服务机构', trigger: 'blur' }
        ],
        DEADLINE: [
          { required: true, message: '请选择服务有限期', trigger: 'blur' }
        ],
        fileF: [
          { required: true, message: '请上传营业执照', trigger: 'blur' }
        ],
        // fileP: [
        //   { required: true, message: '请上传合同文件', trigger: 'blur' }
        // ]
      },
      hideUpload: false,
      uploadVisible: false,
      CAPTURE: '',
      areaList: [],
      industryTypeList: [],
      servicesList: [],
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.selectDate = minDate.getTime()
          if (minDate) {
            this.sign = '1'
          }
          if (maxDate) {
            this.selectDate = ''
            this.sign = ''
            // 标记
          }
        },
        disabledDate: (time) => {
          if (this.sign !== '') {
            const one = 3 * 356 * 24 * 3600 * 1000
            const minTime = this.selectDate - one
            const maxTime = this.selectDate + one
            return time.getTime() < minTime || time.getTime() > maxTime
          }
        }
      },
      props: {
        value: 'DICTIONARIES_ID',
        label: 'NAME',
        children: 'children',
        checkStrictly: true
      },
      lng: '',
      lat: '',
      pointLngLat: '',
      addressKeyword: '',
      zoom: 16,
      sign: '',
      oldname: '',
      loadingMap: true,
      dialogFormEdit: false,
      employerLoading: false
    }
  },
  inject: ['setActiveName', 'parentObj'],
  created() {
    if (this.parentObj.ENTERPRISE_ID) {
      this.getData()
    }
    this.getRegion()
    this.getDict()
    this.getServices()
  },
  methods: {
    cascaderChange() {
      // console.log('cascaderChange')
      // //  const thsAreaCode = this.$refs['cascaderAddr'].currentLabels // 获取label值
      // // console.log(this.$refs['cascaderAddr'].getCheckedNodes())
      // console.log(this.$refs['cascaderAddr'])
      // console.log(this.$refs['cascaderAddr'].inputValue)
      // console.log(this.$refs['cascaderAddr'].presentText)
      // console.log(this.form.INDUSTRY_TYPE)
      // console.log(this.form.INDUSTRY_TYPE.join())
    },
    getRegion() {
      requestFN('/dictionaries/getAdminIstrative', {
      }).then((data) => {
        this.areaList = data.varList.list[0].children
      })
    },

    getDict() {
      requestFN(
        '/industrytype/getIndustryTreeCover'
      ).then((data) => {
        this.industryTypeList = data.zTreeNodes
      }).catch((e) => {
      })
    },
    remoteMethod: debounce(1000, function(query) {
      this.employerLoading = true
      this.getServices(query)
    }),
    getServices(NAME = '') {
      requestFN(`/training/list?showCount=20&currentPage=1`, {
        NAME
      }).then(data => {
        this.servicesList = data.list
        this.employerLoading = false
      })
    },
    getData() {
      requestFN('/enterprises/getInfo', {
        ENTERPRISE_ID: this.parentObj.ENTERPRISE_ID
      }).then((data) => {
        data.info.EMPLOYEES_NUMBER = +data.info.EMPLOYEES_NUMBER
        // data.info.REGISTERED_CAPITAL = +data.info.REGISTERED_CAPITAL
        // data.info.TOTAL_ASSETS = +data.info.TOTAL_ASSETS
        data.info.INDUSTRY_TYPE = JSON.parse(data.info.INDUSTRY_TYPE)
        data.info.dependency = [data.info.PROVINCE, data.info.CITY, data.info.COUNTRY]
        data.info.jinweidu = data.info.LATITUDE + '-' + data.info.LONGITUDE
        data.info.DEADLINE = [data.info.DEADLINE_START, data.info.DEADLINE_END]
        if (data.info.BUSINESS_LICENSE) {
          data.info.fileF = [{
            url: this.config.fileUrl + data.info.BUSINESS_LICENSE
          }]
          this.hideUpload = true
        }
        data.info.fileP = [{ url: this.config.fileUrl + data.info.BUSINESS_LICENSE }]
        this.form = data.info
        this.oldname = this.form.NAME
      })
    },
    handlePreviewIdPhoto(file) {
      this.CAPTURE = file.url
      this.uploadVisible = true
    },
    handleRemoveIdPhoto(file, fileList) {
      this.form.fileF = fileList
      this.hideUpload = fileList.length >= 1
    },
    handleChangeIdPhoto(file, fileList) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.raw.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
        fileList.pop()
      }
      this.form.fileF = fileList
      this.hideUpload = fileList.length >= 1
    },
    confirmDebounce: debounce(1000, function() {
      if (this.parentObj.TYPE == 'edit') {
        if (this.form.NAME != this.oldname) {
          this.editConfirm()
        } else {
          this.confirm()
        }
      } else {
        this.confirm()
      }
    }),
    editConfirm() {
      requestFN('/enterprises/getEntpriseInfo', {
        ENTERPRISE_ID: this.parentObj.ENTERPRISE_ID
      }).then((data) => {
        if (data.info) {
          this.$confirm('该企业正在培训，确定要修改企业名称吗?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$refs.form.validate((valid) => {
              if (valid) {
                this.loading = true
                if (this.form.dependency.length !== 3) {
                  this.$message.warning('属地必须选到县区一级')
                  this.loading = false
                  return
                }
                const formData = new FormData()
                Object.keys(this.form).map(key => {
                  formData.append(key, this.form[key])
                })
                if (this.form.fileF[0].raw) {
                  formData.append('BUSINESS_LICENSE', this.form.fileF[0].raw)
                }
                if (this.form.fileP[0].raw) {
                  formData.append('CONTRACT', this.form.fileP[0].raw)
                }
                if (this.form.fileF[0].raw) {
                  formData.append('CONTRACT', this.form.fileP[0].raw)
                }
                const addrs = this.$refs['cascaderAddr'].presentText
                const data = addrs.toString().trim().replaceAll('/', '-').replaceAll(' ', '')
                formData.append('USERNAME', this.form.NAME)
                formData.append('INDUSTRY_ALL_NAME', data)
                formData.append('INDUSTRY_ALL_TYPE', this.form.INDUSTRY_TYPE.join())
                formData.append('INDUSTRY_END_ID', this.form.INDUSTRY_TYPE[this.form.INDUSTRY_TYPE.length - 1])
                formData.append('PROVINCE', this.form.dependency[0])
                formData.append('CITY', this.form.dependency[1])
                formData.append('COUNTRY', this.form.dependency[2])
                formData.append('DEADLINE_START', this.form.DEADLINE[0])
                formData.append('DEADLINE_END', this.form.DEADLINE[1])
                upload('/enterprises/serialize', formData).then((res) => {
                  if (res.errorMessage) {
                    this.loading = false
                    this.$message({
                      message: res.errorMessage,
                      type: 'error'
                    })
                  } else {
                    this.$message({
                      message: '操作成功,并且该企业密码已重置',
                      type: 'success'
                    })
                    this.goBack()
                  }
                })
              } else {
                if (this.form.fileP[0]) {
                  this.$message.error('请检查输入项')
                } else {
                  this.$message.error('请上传合同文件')
                }
                this.loading = false
              }
            })
          }).catch(() => {
          })
        } else {
          this.confirm()
        }
      })
    },
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.form.dependency.length !== 3) {
            this.$message.warning('属地必须选到县区一级')
            this.loading = false
            return
          }
          const formData = new FormData()
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          if (this.form.fileF[0].raw) {
            formData.append('BUSINESS_LICENSE', this.form.fileF[0].raw)
          }
          if (this.form.fileP[0].raw) {
            formData.append('CONTRACT', this.form.fileP[0].raw)
          }
          if (this.form.fileF[0].raw) {
            formData.append('CONTRACT', this.form.fileP[0].raw)
          }
          const addrs = this.$refs['cascaderAddr'].presentText
          const data = addrs.toString().trim().replaceAll('/', '-').replaceAll(' ', '')
          formData.append('USERNAME', this.form.NAME)
          formData.append('INDUSTRY_ALL_NAME', data)
          formData.append('INDUSTRY_ALL_TYPE', this.form.INDUSTRY_TYPE.join())
          formData.append('INDUSTRY_END_ID', this.form.INDUSTRY_TYPE[this.form.INDUSTRY_TYPE.length - 1])
          formData.append('PROVINCE', this.form.dependency[0])
          formData.append('CITY', this.form.dependency[1])
          formData.append('COUNTRY', this.form.dependency[2])
          formData.append('DEADLINE_START', this.form.DEADLINE[0])
          formData.append('DEADLINE_END', this.form.DEADLINE[1])
          upload('/enterprises/serialize', formData).then((res) => {
            if (res.errorMessage) {
              this.loading = false
              this.$message({
                message: res.errorMessage,
                type: 'error'
              })
            } else {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.goBack()
            }
          })
        } else {
          if (this.form.fileP[0]) {
            this.$message.error('请检查输入项')
          } else {
            this.$message.error('请上传合同文件')
          }
          this.loading = false
        }
      })
    },
    openMap() {
      this.lng = ''
      this.lat = ''
      this.addressKeyword = ''
      this.dialogFormEdit = true
    },
    // 地图初始化
    handler({ BMap, map }) {
      this.BMap = BMap
      this.map = map
      this.loadingMap = true
      var geolocation = new BMap.Geolocation()
      var $this = this
      // 调用百度地图api 中的获取当前位置接口
      geolocation.getCurrentPosition(function(r) {
        const myGeo = new BMap.Geocoder()
        myGeo.getLocation(new BMap.Point(116.404, 39.915), 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 })
          }
        })
      })
    },
    // 设置打开中心位置
    setCenter({ BMap, map }) {
      var point = new BMap.Point(this.pointLngLat.lng, this.pointLngLat.lat)
      const zoom = map.getZoom()
      setTimeout(() => {
        map.centerAndZoom(point, zoom)
      }, 0)
    },
    getPoint(e) { // 点击地图获取一些信息，
      this.lng = e.point.lng // 通过  e.point.lng获取经度
      this.lat = e.point.lat // 通过  e.point.lat获取纬度
    },
    setPoint() {
      if (!this.lat) {
        this.$message.error('未选择坐标')
        return
      }
      this.form.LATITUDE = this.lat
      this.form.LONGITUDE = this.lng
      this.dialogFormEdit = false
      this.form.jinweidu = this.lat + '-' + this.lng
    },
    goBack() {
      this.setActiveName('List')
    },
    lookPdf() {
      this.$refs.glancePdf.init({ url: config.fileUrl + this.form.CONTRACT })
    }
  }
}
</script>

<style scoped>

</style>
