<template>
  <div class="card-container">
    <el-card class="card-heard">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="停车场名称" prop="parkingId">
          <el-select
            v-model="queryParams.param.parkingId"
            placeholder="请输入停车场名称"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in parkNameList"
              :key="item.id"
              :label="item.parkingName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车位编号" prop="spaceNo">
          <el-input
            v-model="queryParams.param.spaceNo"
            placeholder="请输入车位编号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="业主手机号" prop="phone">
          <el-input
            v-model="queryParams.param.phone"
            placeholder="请输入业主手机号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="card-body">
      <el-row :gutter="10" class="mb8">
        <!--        <el-col :span="1.5">
                  <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['space:add']"
                  >新增
                  </el-button>
                </el-col>-->
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['space:remove']"
          >删除
          </el-button>
        </el-col>
<!--        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['space:import']"
          >
            导入
          </el-button>
        </el-col>-->
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-download"
            :loading="downloadLoading"
            @click="handleExport"
            size="mini"
            v-hasPermi="['parking:export']"
          >导出
          </el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="spaceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="停车场名称" align="center" prop="parkingName" :show-overflow-tooltip="true"/>
        <el-table-column label="业主手机号" align="center" prop="phone" :show-overflow-tooltip="true"/>
        <el-table-column label="车位编号" align="center" prop="spaceNo" :show-overflow-tooltip="true"/>
        <el-table-column label="位置描述" align="center" prop="address" :show-overflow-tooltip="true"/>
        <el-table-column label="车位坐标" align="center" prop="longitude" :show-overflow-tooltip="true">
          <template slot-scope="scope" v-if="scope.row.longitude!=null && scope.row.latitude!=null">
            {{ scope.row.longitude + ',' + scope.row.latitude }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['space:edit']"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteOne(scope.row)"
              v-hasPermi="['space:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <pagination
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改停车位信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="停车场名称" prop="parkingId">
          <el-select v-model="form.parkingName" style="width: 100%" @change="handleChange" :disabled="true">
            <el-option
              v-for="item in parkNameList"
              :key="item.id"
              :label="item.parkingName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业主手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入业主手机号" maxlength="11"/>
        </el-form-item>
        <el-form-item label="车位编号" prop="spaceNo">
          <el-input v-model="form.spaceNo" placeholder="请输入车位编号" maxlength="10" :disabled="true"/>
        </el-form-item>
        <el-form-item label="位置描述" prop="address">
          <el-input v-model="form.address" placeholder="请输入位置描述" maxlength="30"/>
        </el-form-item>
        <el-form-item label="坐标" prop="coordinate" label-width="120px">
          <div style="display: flex;justify-content: center">
          <el-input placeholder="请搜索坐标" v-model="form.coordinate" class="input-with-select" :disabled="true" style="width: 80%;">
          </el-input>
          <el-button type="primary" @click="showMap2(form)" style="margin-left: 5px;height: 35px;">修改</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--地图弹框-->
    <el-dialog
      :title="addMapTitle"
      :visible.sync="addMapVisible"
      v-if="addMapVisible"
      width="1000px"
      style="padding-bottom: 50px"
    >
      <mapPoint @changeView="changeMapView"></mapPoint>
      <div slot="footer" class="dialog-footer" style="height: 40px">

      </div>
    </el-dialog>

    <!-- 导入 弹框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :http-request="uploadExcel"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="color: #2866e4; font-size: 12px" @click="downloadTemplate"
          >下载模板
          </el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示:仅允许导入“xls”或“xlsx”格式文件!
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listParkName
} from '@/api/carManage/parking'
import {
  listSpace,
  getSpace,
  delSpace,
  addSpace,
  updateSpace,
  importData,
  exportSpace
} from '@/api/carManage/space'
import mapPoint from '@/components/MapPoint'

export default {
  name: 'Space',
  components: { mapPoint },
  data() {
    return {
      // 上传相关
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        // headers: { Authorization: 'Bearer ' + getToken },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/tSpace/import'
      },
      downloadLoading: false,
      // 选择停车场名称列表
      parkNameList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 停车位信息表格数据
      spaceList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 地图变量初始化
      // 地图变量初始化
      addMapTitle: '修改车位位置',
      addMapVisible: false,
      coordinate: null,
      longitude: 0,
      latitude: 0,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        param: {
          userId: null,
          targetId: null,
          spaceNo: null,
          address: null,
          hideNo: null,
          longitude: null,
          latitude: null,
          parkingId: null,
          isDel: null,
          version: null,
          parkingName: null,
          phone: null
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        phone: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        spaceNo: [
          {
            required: true,
            message: '请输入车位编号',
            trigger: 'blur'

          }
        ]
      },
      spaceNos: [] //批量删除用
    }
  },
  created() {
    this.getList()
    listParkName({}).then(response => {
      this.parkNameList = response.result
    })
  },
  methods: {
    // 下载模版 点击
    downloadTemplate() {
      window.open(
        'http://fresh-life.oss-cn-shanghai.aliyuncs.com/sharedCarTemplate/车位.xlsx'
      )
    },
    // 导入数据
    handleImport() {
      this.upload.title = '车位导入'
      this.upload.open = true
    },
    // 上传Excel
    uploadExcel(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      importData(formData)
        .then((res) => {
          // console.log("上传成功");
          this.msgSuccess('导入成功')
          param.onSuccess()
        })
        .catch((res) => {
          // console.log("上传失败");
          this.msgError('导入失败')
          param.onError()
        })
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },

    /*导出数据 */
    handleExport() {
      exportSpace(this.queryParams.param)
        .then((res) => {
          if (res.code === 200) {
            if (res.result) {
              this.msgSuccess('导出成功')
              window.open(res.result)
            } else {
              this.msgSuccess('导出失败')
            }
          } else {
            this.msgError(res.msg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handleChange(id) {
      let obj = {}
      obj = this.parkNameList.find((item) => { //this.areaList 是通过接口请求下来的区域列表
        return item.id === id //筛选出匹配数据
      })
      this.form.parkingId = obj.id
      this.form.parkingName = obj.parkingName
    },
    /** 查询停车位信息列表 */
    getList() {
      this.loading = true
      listSpace(this.queryParams).then(response => {
        this.spaceList = response.records
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        targetId: null,
        spaceNo: null,
        address: null,
        hideNo: null,
        longitude: null,
        latitude: null,
        parkingId: null,
        createTime: null,
        updateTime: null,
        remark: null,
        isDel: null,
        version: null
      }

      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        current: 1,
        size: 10,
        param: {}
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.spaceNos = selection.map(item => item.spaceNo)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加停车位信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getSpace(id).then(response => {
        this.form = response.result
        if (response.result.longitude != null && response.result.latitude != null) {
          this.form.coordinate = response.result.longitude + ',' + response.result.latitude
        }
        this.open = true
        this.title = '编辑停车位信息'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSpace(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addSpace(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDeleteOne(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除停车位编号为"' + row.spaceNo + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delSpace(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除停车位编号为"' + this.spaceNos + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delSpace(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    showMap2(data) {
      console.log(data)
      // this.path = area;
      console.log(data.latitude)
      console.log(data.longitude)
      if (data.latitude != null && data.longitude != null) {
        this.latitude = Number(data.latitude)
        this.longitude = Number(data.longitude)
      } else {
        this.latitude = 0
        this.longitude = 0
      }
      this.addMapVisible = true
    },
    changeMapView(data) {
      if (data.flag) {

        this.form.longitude = data.lng[0];
        this.form.latitude = data.lng[1];
        this.form.coordinate = "";
        this.form.coordinate = data.lng[0] + ',' + data.lng[1]
        console.log('---' + this.latitude + '--' + this.longitude)
      }
      this.addMapVisible = false
    }
  }
}
</script>
<style>
.el-message-box__message{
  word-wrap: break-word!important;
}
</style>
