<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="parkingName">
          <el-input
            v-model="queryParams.param.parkingName"
            placeholder="请输入停车场名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="租赁权限" prop="open">
          <el-select
            v-model="queryParams.param.open"
            placeholder="请选择租赁权限"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
              @keyup.enter.native="handleQuery"
            />
          </el-select>
        </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="['parking: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="['parking: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="['parking: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="parkingList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="关联物业小区/项目" align="center" prop="communityName" :show-overflow-tooltip="true"/>
        <el-table-column label="关联优安停小区/停车场" align="center" prop="organizationName" :show-overflow-tooltip="true" width="220%"/>
        <el-table-column label="停车场名称" align="center" prop="parkingName" :show-overflow-tooltip="true"/>
        <el-table-column label="地址" align="center" prop="address" :show-overflow-tooltip="true"/>
        <el-table-column label="坐标" align="center" prop="longitude" >
          <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" prop="toltalParkNum" :show-overflow-tooltip="true"/>
        <el-table-column label="租赁权限" align="center" prop="open" :show-overflow-tooltip="true">
          <template slot-scope="scope">
              {{scope.row.open=='0'?'所有用户':'仅小区业主'}}
          </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="['parking:edit']"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteOne(scope.row)"
              v-hasPermi="['parking: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="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="170px">
        <el-row>
          <el-col :span="17">
            <el-form-item label="所属小区/项目" prop="communityId"><!-- 物业系统获取-->
              <el-select v-model="form.communityName" style="width: 100%" @change="changeCommunity" :disabled="addOrEditFlag">
                   <el-option
                     v-for="item in communityNameList"
                     :key="item.id"
                     :label="item.communityName"
                     :value="item.id"
                   ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin:10px 0px 10px 10px ;">
              <span>关联物业系统</span>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="17">
            <el-form-item label="小区/停车场" prop="organizationId" label-width="170px">
              <el-select v-model="form.organizationName" style="width: 100%"   @change="handleChangeArea" :disabled="addOrEditFlag">
                <el-option
                  v-for="item in parkNameList"
                  :key="item.organizationId"
                  :label="item.organizationName"
                  :value="item.organizationId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin:10px 0px 10px 10px ;">
            <span>关联优安停系统</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="17">
            <el-form-item label="停车场名称" prop="parkingName">
              <el-input v-model="form.parkingName" placeholder="请输入停车场名称" maxlength="10"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin:10px 0px 10px 10px ;">
            <span>共享车位系统内显示的名字</span>
          </el-col>
        </el-row>
        <el-form-item label="租赁权限" prop="open">
          <el-radio-group v-model="form.open">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车位数" prop="toltalParkNum" label-width="170px">
              <el-input v-model="form.toltalParkNum" placeholder="车位数" maxlength="80" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="坐标" prop="coordinate" label-width="80px">
              <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-col>
        </el-row>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" maxlength="20"/>
        </el-form-item>

<!--        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="100"/>
        </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 { listCommunity } from '@/api/estate/community'
import { listOrganization } from '@/api/park/organization'
import {
  listParking,
  getParking,
  delParking,
  addParking,
  updateParking,
  importData,
  exportParking
} from '@/api/carManage/parking'
import ScopeTree from '../components/scopeTree'
import mapPoint from '@/components/MapPoint'

export default {
  name: 'Parking',
  components: { ScopeTree,mapPoint },
  data() {
    return {
      addOrEditFlag: false,
      // 上传相关
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        // headers: { Authorization: 'Bearer ' + getToken },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/tParking/import'
      },
      downloadLoading: false,
      // 选择小区名称列表
      communityNameList: [],
      // 选择停车场名称列表
      parkNameList: [],
      // 状态数据字典
      statusOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 停车场,开通停车场的小区同步过来表格数据
      parkingList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 0,
        size: 10,
        param: {
          parkingName: null,
          address: null,
          longitude: null,
          latitude: null,
          open: null,
          isDel: null,
          version: null,
          organizationName: null
        }
      },
      // 地图变量初始化
      addMapTitle: "修改停车场位置",
      addMapVisible: false,
      coordinate: null,
      longitude: 0,
      latitude: 0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        communityId: [
          { required: true, message: '关联物业小区/项目不能为空', trigger: 'blur' }
        ],
        organizationId: [
          { required: true, message: '关联优安停小区/停车场不能为空', trigger: 'blur' }
        ],
        parkingName: [
          { required: true, message: '停车场名称不能为空', trigger: 'blur' }
        ],
        open: [
          { required: true, message: '租赁权限不能为空', trigger: 'blur' }
        ],
        coordinate: [
          { required: true, message: '坐标不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ]
      },
      parkingNames: [] //批量删除用
    }
  },
  mounted() {
    this.getList()
    this.getDicts('parking_open_status').then(response => {
      this.statusOptions = response.data
    })
    listCommunity({}).then(response => {
      this.communityNameList = response.data
    })
    listOrganization({}).then(response => {
      this.parkNameList = response.data
    })
  },
  methods: {
    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]
      }
      this.addMapVisible = false;
      this.$refs['form'].clearValidate('coordinate');//清除验证
    },

    // 下载模版 点击
    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() {
      exportParking(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);
        });
    },
    // 选择小区名称
    changeCommunity(id) {
      let obj = {};
      obj = this.communityNameList.find((item) => { //this.areaList 是通过接口请求下来的区域列表
        return item.id === id; //筛选出匹配数据
      });
      this.form.communityId = obj.id;
      this.form.communityName = obj.communityName;
      this.$refs['form'].clearValidate('communityId');//清除验证
    },
    handleChangeArea(organizationId) {
      let obj = {};
      obj = this.parkNameList.find((item) => { //this.areaList 是通过接口请求下来的区域列表
        return item.organizationId === organizationId; //筛选出匹配数据
      });
      this.form.organizationId = obj.organizationId;
      this.form.organizationName = obj.organizationName;
      this.form.parkingName = obj.organizationName;
      this.form.toltalParkNum = obj.toltalparknum
      this.$refs['form'].clearValidate('organizationId');//清除验证
    },
    /** 查询停车场,开通停车场的小区同步过来列表 */
    getList() {
      this.loading = true
      listParking(this.queryParams).then(response => {
        this.parkingList = response.records
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parkingName: null,
        address: null,
        longitude: null,
        latitude: null,
        open: '0',
        createTime: null,
        updateTime: null,
        remark: null,
        isDel: null,
        version: null,
        communityName: 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.parkingNames = selection.map(item => item.parkingName)
      console.log(this.ids)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加停车场'
      this.addOrEditFlag = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.addOrEditFlag = true;
      const id = row.id || this.ids
      getParking(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) {
            updateParking(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addParking(this.form).then(response => {
              if(response.result.code!=200){
               this.msgError(response.result.msg)
                return;
              }
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDeleteOne(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除停车场名称为"' + row.parkingName + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delParking(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除停车场名称为"' + this.parkingNames + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delParking(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    }
  }
}
</script>
