<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :fullscreen="false" width="60%" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="wastebinForm" label-well-code="right" label-width="100px">
      <div class="form-div">
        <div class="form-left">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="编号" prop="code">
                <el-input v-model.trim="wastebinForm.code" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model.trim="wastebinForm.name" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="类别" prop="type">
                <el-select v-model="wastebinForm.type" :disabled="isDetailMode" placeholder="请选择垃圾桶类别">
                  <el-option
                    v-for="item in typeList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务人口数" prop="servicePeople">
                <el-input v-model.trim="wastebinForm.servicePeople" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="区域" prop="area">
                <el-input v-model.trim="wastebinForm.area" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="街道" prop="street">
                <el-input v-model.trim="wastebinForm.street" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="小区/路段" prop="road">
                <el-input v-model.trim="wastebinForm.area" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置" prop="position">
                <el-input v-model.trim="wastebinForm.position" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="经度" prop="lng">
                <el-input v-model.trim="wastebinForm.lng" :disabled="isDetailMode" type="text" placeholder="经度，如：116.4">
                  <el-button v-if="!isDetailMode" slot="append" icon="el-icon-map-location" @click="choosePoint('edit')"/>
                  <el-button v-if="isDetailMode" slot="append" icon="el-icon-map-location" @click="choosePoint('readonly')"/>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纬度" prop="lat">
                <el-input v-model.trim="wastebinForm.lat" :disabled="isDetailMode" type="text" placeholder="纬度，如：39.9"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="责任人" prop="responsiblePerson">
                <el-input v-model.trim="wastebinForm.responsiblePerson" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="责任人电话" prop="responsiblePersonTel">
                <el-input v-model.trim="wastebinForm.responsiblePersonTel" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="收集单位" prop="collectCompany">
                <el-input v-model.trim="wastebinForm.collectCompany" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收集车辆" prop="collectCar">
                <el-input v-model.trim="wastebinForm.collectCar" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="收集频率" prop="collectFrequency">
                <el-input v-model.trim="wastebinForm.collectFrequency" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="notes">
                <el-input v-model.trim="wastebinForm.notes" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!--右边照片-->
        <div class="form-right">
          <el-row>
            <div class="avatar">
              <el-image
                :src="photo!==''?photo:defaultPhoto"
                fit="cover"
                style="width: 130px; height: 175px"/>
            </div>
          </el-row>
          <el-row>
            <el-upload
              v-show="!isDetailMode"
              ref="upload"
              :before-upload="handleBeforeUpload"
              :on-success="handleSuccess"
              :http-request="uploadFile"
              :show-file-list="false"
              class="avatar-uploader"
              action="string"
              accept=".jpg,.jpeg,.png">
              <el-button type="primary">点击上传照片</el-button>
            </el-upload>
            <el-button v-show="!isDetailMode" type="primary" style="width:126px;margin-top:15px;" @click="choosePoint('edit')">地图选点</el-button>
            <el-button v-show="isDetailMode" type="primary" style="width:126px;margin-top:15px;" @click="choosePoint('readonly')">查看地图</el-button>
          </el-row>
        </div>
      </div>
    </el-form>
    <div v-show="!isDetailMode" slot="footer" class="dialog-footer">
      <el-button :disabled="!canEdit" type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
    <!--地图选点-->
    <choose-point-dialog ref="choosepoint" @choose="chooseOver"/>
  </el-dialog>
</template>

<script>
import { addWastebin, updateWastebin } from '@/api/biz/wastebin'
import { getDictByType, Uploadimg } from '@/api/common'
import ChoosePointDialog from '../mapViews/choosePointDialog'
export default {
  name: 'EditWastebin',
  components: { ChoosePointDialog },
  data() {
    return {
      baseUrl: this.baseConfig.baseUrl + '/static/',
      photo: '', // 图片路径
      defaultPhoto: require('../../assets/global_images/toiletPhoto.png'), // 默认图片路径
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update,detail
      wastebinForm: {
        id: '', // id
        code: '', // 编号
        name: '', // 名称
        type: '', // 类别
        area: '', // 区域
        road: '', // 小区/路段
        street: '', // 街道
        position: '', // 位置：社区/道路
        lng: '', // 经度
        lat: '', // 纬度
        isClassification: '0', // 是否分类箱
        servicePeople: '', // 服务人口
        collectCompany: '', // 收集单位
        collectCar: '', // 收集车辆
        collectFrequency: '', // 收集频率
        photo: '',
        responsiblePerson: '', // 责任人
        responsiblePersonTel: '', // 责任人电话
        notes: '' // 备注
      }, // 表单
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '详情'
      }, // 表头显示标题
      typeList: [],
      rules: {
        code: [{ required: true, message: '编号不能为空', trigger: ['blur', 'change'] }],
        name: [{ required: true, message: '名称不能为空', trigger: ['blur', 'change'] }],
        area: [{ required: true, message: '区域不能为空', trigger: ['blur', 'change'] }],
        street: [{ required: true, message: '街道不能为空', trigger: ['blur', 'change'] }],
        road: [{ required: true, message: '小区/路段不能为空', trigger: ['blur', 'change'] }],
        position: [{ required: true, message: '位置不能为空', trigger: ['blur', 'change'] }],
        lng: [{ required: true, message: '经度不能为空', trigger: ['blur', 'change'] }],
        lat: [{ required: true, message: '纬度不能为空', trigger: ['blur', 'change'] }],
        type: [{ required: true, message: '类别必选', trigger: ['blur', 'change'] }]
      }, // 前端校验规则
      isEditMode: false, // 编辑模式
      isDetailMode: false, // 详情模式
      canEdit: true
    }
  },
  created() {
    this.fetchWastebinType()
  },
  methods: {
    /**
     * 初始化对话框
     * @param dialogStatus 对话框类型
     * @param dialogFormVisible 对话框是否可见
     * @param row 内容参数（编辑和详情需要）
     */
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.isEditMode = false
        this.isDetailMode = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.wastebinForm = {
          id: row.id, // id
          code: row.code, // 编号
          name: row.name, // 名称
          type: row.type, // 类别
          area: row.area, // 区域
          street: row.street, // 街道
          road: row.road, // 小区/路段
          position: row.position, // 位置
          lng: row.lng, // 经度
          lat: row.lat, // 纬度
          servicePeople: row.servicePeople, // 服务人口
          isClassification: row.isClassification, // 是否分类箱
          collectCompany: row.collectCompany, // 是否分类箱
          collectCar: row.collectCar, // 是否分类箱
          collectFrequency: row.collectFrequency, // 是否分类箱
          responsiblePerson: row.responsiblePerson, // 责任人
          responsiblePersonTel: row.responsiblePersonTel, // 责任人电话
          photo: row.photo, // 照片
          notes: row.notes // 备注
        }
        this.isEditMode = true
        this.isDetailMode = false
      } else {
        this.wastebinForm = {
          id: row.id, // id
          code: row.code, // 编号
          name: row.name, // 名称
          type: row.type, // 类别
          area: row.area, // 区域
          street: row.street, // 街道
          road: row.road, // 小区/路段
          position: row.position, // 位置
          lng: row.lng, // 经度
          lat: row.lat, // 纬度
          servicePeople: row.servicePeople, // 服务人口
          isClassification: row.isClassification, // 是否分类箱
          collectCompany: row.collectCompany, // 是否分类箱
          collectCar: row.collectCar, // 是否分类箱
          collectFrequency: row.collectFrequency, // 是否分类箱
          responsiblePerson: row.responsiblePerson, // 责任人
          responsiblePersonTel: row.responsiblePersonTel, // 责任人电话
          photo: row.photo, // 照片
          notes: row.notes // 备注
        }
        this.isEditMode = true
        this.isDetailMode = true
      }
      if (this.wastebinForm.photo && this.wastebinForm.photo !== '') {
        this.photo = this.baseUrl + this.wastebinForm.photo
      }
    },
    // 重置表单
    resetForm() {
      this.wastebinForm = {
        id: '', // id
        code: '', // 编号
        name: '', // 名称
        type: '', // 类别
        area: '', // 区域
        road: '', // 小区/路段
        street: '', // 街道
        position: '', // 位置：社区/道路
        lng: '', // 经度
        lat: '', // 纬度
        isClassification: '0', // 是否分类箱
        servicePeople: '', // 服务人口
        collectCompany: '', // 收集单位
        collectCar: '', // 收集车辆
        collectFrequency: '', // 收集频率
        photo: '',
        responsiblePerson: '', // 责任人
        responsiblePersonTel: '', // 责任人电话
        notes: '' // 备注
      }
    },
    // 保存数据
    saveData: function() {
      // 照片不为空则对照片进行处理
      if (this.photo !== '') {
        if (this.photo.startsWith('http')) { // 上传的普通图片
          let index = this.photo.indexOf('/static/')
          if (index !== -1) {
            index += 8
          }
          this.wastebinForm.photo = this.photo.substring(index)
        }
      }
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.canEdit = false
      this.$refs['dataForm'].validate((valid) => {
        console.log(this.wastebinForm)
        if (valid) {
          addWastebin(this.wastebinForm).then(response => {
            if (response.code === 200) {
              this.$confirm('新增成功，是否继续新增?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetForm()
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                  this.canEdit = true
                })
              }).catch((e) => {
                this.$emit('watchChild')
                this.dialogFormVisible = false
                this.canEdit = true
              })
            }
          }).catch((e) => {
            this.canEdit = true
          })
        } else {
          this.canEdit = true
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.canEdit = false
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateWastebin(this.wastebinForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
              this.canEdit = true
            }
          }).catch((e) => {
            this.canEdit = true
          })
        }
      })
    },
    // 图片上传
    uploadFile(file) {
      console.log('uploadFile:' + file.file.name)
      Uploadimg(file).then(res => {
        if (res.code === 200) {
          this.photo = this.baseUrl + res.data
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 上传前判断文件格式及大小
    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
      }
      return res
    },
    // 上传成功后回显
    handleSuccess(response, file) {
      console.log('handleSuccess')
      if (response.code === 200) {
        this.photo = this.baseUrl + response.data
      } else {
        this.$message.warning(response.message)
      }
    },
    // 打开地图选点
    choosePoint(type) {
      let position = null
      if (this.wastebinForm.lng && this.wastebinForm.lat) {
        position = { lng: this.wastebinForm.lng, lat: this.wastebinForm.lat }
      }
      this.$refs.choosepoint.initDialog(type, position)
    },
    // 地图选点完毕
    chooseOver(marker) {
      this.$set(this.wastebinForm, 'lng', marker.lng)
      this.$set(this.wastebinForm, 'lat', marker.lat)
    },
    // 获取垃圾桶类别
    fetchWastebinType() {
      getDictByType('wastebinType').then(response => {
        this.typeList = response.data
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-select{
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
  .form-div{
    width:100%;
    height:100%;
    display:flex;
    justify-content: space-between;
  }
  .form-left{
    flex:1;
    height:100%;
  }
  .form-right{
    width: 180px;
    height:100%;
    .avatar{
      margin-bottom: 10px;
    }
    text-align: center;
  }
</style>
