<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="Mac号" prop="mac">
        <el-input
          v-model="queryParams.mac"
          placeholder="请输入设备Mac号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="在线状态" prop="onlineStatus">
        <el-select v-model="queryParams.onlineStatus" placeholder="请选择在线状态" clearable>
          <el-option
            v-for="dict in dict.type.as_online_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.as_device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </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-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="['system:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:device:edit']"
        >修改</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="['system:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:device:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="id" align="center" prop="deviceId" />-->
      <el-table-column label="设备mac" align="center" prop="mac" />
      <el-table-column label="SN" align="center" prop="sn" />
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="车牌号" align="center" prop="vehicleNum" />
      <el-table-column label="分区" align="center" prop="areaName" />
      <el-table-column label="定位" align="center" prop="location" />
      <el-table-column label="剩余电量" align="center" prop="remainingPower" />
      <el-table-column label="车辆状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.as_device_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="车辆上下线" align="center" prop="onlineStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.as_online_status" :value="scope.row.onlineStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="二维码" align="center" width="100">
<!--        <template slot-scope="scope">-->
<!--          <image-preview :src="scope.row.qrcode" :width="50" :height="50"/>-->
<!--        </template>-->
        <template slot-scope="d">
          <el-popover
            placement="top"
            width="180"
            trigger="hover">
            <div class="qr-code-box">
              <qr-code :text="qrCodeText(d.row.sn)" :width="150" :height="150" />
<!--              <p>扫描二维码进行设备绑定</p>-->
            </div>
            <el-button slot="reference" type="text" icon="el-icon-picture">查看</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </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-view"
             @click="handleView(scope.row)"
             v-hasPermi="['system:fault:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:device:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:device:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-col :span="12">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="SN" prop="mac">
            <el-input v-model="form.sn" placeholder="请输入设备SN" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号" prop="modelId" >
            <el-select v-model="form.modelId" placeholder="请选择运营区">
              <el-option
                v-for="item in modelOptions"
                :key="item.modelId"
                :label="item.model"
                :value="item.modelId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车牌号" prop="vehicleNum">
            <el-input v-model="form.vehicleNum" placeholder="请输入车牌号" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="二维码" prop="picture">
            <image-upload v-model="form.picture"/>
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="定位" prop="location">-->
<!--            <el-input v-model="form.location" placeholder="请输入定位" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="剩余电量" prop="remainingPower">
            <el-input v-model="form.remainingPower" placeholder="请输入剩余电量" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电压" prop="voltage">
            <el-input v-model="form.voltage" placeholder="请输入剩余电量" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="form.longitude" placeholder="请输入经度" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="form.latitude" placeholder="请输入纬度" disabled/>
          </el-form-item>
        </el-col>
      </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 style="font-weight: bold;" title="设备详情" :visible.sync="open2" width="1000px" append-to-body>
      <el-form ref="form" :model="form"  label-width="100px" size="mini">
        <el-row>
          <el-col :span="8">
            <el-form-item label="设备编号：">{{ form.mac }}</el-form-item>
            <el-form-item label="车辆状态：" style="color: #12d2ac;font-weight: 700">{{ form.statusStr }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分区：" style="color:#4c97e7;font-weight: 700">{{ form.areaName }}</el-form-item>
            <el-form-item label="剩余电量：" >{{ form.remainingPower }}%</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="二维码：">
              <template>
                <image-preview style="margin-top: -30px" :src="form.qrcode" :width="50" :height="50"/>
              </template>
            </el-form-item>
            <el-form-item label="车辆上下线：" style="color: #ffcc00;font-weight: 700">{{ form.onlineStatus == 1 ? '在线' : '离线' }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <h2 style="font-weight: bold;font-size: 18px">自动更新</h2>
          <el-col :span="8">
            <el-form-item label="经度：">{{ form.longitude }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="纬度：">{{ form.latitude }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-row v-if="selected != null" style="margin-bottom: 0.5em" >
              当前选择： {{selected.address}}, {{selected.lng}}, {{selected.lat}}
            </el-row>
            <location-map
              v-if="showPlaceSearchMap"
              ref="map"
              height="400px"
              @select-changed="onSelectChange"
              @map-geo="onMapGeo"
              :init-lat="form.latitude"
              :init-lng="form.longitude"
            />
          </el-col>
        </el-row>
        <el-row>
          <div class="nav-container">
            <el-menu :default-active="activeIndex" class="el-menu-demo nav-menu" mode="horizontal" @select="handleSelect">
              <el-menu-item index="1" >使用记录</el-menu-item>
              <el-menu-item index="2" >维修记录</el-menu-item>
              <el-menu-item index="3" >换电记录</el-menu-item>
            </el-menu>
            <div class="line"></div>
          </div>
        </el-row>
        <el-row>
          <order-record v-show="activeIndex == '1'" :sn="form.sn"/>
          <repair-record v-show="activeIndex == '2'" :sn="form.sn"/>
          <replacement-record v-show="activeIndex == '3'" :sn="form.sn"/>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open2 = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/system/device";
import Map from "@/components/Map";
import OrderRecord from "@/views/system/device/components/orderRecord.vue";
import RepairRecord from "@/views/system/device/components/repairRecord.vue";
import ReplacementRecord from "@/views/system/device/components/replacementRecord.vue";
import PlaceSearchDialog from '@/components/Map/location/PlaceSearchDialog';
import { parseTime } from '../../../utils/ruoyi';
import LocationMap from '@/components/Map/location/LocationMap.vue';
import { listModel} from "@/api/system/model";
import {getWxIndexUrl} from "@/utils/wx";


export default {
  name: "Device",
  dicts: ['as_online_status', 'as_device_status'],
  components: { Map, OrderRecord, RepairRecord, ReplacementRecord, PlaceSearchDialog, LocationMap },
  props: {
    initLng: {
      type: Number,
      default: 120.356031
    },
    initLat: {
      type: Number,
      default: 26.94088
    },
  },
  data() {
    return {
      activeIndex: '1',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情窗口
      open2: false,
      // 设备型号下拉框
      modelOptions: [],
      // 通过key重新渲染area-map组件
      // key: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        mac: null,
        areaId: null,
        onlineStatus: null,
        status: null,
      },
      showPlaceSearchMap: false,
      selected: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  computed: {
    // 二维码文本
    qrCodeText() {
      return (sn) => {
        return getWxIndexUrl({ sn: sn});
      }
    },
  },
  created() {
    this.getList();
    console.log("------"+this.activeIndex)
  },
  methods: {
    onMapGeo(data, lat, lng) {
      console.log("onMapGeo", data)
      let component = data.regeocode.addressComponent;
      this.selected = {
        address: data.regeocode.formattedAddress,
        lng: lat,
        lat: lng,
        province: component.province,
        city: component.city === '' ? '市辖区' : component.city,
        county: component.district,
        name: component.street + component.streetNumber
      }
    },
    onSelectChange(addr) {
      console.log("onSelectChange", addr)
      let data = addr.selected.data;
      this.selected = {
        address: data.pname + (data.cityname === data.pname ? '' : data.cityname) + data.adname + data.address + data.name,
        lng: data.location.lng,
        lat: data.location.lat,
        province: data.pname,
        city: data.cityname === data.pname ? '市辖区' : data.cityname,
        county: data.adname,
        name: data.address + data.name,
      }
    },
    parseTime,
    // onSubmitAddress(addr) {
    //   this.form.address = addr.name;
    //   this.form.lat = addr.lat;
    //   this.form.lng = addr.lng;
    //   this.form.province = addr.province;
    //   this.form.city = addr.city;
    //   this.form.county = addr.county;
    //   this.form.specificAddress = addr.name;
    // },
    handleSelect(key, keyPath) {
      this.activeIndex = key;
      console.log(key, keyPath);
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        picture: null,
        deviceName: null,
        mac: null,
        areaId: null,
        activationTime: null,
        onlineStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        status: null,
        location: null,
        remainingPower: null,
        qrcode: null,
        longitude: null,
        latitude: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      listModel(this.queryParams).then(response => {
        this.modelOptions = response.rows;
        this.open = true;
        this.title = "添加设备";
      });
    },
    /** 详情按钮 */
    handleView(row) {
      this.open2 = true;
      this.form = row;
      this.showPlaceSearchMap = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids
      getDevice(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('是否确认删除设备编号为"' + deviceIds + '"的数据项？').then(function() {
        return delDevice(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
  .nav-container {
    display: flex;
    justify-content: center;
  }
  .nav-menu {
    /* 如果需要清除默认样式 */
    margin: 0;
    padding: 0;
  }
  .el-dialog__body{
    padding: 10px 20px;
  }
  .el-dialog:not(.is-fullscreen) {
    margin-top: 3vh !important;
  }
</style>
