<template>
  <el-dialog :visible.sync="dialogFormVisible" class="editDialog" title="编辑闸井" append-to-body @close="cancel">
    <el-scrollbar :native="false">
      <el-form ref="dataForm" :label-position="labelPosition" :rules="rules" :model="wellForm" label-width="120px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="闸井名称" prop="wellName">
              <el-input v-model.trim="wellForm.wellName" type="text" placeholder="必填"/>
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="1">
            <el-form-item label="闸井编号" prop="wellCode">
              <el-input v-model.trim="wellForm.wellCode" :disabled="isEditMode" type="text" placeholder="必填"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <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="10" :offset="1">
            <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>
          <el-col :span="10">
            <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>
          <el-col :span="10">
            <el-form-item label="经度" prop="coordinateX">
              <el-input v-model.trim="wellForm.coordinateX" type="text" placeholder="必填"/>
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="1">
            <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>
          <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"
                :http-request="uploadFile"
                :file-list="imageList"
                :limit="4"
                :class="{hide:hideUpload}"
                multiple
                action="string"
                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="showResponseDept" 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="showResponseDept" 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>
          <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="13">
            <el-form-item label="闸井维护机构" prop="responsibleDept">
              <el-select v-if="secondDeptTreeList.length>=1" 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-input v-else v-model="wellForm.responsibleDeptName" type="text" placeholder="未知" disabled/>
            </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="cancel"> 取消</el-button>
            <el-button type="primary" size="medium" style="margin-left: 10px;" @click="saveData"> 保存</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
  </el-dialog>
</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, updateWell } from '@/api/well'
import { Uploadimg } from '@/api/common'
import DeptSelect from '@/components/DeptSelect'

export default {
  name: 'EditWell',
  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 > 100 || deep < 0) {
            callback(new Error('请填写0到100数值'))
          } else {
            callback()
          }
        }
      } else {
        callback(new Error('井深不能为空'))
      }
    }
    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, // 对话框是否显示
      wellForm: {
        id: null, // 闸井id
        wellCode: '', // 闸井编号
        wellName: '', // 闸井名称
        wellType: '', // 闸井类型
        deptid: '', // 权属单位
        deep: '', // 井深，
        position: '', // 位置描述
        coordinateX: '', // 经度
        coordinateY: '', // 纬度
        photos: '', // 照片路径
        notes: '', // 备注,
        qu: '',
        area: '', // 街道
        responsibleDept: '', // 维护人员部门
        responsibleDeptName: '' // 维护人员部门
      }, // 表单
      deptProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      },
      hideUpload: false,
      imageList: [],
      secondDeptTreeList: [], // 二级组织树列表
      wellTypeList: [],
      quList: [],
      jiedaoList: [],
      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: true, 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' }]
      },
      deptShowTop: false, // 权属单位下拉是否显示顶级
      dialogImageUrl: '',
      dialogVisible: false,
      labelPosition: 'right',
      responseAssignShow: false,
      isEditMode: true,
      deptShow: true
    }
  },
  computed: {
    showResponseDept() {
      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.responsibleDept = ''
        this.fetchSecondDeptTree()
        this.fetchArea1()
      }
    },
    qu(val) { // 监控区变化
      if (val !== '') {
        this.fetchArea2()
      }
    }
  },
  mounted: function() {
    this.fetchWellType()
    this.imageList = []
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogFormVisible, row = null) {
      this.imageList = []
      if (row.photos.length === 0 && this.$refs.upload) this.$refs.upload.clearFiles()
      this.dialogFormVisible = dialogFormVisible
      this.fetchWellType()
      this.wellForm = {
        id: row.id, // 闸井id
        wellCode: row.wellCode, // 闸井编号
        wellName: row.wellName, // 闸井名称
        wellType: row.wellType, // 闸井类型
        deptid: row.deptid, // 权属单位
        deep: row.deep, // 井深，
        position: row.position, // 位置描述
        coordinateX: row.coordinateX, // 经度
        coordinateY: row.coordinateY, // 纬度
        photos: row.photos, // 照片路径
        notes: row.notes, // 备注,
        qu: row.qu,
        area: row.area, // 街道
        responsibleDept: row.responsibleDept, // 维护人员部门
        responsibleDeptName: row.responsibleDeptName // 维护人员部门
      }
      if (row.deptid && row.deptid !== '') {
        this.fetchArea1(row.deptid)
        this.fetchArea2()
        this.fetchSecondDeptTree()
        this.loading = false
      }
      // 处理图片
      const base_url = process.env.BASE_API + '/static/'
      const urls = row.photos.split(';')
      for (const url of urls) {
        if (url) {
          this.imageList.push({ name: url, url: base_url + url })
        }
      }
      this.handleChange(null, this.imageList)
    },
    // 加载组织机构树形下拉菜单
    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(deptid) {
      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.wellForm.qu).then(response => {
        this.jiedaoList = response.data
      })
    },
    // 取消
    cancel() {
      this.dialogFormVisible = false
      this.imageList = []
      this.$emit('watchChild')
      // 清除验证
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 保存数据
    saveData: function() {
      this.wellForm.photos = ''
      if (this.wellForm.responsibleDept === '') {
        if (this.secondDeptTreeList.length > 0) {
          this.$message.warning('必须选择维护机构')
          return
        } else {
          this.wellForm.responsibleDept = this.wellForm.deptid
        }
      }
      for (const image of this.imageList) {
        let index = image.url.indexOf('/static/')
        if (index !== -1) {
          index += 8
        }
        this.wellForm.photos += image.url.substring(index) + ';'
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateWell(this.wellForm).then(response => {
            console.log('修改闸井')
            if (response.code === 200) {
              this.$message.success('修改成功!')
              this.$emit('watchChild')
              this.dialogFormVisible = false
              this.imageList = []
            }
            // 清除验证
            this.$nextTick(() => {
              this.$refs['dataForm'].clearValidate()
            })
          })
        }
      })
    },
    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.imageList.push({ name: file.file.name, url: base_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.imageList) {
        if (this.imageList[i].name === file.name) {
          this.imageList.splice(i, 1)
          this.hideUpload = this.imageList.length >= 4
          return
        }
      }
    },
    handleExceed(files, fileList) {
      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
      }
    }
  }
}
</script>

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

  .editDialog {
    .el-dialog {
      width: 900px;
      margin-top: 10vh !important;
      .el-dialog__body {
      }
      .el-scrollbar {
        height: 410px;
        width: 100%;
      }
      .el-scrollbar__wrap {
        /*overflow: scroll;*/
        overflow-x: auto;
        overflow-y: auto;
      }
      .el-scrollbar__view {
        width: 98%;
      }
    }
  }

  .el-select {
    width: 100%;
  }

  .line {
    width: 50px;
    margin-left: 5px;
  }

  .hide .el-upload-–picture-card {
    display: none;
  }

  .imgBox {
    width: 100%;
    text-align: center;
  }
</style>
