<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 :disabled="parentObj.TYPE === 'edit'" v-model="form.NAME" placeholder="请输入机构（企业）名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="统一社会信用代码" prop="NUMBER">
                <el-input :disabled="parentObj.TYPE === 'edit'" 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%" @active-item-change="getAreaList"/>
              </el-form-item>
            </el-col>
            <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="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="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="TYPE">
                <el-select v-model="form.TYPE" style="width: 100%;">
                  <el-option value="0" label="机构"/>
                  <el-option value="1" label="企业"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="截至使用日期" prop="EXPIRE">
                <el-date-picker
                  :disabled="parentObj.TYPE === 'edit'"
                  v-model="form.EXPIRE"
                  style="width: 100%;"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="营业执照" prop="BUSINESS_LICENSE">
                <el-upload
                  :on-preview="handlePreviewIdPhoto"
                  :on-remove="handleRemoveIdPhoto"
                  :on-change="handleChangeIdPhoto"
                  :auto-upload="false"
                  :file-list="form.BUSINESS_LICENSE"
                  :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 v-if="parentObj.TYPE === 'add'" :span="12">
              <el-form-item label="视频文件" prop="file">
                <div>
                  <input v-show="false" id="fileUpload" ref="fileUpload" type="file" @change="fileChange($event)">
                  <el-button type="primary" @click="uploadFile">选择文件</el-button>
                  <span v-if="form.file" class="text-tip">{{ form.file.name }}</span>
                  <span v-if="!form.file.name" class="text-tip">文件格式.mp4，最大上传500M</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <el-form-item label="公章" prop="official_seal_file">
                <el-upload
                  :on-preview="handlePreviewOfficialSeal"
                  :on-remove="handleRemoveOfficialSeal"
                  :on-change="handleChangeOfficialSeal"
                  :auto-upload="false"
                  :file-list="form.official_seal_file"
                  :limit="1"
                  :class="{hide:officialSealUpload}"
                  action="#"
                  accept=".png"
                  list-type="picture-card">
                  <i class="el-icon-plus"/>
                </el-upload>
                <el-dialog :visible.sync="officialSealVisible" append-to-body>
                  <img :src="OFFICIAL_SEAL" width="100%" alt="">
                </el-dialog>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <div v-if="parentObj.TYPE !== 'view'" class="text-tip">
                *请上传背景透明的png图片，<br>建议尺寸为600px*600px以上正方形。
              </div>
            </el-col>
          </el-row>
        </el-form>
        <div class="detail_foot">
          <el-button v-if="parentObj.TYPE !== 'view'" :loading="loading" type="primary" @click="confirm">
            {{ parentObj.TYPE === 'add' ? '立即创建' : '修改' }}
          </el-button>
          <el-button icon="el-icon-arrow-left" @click="goBack">返回</el-button>
        </div>
      </div>
    </div>
    <div v-if="isShowProgress" class="popContainer">
      <div class="progress_title">视频上传中，请耐心等待...</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>
  </div>
</template>

<script>
import { requestFN } from '@/utils/request'
import { upload } from '@/utils/upload'

export default {
  data() {
    return {
      config: config,
      form: {
        NAME: '',
        NUMBER: '',
        dependency: [],
        ADDRESS: '',
        LONGITUDE: '',
        LATITUDE: '',
        COMMANDER: '',
        COMMANDER_PHONE: '',
        ESTABLISHMENT_TIME: '',
        TYPE: '',
        BUSINESS_LICENSE: [],
        file: {},
        official_seal_file: []
      },
      rules: {
        NAME: [
          { required: true, message: '请输入机构（企业）名称', trigger: 'blur' }
        ],
        EXPIRE: [
          { 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' }
        ],
        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'
          }
        ],
        ESTABLISHMENT_TIME: [
          { required: true, message: '请选择成立时间', trigger: 'blur' }
        ],
        TYPE: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ],
        BUSINESS_LICENSE: [
          { required: true, message: '请上传营业执照', trigger: 'blur' }
        ],
        file: [
          { required: true, message: '请上传视频文件', trigger: 'blur' }
        ],
        official_seal_file: [
          { required: true, message: '请上传公章照片', trigger: 'blur' }
        ]
      },
      hideUpload: false,
      loading: false,
      officialSealUpload: false,
      uploadVisible: false,
      officialSealVisible: false,
      isShowProgress: false,
      CAPTURE: '',
      OFFICIAL_SEAL: '',
      areaList: [],
      props: {
        value: 'DICTIONARIES_ID',
        label: 'NAME',
        children: 'children',
        checkStrictly: true
      },
      // file: {},
      lng: '',
      lat: '',
      addressKeyword: '',
      zoom: 16,
      loadingMap: true,
      dialogFormEdit: false
    }
  },
  inject: ['setActiveName', 'parentObj'],
  created() {
    if (this.parentObj.CORPINFO_ID) {
      this.getData()
    }
    this.getDict()
  },
  methods: {
    getDict() {
      requestFN('/dictionaries/getAdminIstrative', {
      }).then((data) => {
        this.areaList = data.varList.list[0].children
      })
    },
    getData() {
      requestFN('/training/getInfo', {
        CORPINFO_ID: this.parentObj.CORPINFO_ID
      }).then((data) => {
        data.info.dependency = [data.info.PROVINCE, data.info.CITY, data.info.COUNTRY]
        data.info.BUSINESS_LICENSE = [{
          url: this.config.fileUrl + data.info.BUSINESS_LICENSE
        }]
        data.info.official_seal_file = [{
          url: this.config.fileUrl + data.info.OFFICIAL_SEAL_PATH
        }]
        this.form = data.info
        this.hideUpload = true
        this.officialSealUpload = true
      })
    },
    handlePreviewIdPhoto(file) {
      this.CAPTURE = file.url
      this.uploadVisible = true
    },
    handleRemoveIdPhoto(file, fileList) {
      this.form.file = 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.BUSINESS_LICENSE = fileList
      this.hideUpload = fileList.length >= 1
    },

    // 公章
    handlePreviewOfficialSeal(file) {
      this.OFFICIAL_SEAL = file.url
      this.officialSealVisible = true
    },
    handleRemoveOfficialSeal(file, fileList) {
      this.form.official_seal_file = fileList
      this.officialSealUpload = fileList.length >= 1
    },
    handleChangeOfficialSeal(file, fileList) {
      const types = ['image/png']
      const isImage = types.includes(file.raw.type)
      if (!isImage) {
        this.$message.error('上传图片只能是PNG 格式!')
        fileList.pop()
        return
      }
      const img = new Image()
      img.src = file.url
      img.onload = () => {
        if (img.width !== img.height) {
          this.$message.warning('请上传正方形图片！')
          fileList.pop()
          return
        } else {
          this.form.official_seal_file = fileList
          this.officialSealUpload = fileList.length >= 1
        }
      }
    },
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.form.dependency.length !== 3) {
            this.$message.warning('属地必须选到县区一级')
            this.loading = false
            return
          }
          if (this.parentObj.TYPE === 'add') {
            if (!this.file || !this.file.name) {
              this.$message.warning('视频文件不能为空，请上传')
              this.loading = false
              return
            } else {
              this.isShowProgress = true
            }
          }
          const formData = new FormData()
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          if (this.form.BUSINESS_LICENSE[0].raw) {
            formData.append('BUSINESS_LICENSE', this.form.BUSINESS_LICENSE[0].raw)
          }
          if (this.form.official_seal_file[0].raw) {
            formData.append('OFFICIAL_SEAL_PATH', this.form.official_seal_file[0].raw)
          }
          if (this.parentObj.TYPE === 'add') {
            formData.append('VIDEOFILE', this.form.file)
            formData.append('VIDEO_NAME', this.form.file.name)
          }
          // formData.append('BUSINESS_LICENSE', this.form.BUSINESS_LICENSE[0].raw)
          formData.append('PROVINCE', this.form.dependency[0])
          formData.append('CITY', this.form.dependency[1])
          formData.append('COUNTRY', this.form.dependency[2])
          upload('/training/serialize', formData).then((res) => {
            if (res.errorMessage) {
              this.loading = false
              this.$message({
                message: res.errorMessage,
                type: 'error'
              })
            } else {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              if (this.parentObj.TYPE === 'add') {
                this.isShowProgress = false
              }
              this.goBack()
              this.loading = false
            }
          })
        } else {
          this.$message.error('请检查输入项')
        }
      })
    },
    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(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 })
          }
        })
      })
    },
    // 设置打开中心位置
    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() {
      this.form.LATITUDE = this.lat
      this.form.LONGITUDE = this.lng
      this.dialogFormEdit = false
    },
    uploadFile() {
      this.$refs.fileUpload.dispatchEvent(new MouseEvent('click'))
    },
    fileChange(e) {
      if (!e.target.files[0]) {
        this.$message.warning('请先选择需要上传的文件!')
        return
      } else if (e.target.files[0].type != 'video/mp4') {
        this.$message.warning('请选择MP4文件!')
        return
      } else if (e.target.files[0].size > 524288000) {
        this.$message.warning('文件最大500M!')
        return
      }

      this.file = e.target.files[0]
      this.form.file = this.file
    },
    goBack() {
      this.setActiveName('List')
    }
  }
}
</script>

<style scoped>

</style>
<style lang="scss">
  html{
    touch-action:none;
  }
  .hide .el-upload--picture-card {
    display: none;
  }

  .popContainer {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999999;
    background: rgba(0, 0, 0, 0.6);
    .el-progress__text{
      color: #fff;
    }
    .progress_title{
      position: relative;
      top: 35%;
      color: #e8e8e8;
      left:44.7%;
      text-shadow:#000 1px 1px 2px
    }
  }
</style>
