<template>
  <div class="common-page">
    <div class="option page-row">
      <!--工具栏-->
      <div class="head-container">
        <!-- 搜索 -->
        <label class="el-form-item-label" style="font-weight: 500;">项目名称</label>
        <el-input v-model="query.name" clearable size="small" placeholder="请输入项目名称" style="width:140px;" @clear="clearLimit" />

        <label class="el-form-item-label" style="font-weight: 500;margin-left: 10px;">所在位置</label>
        <el-input v-model="query.address" clearable size="small" placeholder="请输入所在位置" style="width:150px;" @clear="clearLimit" />

        <el-button size="mini" type="success" icon="el-icon-search" @click="toSearch">搜索</el-button>
      </div>
    </div>
    <div class="panel-bottom page-row">
      <h3>项目管理列表</h3>
      <div class="ctin-box">
        <div class="content-within">
          <div class="content-fix">
            <div class="toolbar">
              <el-button size="mini" type="primary" icon="el-icon-plus" @click="toAdd">新增</el-button>
            </div>
            <div class="content">
              <el-table v-loading="loading" :data="tableData" border style="width:auto" :row-class-name="tableRowClassName">
                <el-table-column prop="name" label="项目名称" />
                <el-table-column prop="address" label="项目所在地址" />
                <el-table-column prop="lng" label="经度" />
                <el-table-column prop="lat" label="纬度" />
                <el-table-column prop="createTime" label="项目创立时间" />
                <el-table-column label="操作" width="130px" align="center" fixed="right">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit" @click="toEdit(scope.row)" />
                    <el-button size="mini" type="danger" icon="el-icon-delete" @click="toDelete(scope.row)" />
                  </template>
                </el-table-column>
              </el-table>
              <!--分页组件-->
              <el-pagination :total="total" :current-page="page" style="margin-top: 8px;" layout="total, prev, pager, next, sizes" @size-change="sizeChange" @current-change="pageChange" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 表单渲染 -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelForm" :visible.sync="form.visible" :title="form.title" width="520px">
      <el-form ref="form1" :model="form.item" :rules="rules" :inline="true" size="small" label-width="80px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.item.name" style="width:260px;" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="所在地址" prop="address">
          <el-input v-model="form.item.address" style="width:260px;" placeholder="请选择位置" />
          <el-button size="mini" type="primary" @click="toSearchAddress(form.item.address)">搜索</el-button>
        </el-form-item>
        <el-form-item label="选择位置" prop="" style="display:block;">
          <div id="dialogMap" class="dialog-map">
            <cu-amap
              ref="amap"
              :mapinfo="mapinfo"
              :onload="amapOnload"
              @click="mapClick"
            />
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.item.remark" style="width:260px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancelForm">取消</el-button>
        <el-button :loading="form.status.cu === 2" type="primary" @click="submitForm('form1', form.item)">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { HttpReq } from '@/assets/js/common.js'
import cuAmap from '@/components/AMap'
// style
import '@/assets/styles/common.css'

export default {
  name: 'Dashboard',
  components: {
    cuAmap
  },
  data() {
    return {
      loading: false,
      page: 1,
      size: 10,
      total: 0,
      query: {},
      tableData: [],
      form: {
        title: '添加项目',
        visible: false, 
        reqType: 'add',
        status: { cu: 0 },
        item: {
          name: '',
          address: '',
          lng: '',
          lat: '',
          remark: ''
        }
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        address: [
          { type: 'string', required: true, message: '请选择位置', trigger: 'blur' }
        ]
      },
      mapinfo: {
        zoom: 6,
        longitude: 120.651884,
        latitude: 36.962533
      }
    }
  },
  mounted() {
    // var that = this

    this.$nextTick(() => {
      this.loadData()
    })
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    // 点击搜索
    toSearch() {
      this.page = 1
      this.loadData()
    },
    clearLimit() {		// 清除限制
      this.loadData()
    },
    loadData() {
      // var that = this; 
      var sort = 'createTime,desc'
      var param = this.query
      param.page = this.page - 1
      param.size = this.size
      param.sort = sort

      // 按时间过滤
      // var param2 = {}
      var Time = param.createTime || []
      if (Time[0]) {
        var date1 = new Date(Time[0]).getTime()
        var date2 = new Date(Time[1] || Time[0]).getTime()
        // param2 = { date1: date1, date2: date2 }
      }
      this.loading = true

      HttpReq.project.getProject(param).then((res) => {
        this.loading = false
        if (res.code === 200) {
          var body = res.data || {}
          var list = body.content || []
          this.tableData = list
          this.total = body.totalElements
        }
      }).catch(function(error) {
        this.loading = false
      })
    },

    toAdd() {
      this.form.status.cu = 0
      this.form.visible = true
      this.form.reqType = 'add'
      this.form.title = '添加项目'
      this.form.item = {
        name: '',
        address: '',
        lng: '',
        lat: '',
        remark: ''
      }
    },
    toDelete(item) {
      var id = item.id
      this.$confirm('确认删除该条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((e) => {
        this.reqRemoveProject([id])
      }).catch((e) => {
      })
    },
    toEdit(data) {
      var that = this; var camap = this.$refs.amap
      this.form.status.cu = 0
      this.form.visible = true
      this.form.item = data
      this.form.reqType = 'edit'
      this.form.title = '修改项目'
      if (camap) {
        camap.setCenter([data.lng, data.lat])
        camap.addMarker({
          lnglat: [data.lng, data.lat],
          title: '',
          draggable: true,
          dragend: function(e) {
            var lnglat = e.lnglat
            camap.deGeocode([lnglat.lng, lnglat.lat], function(addr) {
              that.form.item.lng = lnglat.lng
              that.form.item.lat = lnglat.lat
              that.form.item.address = addr
            })
          }
        })
      } else {
        this.mapOnload = function() {
          camap = this.$refs.amap
          camap.addMarker({
            lnglat: [data.lng, data.lat],
            title: '',
            draggable: true,
            dragend: function(e) {
              var lnglat = e.lnglat
              camap.deGeocode([lnglat.lng, lnglat.lat], function(addr) {
                that.form.item.lng = lnglat.lng
                that.form.item.lat = lnglat.lat
                that.form.item.address = addr
              })
            }
          })
        }
      }
    },
    pageChange(e) {
      this.page = e
      this.loadData()
    },
    sizeChange(e) {
      this.page = 1
      this.size = e
      this.loadData()
    },
    cancelForm() {
      this.form.visible = false
    },
    submitForm(validateName, item) {
      if (!this.form.status.cu) {
        this.form.status.cu = 2
        this.$refs[validateName].validate(valid => {
          if (valid) {
            if (this.form.reqType === 'add') {
              this.reqAddProject(this.form, item)
            } else {
              this.reqUpdateProject(this.form, item)
            }
          } else {
            this.form.status.cu = 0
          }
        })
      }
    },
    reqAddProject(form, item) {
      HttpReq.project.saveProject(item).then((res) => {
        form.visible = false
        if (res.code === 200) {
          this.$notify({
            title: '项目添加' + res.msg,
            type: 'success',
            duration: 2500
          })
        } else {
          this.$notify({
            title: res.msg,
            type: 'error',
            duration: 2500
          })
        }

        this.loadData()
      }).catch(function(error) {
        form.status.cu = 0
      })
    },
    reqUpdateProject(form, item) {
      HttpReq.project.updateProject(item).then((res) => {
        form.visible = false
        if (res.code === 200) {
          this.$notify({
            title: '修改' + res.msg,
            type: 'success',
            duration: 2500
          })
        } else {
          this.$notify({
            title: res.msg,
            type: 'error',
            duration: 2500
          })
        }
        this.loadData()
      }).catch(function(error) {
        form.status.cu = 0
      })
    },
    reqRemoveProject(item) {
      HttpReq.project.removeProject(item).then((res) => {
        if (res.code === 200) {
          this.$notify({
            title: '删除项目' + res.msg,
            type: 'success',
            duration: 2500
          })
        } else {
          this.$notify({
            title: res.msg,
            type: 'error',
            duration: 2500
          })
        }
        this.loadData()
      }).catch(function(error) {
      })
    },

    // 地图
    mapClick(e) {
      var that = this; var lnglat = e.lnglat; var camap = this.$refs.amap
      // 地址解码
      camap.deGeocode([lnglat.lng, lnglat.lat], function(addr) {
        that.form.item.lng = lnglat.lng
        that.form.item.lat = lnglat.lat
        that.form.item.address = addr
      })

      // 添加标记
      camap.addMarker({
        lnglat: [lnglat.lng, lnglat.lat],
        title: '',
        draggable: true,
        dragend: function(e) {
          var lnglat = e.lnglat
          camap.deGeocode([lnglat.lng, lnglat.lat], function(addr) {
            that.form.item.lng = lnglat.lng
            that.form.item.lat = lnglat.lat
            that.form.item.address = addr
          })
        }
      })
    },
    amapOnload() {
      this.mapOnload && this.mapOnload()
    },
    toSearchAddress(addr) {
      var that = this; var camap = this.$refs.amap
      // 搜索
      camap.addressSearch(addr).then((res) => {
        that.form.item.lng = res.location.lng
        that.form.item.lat = res.location.lat
        var marker = camap.addMarker({
          lnglat: [res.location.lng, res.location.lat],
          draggable: true,
          dragend: function(e) {
            var lnglat = e.lnglat
            camap.deGeocode([lnglat.lng, lnglat.lat], function(addr) {
              that.form.item.lng = lnglat.lng
              that.form.item.lat = lnglat.lat
              that.form.item.address = addr
            })
          }
        })
        camap.deGeocode([res.location.lng, res.location.lat], function(addr) {
          that.form.item.address = addr
        })

        this.$refs.amap.setFitView(marker)
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
	.el-table .warning-row {
		background: oldlace;
	}

	.el-table .success-row {
		background: #f0f9eb;
	}

	.dialog-map{border:1px solid green;height:300px;width:480px;}

</style>
