<template>
  <div class="main-form">
    <el-form ref="dataForm" :model="caseForm" :label-position="labelPosition" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="举报人" prop="reporterName">
            <el-input v-model.trim="caseForm.reporterName" type="text" placeholder="必填" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话" prop="reporterPhone">
            <el-input v-model.trim="caseForm.reporterPhone" type="text" placeholder="必填" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary">历史记录</el-button>
          <el-button type="primary" @click="openMapQueryDialog">地图查询</el-button>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="信息来源" prop="source">
            <el-select v-model="caseForm.source" placeholder="选择信息来源" clearable value="">
              <el-option
                v-for="item in caseSourceOpts"
                :key="item.value"
                :label="item.name"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="案卷等级" prop="caseLevel">
            <el-select v-model="caseForm.caseLevel" placeholder="选择案卷等级" value="">
              <el-option
                v-for="item in caseLevelOpts"
                :key="item.value"
                :label="item.name"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否核实">
            <div>
              <el-radio-group v-model="caseForm.isNeedVerify" @change="changeNeedVerify()">
                <el-radio-button label="1">需要</el-radio-button>
                <el-radio-button label="0">不需要</el-radio-button>
              </el-radio-group>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否回访">
            <div>
              <el-radio-group v-model="caseForm.isNeedRevisit">
                <el-radio-button label="1">需要</el-radio-button>
                <el-radio-button label="0">不需要</el-radio-button>
              </el-radio-group>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">

        <el-col :span="6">
          <el-form-item label="所在区县" prop="areaCode">
            <el-select v-model="caseForm.areaCode" placeholder="选择所在区县" value="">
              <el-option key="361029" label="东乡区" value="361029"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所在街道" prop="streetCode">
            <el-select v-model="caseForm.streetCode" placeholder="选择所在街道" value="">
              <el-option key="361029001" label="孝岗镇" value="361029001"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所在社区" prop="communityName">
            <el-input v-model="caseForm.communityName" type="text" placeholder="必填" readonly />
          </el-form-item>
        </el-col>
        <el-col v-if="caseForm.componentId !== ''" :span="6">
          <el-form-item label="部件编码">
            <el-input v-model="caseForm.componentId" type="text" placeholder="必填" readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col v-if="showVerifyPerson" :span="6">
          <el-form-item label="监督员" prop="verifyPersonId">
            <el-select v-model="caseForm.verifyPersonId" type="text" placeholder="选择监督员" filterable clearable value="">
              <el-option
                v-for="item in verifyPersonOpts"
                :key="item.id"
                :label="item.name"
                :value="item.id">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #999999; font-size: 13px">{{ item.id }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="案卷类别" prop="eorc">
            <el-select v-model="caseForm.eorc" placeholder="选择案卷类别" value="">
              <el-option
                v-for="item in caseEorCOpts"
                :key="item.value"
                :label="item.name"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="案卷大类" prop="caseType">
            <el-select v-model="caseForm.casetypeCode" placeholder="选择案卷大类" clearable value="">
              <el-option
                v-for="item in caseTypeOpts"
                :key="item.id"
                :label="item.typeName"
                :value="item.typeCode"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="案卷小类" prop="caseDetailType">
            <el-select v-model="caseForm.casetypeDetailCode" placeholder="选择案卷小类" clearable value="">
              <el-option
                v-for="item in caseDetailTypeOpts"
                :key="item.id"
                :label="item.typeDetailName"
                :value="item.typeDetailCode"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="showCaseTypesTime" :gutter="20">
        <el-col :span="12">
          <el-form-item label="立案标准" prop="casetypesTimeId">
            <el-select v-model="caseForm.casetypesTimeId" placeholder="选择立案标准" clearable value="" style="width: 100%">
              <el-option
                v-for="item in caseTypeTimeOpts"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="处理时限" prop="bzhours">
            <el-input-number v-model="caseForm.bzhours" :min="0" style="margin-right: 5px" />小时
            <el-input-number v-model="caseForm.bzminis" :min="0" :max="59" style="margin-left: 20px; margin-right: 5px" />分钟
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18">
          <el-form-item label="案卷描述" prop="description">
            <el-input v-model.trim="caseForm.description" type="textarea" placeholder="必填" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18">
          <el-form-item label="位置描述" prop="fieldintro">
            <el-input v-model.trim="caseForm.fieldintro" type="text" placeholder="必填" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="图片信息" prop="images">
            <el-upload
              ref="upload"
              :before-upload="handleBeforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :on-success="handleSuccess"
              :limit="2"
              :http-request="uploadFile"
              action="string"
              multiple
              accept=".jpg,.jpeg,.png "
              list-type="picture-card">
              <i class="el-icon-plus"/>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" style="margin-left: 120px; margin-bottom: 40px; text-align: center;">
          <el-button type="primary" size="medium" icon="el-icon-check" style="width: 200px;" @click="saveData"> 提交 </el-button>
        </el-col>
      </el-row>

    </el-form>

    <el-dialog :visible.sync="dialogVisible" title="图片预览" append-to-body>
      <div class="imgBox">
        <img :src="dialogImageUrl" max-height="400px;" alt="" style="margin: 0 auto;">
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="mapDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="地图查询"
      width="80%"
      append-to-body>

      <arcgis-map-comp
        ref="mapComp"
        @closeMapQueryDialogByEvent="closeMapQueryDialogByEvent"
        @closeMapQueryDialogByComp="closeMapQueryDialogByComp"/>

    </el-dialog>

  </div>
</template>

<script>
import { getCaseSource, getCaseLevel, getCaseEorC, getCaseType, getCaseDetailType, getCaseTypesTime, getVerifyPerson, addCase } from '@/api/callCase/callCase'
import { Uploadimg } from '@/api/common'
import ArcgisMapComp from '@/components/Map/ArcGISMap'

export default {
  name: 'CallCase',
  components: {// 注册组件
    ArcgisMapComp: ArcgisMapComp
  },
  data() {
    const phoneValidator = (rule, value, callback) => {
      if (value !== '') {
        if ((/^[1][3,5,6,7,8,9][0-9]{9}$/).test(value) === false) {
          callback(new Error('举报人电话格式不正确'))
        } else {
          callback()
        }
      } else {
        callback(new Error('举报人电话不能为空'))
      }
    }
    return {
      caseForm: {
        reporterName: '', // 举报人姓名
        reporterPhone: '', // 举报人电话
        isNeedVerify: '1', // 是否需要核实
        isNeedRevisit: '1', // 是否需要回访
        lng: '', // 经度，
        lat: '', // 纬度
        source: '', // 案卷信息来源
        caseLevel: '', // 案卷等级
        eorc: '', // 案卷类别
        casetypeCode: '', // 案卷大类编码,
        casetypeDetailCode: '', // 案卷小类编码
        areaCode: '361029', // 所属区县ID
        streetCode: '361029001', // 所属街道ID
        communityCode: '', // 所属社区编码
        communityName: '', // 所属社区NAME
        gridId: '', // 万米网格ID（单元网格）
        componentId: '', // 部件ID
        casetypesTimeId: '', // 立案标准ID
        bzhours: 0, // 限制完成总时限（小时）
        bzminis: 0, // 限制完成总时限（分钟）
        description: '', // 案件描述
        fieldintro: '', // 位置描述
        verifyPersonId: '', // 核实人员id
        photos: '' // 图片存储的地址
      }, // 表单
      rules: {
        reporterName: [{ required: true, message: '举报人姓名不能为空', trigger: ['blur'] }],
        reporterPhone: [{ required: true, trigger: ['blur'], validator: phoneValidator }],
        source: [{ required: true, message: '信息来源不能为空', trigger: ['change'] }],
        caseLevel: [{ required: true, message: '案卷等级不能为空', trigger: ['change'] }],
        eorc: [{ required: true, message: '案卷类别不能为空', trigger: ['change'] }],
        description: [{ required: true, message: '案卷描述不能为空', trigger: ['blur'] }],
        fieldintro: [{ required: true, message: '位置描述不能为空', trigger: ['blur'] }]
      }, // 表单验证
      hideUpload: false,
      fileList: [],
      imageList: [],
      uploadPath: process.env.BASE_API + 'imageUpload', // 图片上传路径
      dialogImageUrl: '',
      dialogVisible: false,
      mapDialogVisible: false, // 地图对话框
      labelPosition: 'right',
      caseSourceOpts: [], // 案卷来源下拉框
      caseLevelOpts: [], // 案卷等级下拉框
      caseEorCOpts: [], // 案卷类别下拉框
      caseTypeOpts: [], // 案卷大类下拉框
      caseDetailTypeOpts: [], // 案卷小类下拉框
      caseTypeTimeOpts: [], // 立案标准下拉框
      verifyPersonOpts: [], // 监督员下拉框
      showVerifyPerson: true,
      showCaseTypesTime: false,
      caseTypeCodeAuto: '', // 自动生成的案卷大类代码
      caseTypeDetailCodeAuto: '' // 自动生成的案卷小类代码
    }
  },
  computed: {
    caseLevel() {
      return this.caseForm.caseLevel
    },
    eorc() {
      return this.caseForm.eorc
    },
    caseType() {
      return this.caseForm.casetypeCode
    },
    caseTypeDetail() {
      return this.caseForm.casetypeDetailCode
    },
    caseTypeDetailTime() {
      return this.caseForm.casetypesTimeId
    }
  },
  watch: {
    caseLevel(level) {
      this.calculateTime(this.caseForm.casetypesTimeId)
    },
    eorc(eorcVal) {
      this.cascaderCaseType(eorcVal)
    },
    caseType(typeVal) {
      this.cascaderCaseDetailType(typeVal)
    },
    caseTypeDetail(detailVal) {
      this.cascaderCaseDetailTypeTime(detailVal)
    },
    caseTypeDetailTime(timeVal) {
      this.calculateTime(timeVal)
    }
  },
  mounted: function() {
    this.initCaseSource()
    this.initCaseLevel()
    this.initCaseEorC()
    this.initVerifyPerson()
  },
  methods: {
    initCaseSource: function() {
      getCaseSource().then(response => {
        this.caseSourceOpts = []
        for (const opt of response.data) {
          this.caseSourceOpts.push(opt)
          if (opt.name.indexOf('电话') >= 0) {
            this.caseForm.source = opt.value
          }
        }
      })
    },
    initCaseLevel: function() {
      getCaseLevel().then(response => {
        this.caseLevelOpts = []
        for (const opt of response.data) {
          this.caseLevelOpts.push(opt)
          if (opt.name.indexOf('一般') >= 0) {
            this.caseForm.caseLevel = opt.value
          }
        }
      })
    },
    initCaseEorC: function() {
      getCaseEorC().then(response => {
        this.caseEorCOpts = []
        for (const opt of response.data) {
          this.caseEorCOpts.push(opt)
        }
      })
    },
    initVerifyPerson: function() {
      getVerifyPerson().then(response => {
        this.verifyPersonOpts = []
        console.log(response)
        for (const opt of response.data) {
          this.verifyPersonOpts.push(opt)
        }
      })
    },
    // 级联查询案卷大类
    cascaderCaseType: function(eorc) {
      // 前两行的作用是清除案卷大类的当前值和select中的所有选项
      this.caseTypeOpts = []
      this.caseForm.casetypeCode = ''
      // 以下两行的作用是清除案卷小类的当前值和select中的所有选项
      this.caseDetailTypeOpts = []
      this.caseForm.casetypeDetailCode = ''
      // 以下两行是清除案卷时限（小时和分钟）
      this.caseTypeTimeOpts = []
      this.caseForm.casetypesTimeId = ''
      this.caseForm.bzhours = 0
      this.caseForm.bzminis = 0

      // 若事部件选择的值不为空，则查询相应的案卷大类
      if (eorc !== null && eorc.length > 0) {
        getCaseType(eorc).then(response => {
          for (const opt of response.data) {
            this.caseTypeOpts.push(opt)

            if (opt.typeCode === this.caseTypeCodeAuto) {
              this.caseForm.casetypeCode = opt.typeCode
            }
          }
        })
      }
    },
    cascaderCaseDetailType: function(typeCode) {
      // 以下两行的作用是清除案卷小类的当前值和select中的所有选项
      this.caseDetailTypeOpts = []
      this.caseForm.casetypeDetailCode = ''
      // 以下两行是清除案卷时限（小时和分钟）
      this.caseTypeTimeOpts = []
      this.caseForm.casetypesTimeId = ''
      this.caseForm.bzhours = 0
      this.caseForm.bzminis = 0

      // 根据code获取ID，进行级联查询
      let typeId = 0
      this.caseTypeOpts.forEach(item => {
        if (item.typeCode === typeCode) {
          typeId = item.id
        }
      })

      if (typeId > 0) {
        getCaseDetailType(typeId).then(response => {
          for (const opt of response.data) {
            this.caseDetailTypeOpts.push(opt)

            if (opt.typeDetailCode === this.caseTypeDetailCodeAuto) {
              this.caseForm.casetypeDetailCode = opt.typeDetailCode
            }
          }
        })
      }
    },
    // 查询立案标准
    cascaderCaseDetailTypeTime: function(detailCode) {
      // 以下两行是清除案卷时限（小时和分钟）
      this.caseTypeTimeOpts = []
      this.caseForm.casetypesTimeId = ''
      this.caseForm.bzhours = 0
      this.caseForm.bzminis = 0

      // 根据code获取ID，进行级联查询
      let typeDetailId = 0
      this.caseDetailTypeOpts.forEach(item => {
        if (item.typeDetailCode === detailCode) {
          typeDetailId = item.id
        }
      })

      if (typeDetailId > 0) {
        getCaseTypesTime(typeDetailId).then(response => {
          console.log(response)
          for (const opt of response.data) {
            this.caseTypeTimeOpts.push(opt)
          }
        })
      }
    },
    calculateTime: function(timeVal) {
      const hoursPerDay = this.caseForm.caseLevel === '1' ? 8 : 24
      let day = 0
      let hours = 0
      this.caseTypeTimeOpts.forEach(item => {
        if (item.id === timeVal) {
          day = item.day
          hours = item.hours
        }
      })

      this.caseForm.bzhours = hoursPerDay * parseInt(day) + parseInt(hours)
    },
    // 打开地图查询对话框显示地图
    openMapQueryDialog: function() {
      this.mapDialogVisible = true
    },
    // 关闭地图查询对话框
    closeMapQueryDialogByEvent: function(longitude, latitude, communityId, communityName, gridId) {
      this.mapDialogVisible = false

      // 赋值
      this.caseForm.eorc = '1' // 事件点返回时案卷类别自动选择为事件
      this.caseForm.communityCode = communityId
      this.caseForm.communityName = communityName
      this.caseForm.gridId = gridId
      this.caseForm.lng = longitude
      this.caseForm.lat = latitude

      this.caseForm.areaCode = communityId.substring(0, 6) // 区县代码
      this.caseForm.streetCode = communityId.substring(0, 9) // 街道代码
    },
    // 关闭地图查询对话框
    closeMapQueryDialogByComp: function(longitude, latitude, communityId, communityName, gridId, componentId, componentName) {
      this.mapDialogVisible = false

      // 赋值
      this.caseForm.eorc = '2' // 部件点返回时案卷类别自动选择为部件
      this.caseForm.communityCode = communityId
      this.caseForm.communityName = communityName
      this.caseForm.gridId = gridId
      this.caseForm.lng = longitude
      this.caseForm.lat = latitude
      this.caseForm.componentId = componentId
      this.caseForm.componentName = componentName

      this.caseForm.areaCode = communityId.substring(0, 6) // 区县代码
      this.caseForm.streetCode = communityId.substring(0, 9) // 街道代码
      this.caseTypeCodeAuto = componentId.substring(6, 8) // 自动赋值部件大类
      this.caseTypeDetailCodeAuto = componentId.substring(8, 10) // 自动赋值部件小类
    },
    // 修改是否需要核实
    changeNeedVerify: function() {
      if (this.caseForm.isNeedVerify === '0') {
        // 不需要核实，显示立案标准、处理时限
        this.showVerifyPerson = false
        this.showCaseTypesTime = true
      } else {
        this.showVerifyPerson = true
        this.showCaseTypesTime = false
      }
    },
    // 保存数据
    saveData: function() {
      const that = this
      if (this.fileList.length > 0) {
        let photos = ''
        this.fileList.forEach(photo => {
          photos += photo.url + ','
        })
        this.caseForm.photos = photos.substring(0, photos.length - 1)
      }

      this.$refs['dataForm'].validate((valid) => {
        console.log(valid)
        if (valid) {
          addCase(this.caseForm).then(function(response) {
            if (response.code === 200) {
              that.$message({
                message: '添加案卷成功',
                type: 'success'
              })

              that.$router.push({ path: '/dashboard' })
            } else {
              that.$message({
                message: '添加案卷失败',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 图片上传
    uploadFile(file) {
      console.log('uploadFile:' + file.file.name)
      // const base_url = process.env.BASE_API + '/static/'
      Uploadimg(file).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.fileList.push({ name: file.file.name, url: res.data })
        }
      })
    },
    // 上传前判断文件格式及大小
    handleBeforeUpload(file) {
      const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png')
      let res = true
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        res = false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        res = false
      }
      for (const i in this.fileList) {
        if (this.fileList[i].name === file.name) {
          this.$message.error('该图片已上传过，请选择其他图片')
          res = false
        }
      }
      return res
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log('handleRemove')
      for (const i in this.fileList) {
        if (this.fileList[i].name === file.name) {
          this.fileList.splice(i, 1)
          this.hideUpload = this.fileList.length >= 2
          return
        }
      }
      this.handleChange()
    },
    // 限制提示
    handleExceed(files, fileList) {
      console.log('handleExceed')
      this.$message.warning(`限制选择 2 张图片，本次选择了 ${files.length} 张图片，共选择了 ${files.length + fileList.length} 张图片`)
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      console.log('handlePictureCardPreview')
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      console.log('handleChange')
      if (fileList) {
        this.hideUpload = fileList.length >= 2
      } else {
        this.hideUpload = false
      }
    },
    handleSuccess(response, file, fileList) {
      console.log('handleSuccess')
      console.log(response)
      const base_url = process.env.BASE_API + '/static/'
      if (response.code === 200) {
        this.fileList.push({ name: file.file.name, url: base_url + response.data })
        this.handleChange()
      } else {
        this.$message.warning(response.message)
      }
    }
  }
}
</script>

<style scoped>
  .main-form{
    margin: 20px;
  }
</style>
