<template>
  <div class="main-form">
    <el-form ref="dataForm" :label-position="labelPosition" :rules="rules" :model="wellForm" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="9">
          <el-form-item label="窨井名称" prop="wellName">
            <el-input v-model.trim="wellForm.wellName" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="9" :offset="3">
          <el-form-item label="窨井编号" prop="wellCode">
            <el-input v-model.trim="wellForm.wellCode" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="9">
          <el-form-item label="窨井类型" prop="wellType">
            <el-select v-model="wellForm.wellType" placeholder="点击选择窨井类型" clearable>
              <el-option
                v-for="item in wellTypeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9" :offset="3">
          <el-form-item label="权属单位" prop="deptid">
            <dept-select v-model="wellForm.deptid" :need-top="deptShowTop" :dept-show="deptShow" dept-type="03" placeholder="选择权属单位"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="9">
          <el-form-item label="井深(m)" prop="deep">
            <el-input v-model.trim="wellForm.deep" type="text" placeholder="需要装液位监测仪的井必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="9">
          <el-form-item label="经度" prop="coordinateX">
            <el-input v-model.trim="wellForm.coordinateX" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="9" :offset="3">
          <el-form-item label="纬度" prop="coordinateY">
            <el-input v-model.trim="wellForm.coordinateY" type="text" placeholder="必填"/>
          </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-change="handleChange"
              :on-success="handleSuccess"
              :limit="4"
              :class="{hide:hideUpload}"
              :http-request="uploadFile"
              action="string"
              multiple
              accept=".jpg,.jpeg,.png "
              list-type="picture-card">
              <i class="el-icon-plus"/>
            </el-upload>
            <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-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="1">

        <el-form-item label="所在区域" required>
          <el-col :span="5">
            <el-form-item prop="qu">
              <el-select v-model="wellForm.qu" :disabled="showArea" placeholder="请选择所在区/县" clearable>
                <el-option
                  v-for="item in quList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1" class="line">区/县</el-col>
          <el-col :span="5">
            <el-form-item prop="area">
              <el-select v-model="wellForm.area" :disabled="showArea" placeholder="请选择所在街道/镇" clearable>
                <el-option
                  v-for="item in jiedaoList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1" class="line">街道/镇</el-col>
        </el-form-item>

      </el-row>
      <el-row :gutter="20">
        <el-col :span="15">
          <el-form-item label="详细地址" prop="position">
            <el-input v-model.trim="wellForm.position" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="9">
          <el-form-item label="窨井维护机构" prop="responsibleDept">
            <el-select v-model="wellForm.responsibleDept" :disabled="showResponseDept" placeholder="选择维护组织，不选默认为权属单位" clearable>
              <el-option
                v-for="item in secondDeptTreeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="15" style="margin-left: 120px; margin-bottom: 40px;">
          <el-button size="medium" @click="resetForm"> 重置 </el-button>
          <el-button type="primary" size="medium" style="margin-left: 10px;" @click="saveData"> 保存 </el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { toTreeList } from '@/utils/structure'
import SelectTree from '@/components/SelectTree/singleSelect'
import { getDeptTreeList } from '@/api/dept'
import { getAreaList, getAreaByDept } from '@/api/area'
import { getWellType, addWell } from '@/api/well'
import { Uploadimg } from '@/api/common'
import DeptSelect from '@/components/DeptSelect'

export default {
  name: 'AddWell',
  components: { SelectTree, DeptSelect },
  data() {
    const validateDeep = (rule, value, callback) => {
      if (value !== '') {
        if ((/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value) === false) {
          callback(new Error('请填写大于0的数字'))
        } else {
          const deep = parseFloat(value)
          if (deep > 10 || deep < 0) { callback(new Error('请填写0到10数值')) } else { callback() }
        }
      } else {
        callback()
      }
    }
    const validateLng = (rule, value, callback) => {
      if (value !== '') {
        if ((/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value) === false) {
          callback(new Error('请填写大于0的数字'))
        } else {
          callback()
        }
      } else {
        callback(new Error('经度不能为空'))
      }
    }
    const validateLat = (rule, value, callback) => {
      if (value !== '') {
        if ((/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value) === false) {
          callback(new Error('请填写大于0的数字'))
        } else {
          callback()
        }
      } else {
        callback(new Error('纬度不能为空'))
      }
    }
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      wellForm: {
        wellCode: '', // 窨井编号
        wellName: '', // 窨井名称
        wellType: '', // 窨井类型
        deptid: '', // 权属单位
        deep: '', // 井深，
        position: '', // 位置描述
        coordinateX: '', // 经度
        coordinateY: '', // 纬度
        photos: '', // 照片路径
        notes: '', // 备注,
        qu: '',
        area: '', // 街道
        responsibleDept: '' // 维护人员部门
      }, // 表单
      deptProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      },
      hideUpload: false,
      fileList: [],
      imageList: [],
      deptTreeList: null, // 组织树列表数据
      secondDeptTreeList: null, // 二级组织树列表
      wellTypeList: null,
      quList: null,
      jiedaoList: null,
      textMap: {
        update: '编辑',
        create: '新增'
      }, // 表头显示标题
      rules: {
        wellCode: [{ required: true, message: '窨井编号不能为空', trigger: ['blur', 'change'] }],
        wellName: [{ required: true, message: '窨井名称不能为空', trigger: ['blur', 'change'] }],
        position: [{ required: true, message: '窨井详细地址不能为空', trigger: ['blur', 'change'] }],
        deep: [{ required: false, trigger: ['blur', 'change'], validator: validateDeep }],
        coordinateX: [{ required: true, trigger: ['blur', 'change'], validator: validateLat }],
        coordinateY: [{ required: true, trigger: ['blur', 'change'], validator: validateLng }],
        deptid: [{ required: true, message: '组织机构必选', trigger: 'change' }],
        wellType: [{ required: true, message: '窨井类型必选', trigger: 'change' }],
        qu: [{ required: true, message: '所在区/县必选', trigger: 'change' }],
        area: [{ required: true, message: '所在街道/镇必选', trigger: 'change' }]
      },
      uploadPath: process.env.BASE_API + '/imageUpload', // 图片上传路径
      dialogImageUrl: '',
      dialogVisible: false,
      labelPosition: 'right',
      responseAssignShow: false,
      deptShowTop: false, // 权属单位下拉是否显示顶级
      deptShow: true
    }
  },
  computed: {
    showResponseDept() {
      if (this.wellForm.deptid === '') {
        return true
      } else {
        if (this.secondDeptTreeList && this.secondDeptTreeList.length >= 1) {
          return false
        } else {
          return true
        }
      }
    },
    showArea() {
      if (this.wellForm.deptid === '') {
        return true
      } else {
        return false
      }
    },
    firstDept() { // 获取权属单位
      return this.wellForm.deptid
    },
    qu() { // 获取区
      return this.wellForm.qu
    }
  },
  watch: {
    firstDept(val) { // 监控权属单位变化
      if (val !== '') {
        this.wellForm.qu = ''
        this.wellForm.area = ''
        this.wellForm.responsibleDept = ''
        this.fetchSecondDeptTree()
        this.fetchArea1()
      }
    },
    qu(val) { // 监控区变化
      if (val !== '') {
        this.wellForm.area = ''
        this.fetchArea2()
      }
    }
  },
  mounted: function() {
    this.fetchWellType()
  },
  methods: {
    // 加载组织机构树形下拉菜单
    fetchSecondDeptTree: function() {
      const listQuery = {
        pid: this.wellForm.deptid,
        deptType: '04'
      }
      getDeptTreeList(listQuery).then(response => {
        console.log(response.data)
        if (response.data.list) {
          this.secondDeptTreeList = toTreeList(response.data.list, this.wellForm.deptid)
        }
      })
    },
    // 获取窨井类型
    fetchWellType() {
      getWellType().then(response => {
        this.wellTypeList = []
        const wellTypes = this.$store.getters.wellTypes
        for (const wellType of response.data) {
          if (wellTypes.indexOf(wellType.value) !== -1) {
            this.wellTypeList.push(wellType)
          }
        }
        if (this.wellTypeList.length <= 1) {
          this.showWellType = false
        }
      })
    },
    // 获取区域1
    fetchArea1() {
      getAreaByDept(this.wellForm.deptid).then(response => {
        if (response.code === 200) {
          const pid = response.data.area
          getAreaList(pid).then(response => {
            this.quList = response.data
          })
        }
      })
    },
    // 获取区域2
    fetchArea2() {
      getAreaList(this.qu).then(response => {
        this.jiedaoList = response.data
      })
    },
    // 取消
    cancel() {
      this.dialogFormVisible = false
      this.fileList = []
      // 清除验证
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 重置表单
    resetForm() {
      this.wellForm = {
        wellCode: '', // 窨井编号
        wellName: '', // 窨井名称
        wellType: '', // 窨井类型
        deptid: '', // 权属单位
        deep: '', // 井深，
        position: '', // 位置描述
        coordinateX: '', // 经度
        coordinateY: '', // 纬度
        photos: '', // 照片路径
        notes: '', // 备注,
        qu: '',
        area: '', // 街道
        responsibleDept: '' // 维护人员部门
      }
      // 清空上传图片
      this.$refs.upload.clearFiles()
      this.fileList = []
      this.hideUpload = this.fileList.length >= 4
      // 清除验证
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 保存数据
    saveData: function() {
      for (const image of this.fileList) {
        this.wellForm.photos += image.url + ';'
      }
      // 如果责任部门不选，则用权属作为责任部门
      if (this.wellForm.responsibleDept === '') {
        if (this.secondDeptTreeList && this.secondDeptTreeList.length > 0) {
          this.$message.warning('必须选择维护机构')
          return
        } else {
          this.wellForm.responsibleDept = this.wellForm.deptid
        }
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addWell(this.wellForm).then(response => {
            console.log('新增窨井')
            if (response.code === 200) {
              this.$message.success('新增成功!')
              this.resetForm()
            }
          })
        }
      })
    },
    // 图片上传
    uploadFile(file) {
      console.log('uploadFile:' + file.file.name)
      // const base_url = process.env.BASE_API + '/static/'
      Uploadimg(file).then(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 < 5
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        res = false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        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 >= 4
          return
        }
      }
      this.handleChange()
    },
    // 限制提示
    handleExceed(files, fileList) {
      console.log('handleExceed')
      this.$message.warning(`限制选择 4 张图片，本次选择了 ${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 >= 4
      } else {
        this.hideUpload = false
      }
    },
    handleSuccess(response, file, fileList) {
      console.log('handleSuccess')
      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 rel="stylesheet/scss" lang="scss" >
  .hide .el-upload--picture-card {
    display: none;
  }
  .main-form{
    margin: 20px 30px;
    padding: 10px;
  }
  .el-dialog{
    width:700px
  }
  .el-select{
    width: 100%;
  }
  .line{
    width: 50px;
    margin-left: 5px;
  }
  .hide .el-upload-–picture-card{
    display: none;
  }
  .imgBox{
    width: 100%;
    text-align: center;
  }
</style>
