<template>
  <el-dialog :visible.sync="dialogFormVisible" class="editWellDialog" 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="必填" disabled/>
            </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 disabled>
                <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="notes">
              <el-select v-model="wellForm.notes" placeholder="点击选择备注" clearable>
                <el-option
                  v-for="item in notesTypeList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
        </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="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, getNotesType } 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 validatePosition = (rule, value, callback) => {
      if (value !== '') {
        if (value.length > 50) {
          callback(new Error('位置长度不能超过50个字'))
        } else {
          callback()
        }
      } else {
        callback(new Error('位置不能为空'))
      }
    }
    return {
      dialogFormVisible: false, // 对话框是否显示
      wellForm: {
        id: null, // 闸井id
        wellCode: '', // 闸井编号
        wellName: '', // 闸井名称
        wellType: '', // 闸井类型
        deptid: '', // 所属派出所
        deep: '', // 井深，
        position: '', // 位置描述
        photos: '', // 照片路径
        notes: '', // 备注,
        qu: '',
        area: '', // 街道
        responsibleDept: '', // 维护人员部门
        owner: '', // 产权的单位
        responsibleDeptName: '' // 维护人员部门
      }, // 表单
      deptProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      },
      hideUpload: false,
      imageList: [],
      secondDeptTreeList: [], // 二级组织树列表
      wellTypeList: [],
      notesTypeList: [],
      quList: [],
      jiedaoList: [],
      textMap: {
        update: '编辑',
        create: '新增'
      }, // 表头显示标题
      rules: {
        wellCode: [{ required: true, message: '闸井编号不能为空', trigger: ['blur', 'change'] }],
        wellName: [{ required: true, message: '闸井名称不能为空', trigger: ['blur', 'change'] }],
        position: [{ required: true, trigger: ['blur', 'change'], validator: validatePosition }],
        deep: [{ required: true, trigger: ['blur', 'change'], validator: validateDeep }],
        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.fetchNotesType()
    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, // 位置描述
        photos: row.photos, // 照片路径
        notes: row.notes, // 备注,
        qu: row.qu,
        area: row.area, // 街道
        responsibleDept: row.responsibleDept, // 维护人员部门
        responsibleDeptName: row.responsibleDeptName, // 维护人员部门
        owner: row.owner // 产权单位
      }
      this.loading = false
    },
    // 加载组织机构树形下拉菜单
    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
        }
      })
    },
    // 获取备注类型
    fetchNotesType() {
      getNotesType().then(response => {
        this.notesTypeList = response.data
      })
    },
    // 获取区域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.$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;
  }

  .editWellDialog {
    .el-dialog {
      width: 700px;
      margin-top: 10vh !important;
      .el-dialog__body {
      }
      .el-scrollbar {
        height: 300px;
        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>
