<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :fullscreen="false" width="60%" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="transferstationForm" 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="transferstationForm.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="transferstationForm.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="area">
                <el-input v-model.trim="transferstationForm.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="transferstationForm.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="transferstationForm.lng" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纬度" prop="lat">
                <el-input v-model.trim="transferstationForm.lat" :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="responsiblePerson">
                <el-input v-model.trim="transferstationForm.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="transferstationForm.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="owner">
                <el-input v-model.trim="transferstationForm.owner" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="建设时间" prop="ts">
                <el-date-picker
                  v-model.trim="transferstationForm.ts"
                  :disabled="isDetailMode"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择建设时间"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="备注" prop="notes">
                <el-input v-model.trim="transferstationForm.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 { addTransferstation, updateTransferstation } from '@/api/sanitation/transferstation'
import { Uploadimg } from '@/api/common'
import { getDictByType } from '@/api/common'
import ChoosePointDialog from '../mapViews/choosePointDialog'

export default {
  name: 'EditTransferstation',
  components: { ChoosePointDialog },
  data() {
    return {
      baseUrl: this.baseConfig.baseUrl + '/static/',
      photo: '', // 图片路径
      defaultPhoto: require('../../assets/global_images/transferStationPhoto.png'), // 默认图片路径
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update,detail
      transferstationForm: {
        id: '', // id
        code: '', // 编号
        name: '', // 名称
        owner: '', // 建设单位
        area: '', // 占地面积
        position: '', // 位置：社区/道路
        lng: '', // 经度
        lat: '', // 纬度
        responsiblePerson: '', // 责任人
        responsiblePersonTel: '', // 责任人电话
        capacity: '', // 最新垃圾量
        ts: '', // 启用时间
        notes: '' // 备注
      }, // 表单
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '详情'
      }, // 表头显示标题
      sexList: [
        { name: '男', value: '0' },
        { name: '女', value: '1' }
      ], // 性别列表
      typeList: [],
      rules: {
        code: [{ required: true, message: '编号不能为空', trigger: ['blur', 'change'] }],
        name: [{ 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'] }]
      }, // 前端校验规则
      isEditMode: false, // 编辑模式
      isDetailMode: false, // 详情模式
      canEdit: true
    }
  },
  created() {
  },
  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.transferstationForm = {
          id: row.id, // id
          code: row.code, // 编号
          name: row.name, // 名称
          type: row.type, // 类别
          position: row.position, // 位置：社区/道路
          lng: row.lng, // 经度
          lat: row.lat, // 纬度
          responsiblePerson: row.responsiblePerson, // 责任人
          responsiblePersonTel: row.responsiblePersonTel, // 责任人电话
          area: row.area, // 占地面积
          owner: row.owner, // 建设单位
          capacity: row.capacity, // 最新垃圾量
          ts: row.ts, // 启用时间
          photo: row.photo, // 照片
          notes: row.notes // 备注
        }
        this.isEditMode = true
        this.isDetailMode = false
      } else {
        this.transferstationForm = {
          id: row.id, // id
          code: row.code, // 编号
          name: row.name, // 名称
          type: row.type, // 类别
          position: row.position, // 位置：社区/道路
          lng: row.lng, // 经度
          lat: row.lat, // 纬度
          responsiblePerson: row.responsiblePerson, // 责任人
          responsiblePersonTel: row.responsiblePersonTel, // 责任人电话
          area: row.area, // 占地面积
          owner: row.owner, // 建设单位
          capacity: row.capacity, // 最新垃圾量
          photo: row.photo, // 照片
          ts: row.ts, // 启用时间
          notes: row.notes // 备注
        }
        this.isEditMode = true
        this.isDetailMode = true
      }
      if (this.transferstationForm.photo && this.transferstationForm.photo !== '') {
        this.photo = this.baseUrl + this.transferstationForm.photo
      }
    },
    // 重置表单
    resetForm() {
      this.transferstationForm = {
        id: '', // id
        code: '', // 编号
        name: '', // 名称
        owner: '', // 建设单位
        area: '', // 占地面积
        position: '', // 位置：社区/道路
        lng: '', // 经度
        lat: '', // 纬度
        responsiblePerson: '', // 责任人
        responsiblePersonTel: '', // 责任人电话
        capacity: '', // 最新垃圾量
        ts: '', // 启用时间
        notes: '' // 备注
      }
      this.photo = ''
    },
    // 保存数据
    saveData: function() {
      // 照片不为空则对照片进行处理
      if (this.photo !== '') {
        if (this.photo.startsWith('http')) { // 上传的普通图片
          let index = this.photo.indexOf('/static/')
          if (index !== -1) {
            index += 8
          }
          this.transferstationForm.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.transferstationForm)
        if (valid) {
          addTransferstation(this.transferstationForm).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(() => {
                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) {
          updateTransferstation(this.transferstationForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
              this.canEdit = true
            }
          }).catch((e) => {
            this.canEdit = true
          })
        }else{
          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.transferstationForm.lng && this.transferstationForm.lat) {
        position = { lng: this.transferstationForm.lng, lat: this.transferstationForm.lat }
      }
      this.$refs.choosepoint.initDialog(type, position)
    },
    // 地图选点完毕
    chooseOver(marker) {
      this.$set(this.transferstationForm, 'lng', marker.lng)
      this.$set(this.transferstationForm, 'lat', marker.lat)
    },
    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>
