<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="SN" prop="deviceNo">
        <el-input
          v-model="queryParams.deviceNo"
          placeholder="请输入设备SN码"
          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 @change="handleQuery">
          <el-option
            v-for="dict in dict.type.device_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 @change="handleQuery">
          <el-option
            v-for="dict in dict.type.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-has-permi="['bst:device: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-has-permi="['bst: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-has-permi="['bst:device:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange" :default-sort="defaultSort"  @sort-change="onSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="column of showColumns">
        <el-table-column
            :key="column.key"
            :label="column.label"
            :prop="column.key"
            :align="column.align"
            :min-width="column.minWidth"
            :sort-orders="orderSorts"
            :sortable="column.sortable"
            :show-overflow-tooltip="column.overflow"
            :width="column.width"
        >

        </el-table-column>
      </template>
      <el-table-column label="设备名称" align="center" width="220">
        <template slot-scope="scope">
          <i class="el-icon-s-opportunity"/>
          <device-link
            :id="scope.row.deviceId"
            :text="scope.row.deviceName"
            size="mini"
          />
            <device-sn
              :sn="scope.row.deviceNo"
              style="margin-left: 8px; vertical-align: middle"
            >
              <el-button
                type="text"
                icon="el-icon-picture"
                size="mini"
                class="qrcode-btn"
              >设备二维码</el-button>
            </device-sn>

        </template>
      </el-table-column>
      <el-table-column label="型号" align="center" prop="modelName" />
      <el-table-column label="SN" align="center" prop="deviceNo" />
      <el-table-column label="MAC-1" align="center" prop="mac" />
      <el-table-column label="MAC-2" align="center" prop="mac2" />
      <el-table-column label="在线状态" align="center" prop="onlineStatus">
        <template slot-scope="scope">
          <dict-tag
            :value="scope.row.onlineStatus"
            :options="dict.type.device_online_status"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :value="scope.row.status"
            :options="dict.type.device_status"
          />
        </template>
      </el-table-column>
      <el-table-column label="设备所绑用户" align="center" prop="userName" >
        <template slot-scope="{row}">
            <i class="el-icon-user"/>
            <user-link
              :id="row.userId"
              :text="row.userName"
              size="mini"
            />
        </template>
      </el-table-column>
      <el-table-column label="归属店铺" align="center" prop="storeName" >
        <template slot-scope="{row}">
          <div v-if="row.storeName != null">
            <i class="el-icon-takeaway-box"/>
            <store-link
              :id="row.storeId"
              :name="row.storeName || '--'"
              size="mini"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="最后在线时间" align="center" prop="lastOnlineTime" />
      <el-table-column label="卡座名称" align="center" prop="position" >
        <template slot-scope="{row}">
          <div v-if="row.position != null">
            <i class="el-icon-takeaway-box"/>
            <booth-link
              :id="row.boothId"
              :text="row.position"
              size="mini"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleSee(scope.row)"
            v-has-permi="['bst:device:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-has-permi="['bst:device:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-shop"
            @click="handleChangeStore(scope.row)"
            v-has-permi="['bst:device:changeStore']"
            v-if="scope.row.userId"
          >投放店铺</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleUnbindStoreConfirm(scope.row)"
            v-has-permi="['bst:store:unbindStore']"
            v-if="scope.row.storeId"
          >解绑店铺</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleUnbindBoothConfirm(scope.row)"
            v-has-permi="['bst:booth:unbindBooth']"
            v-if="scope.row.boothId"
          >解绑卡座</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-has-permi="['bst: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"
    />

    <change-store-dialog
      :visible.sync="showChangeStore"
     :device="selectDevice"
      @success="handleChangeStoreSuccess"
    />

    <device-edit-dialog
      :visible.sync="showEditDialog"
      :device-id="selectDeviceId"
      @success="getList"
    />

  </div>
</template>

<script>
import {listDevice, getDevice, delDevice, addDevice, updateDevice, logicDelDevice} from "@/api/bst/device";
import { $showColumns } from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import DeviceSn from "@/views/bst/device/components/DeviceSn.vue";
import DeviceEditDialog from "@/views/bst/device/components/DeviceEditDialog.vue";
import StoreLink from "@/views/bst/store/StoreLink.vue";
import ChangeStoreDialog from "@/views/bst/device/components/DeviceChangeStoreDialog.vue";
import {unbindBooth} from "@/api/bst/booth";
import {unbindStore} from "@/api/bst/store";
import BoothLink from "@/views/bst/booth/components/BoothLink.vue";
import UserLink from "@/views/system/user/UserLink.vue";
import DeviceLink from "@/components/Business/Device/DeviceLink.vue";

  // 默认排序字段
const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "Device",
  mixins: [$showColumns],
  dicts: ['device_status', 'device_online_status', 'device_power_status'],
  props: {
    query: {
      type: Object,
      default: () => ({})
    }
  },
  components: {DeviceLink, UserLink, BoothLink, ChangeStoreDialog, StoreLink, DeviceEditDialog, DeviceSn, FormCol},
  data() {
    return {
      // 是否展示编辑弹窗
      showEditDialog: false,
      // 选中的设备ID
      selectDeviceId: null,
      // 是否展示更换店铺弹窗
      showChangeStore: false,
      // 选中的设备
      selectDevice: null,
      span: 24,
      gutter: 8,
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        deviceNo: null,
        storeId: null,
        userId: null,
        modelId: null,
        deviceName: null,
        mac: null,
        mac2: null,
        totalElectriQuantity: null,
        onlineStatus: null,
        status: null,
        realTimePower: null,
        electricity: null,
        voltage: null,
        set: null,
        wifi: null,
        deleted: null,
        lastPullTime: null,
        initReading: null,
        powerStatus: null,
        expireTime: null,
        customPicture: null,
        remainTime: null,
        surplusEle: null,
        lastOnlineTime: null,
        onlineStatus1: null,
        onlineStatus2: null,
        version: null,
        expireEle: null,
        lastInitReading: null,
        vxs: null,
        imsi: null,
        wxs: null,
        lastRecoverTime: null
      },

      // 表单参数
      form: {},
    };
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }
    this.getList();
  },
  methods: {
    handleUnbindStoreConfirm(row) {
      this.$confirm('是否确定解除店铺和设备的绑定关系？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.executeStoreUnbind(row);
      }).catch(() => {});
    },

    // 执行解绑店铺操作
    async executeStoreUnbind(row) {
      try {
        const deviceData = {
          deviceId: row.deviceId,
          deviceNo: row.deviceNo // 根据接口需要添加必要字段
        };

        await unbindStore(deviceData, row.storeId);

        this.$message.success('店铺解绑成功');
        this.refreshList(); // 刷新列表
      } catch (error) {
        this.$message.error(error.response?.data?.message || '解绑失败');
      }
    },
    handleUnbindBoothConfirm(row) {
      this.$confirm('确认解除当前卡座和设备的绑定关系吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.executeUnbind(row);
      }).catch(() => {});
    },

    // 执行解绑操作
    async executeUnbind(row) {
      try {

        await unbindBooth(
          { deviceId: row.deviceId },
          row.boothId
        );

        this.$message.success('解绑成功');
        this.refreshList(); // 刷新列表数据
      } catch (error) {
        this.$message.error(error.response?.data?.message || '解绑失败');
      }
    },

    // 刷新数据列表方法
    refreshList() {
      // 调用你的数据获取方法
      this.getList();
    },
    handleChangeStore(row){
      this.selectDevice = row
      this.showChangeStore=true
    },
    handleChangeStoreSuccess() {
      this.showEditDialog = false
      this.getList()
    },
    /** 当排序按钮被点击时触发 **/
    onSortChange(column) {
      if (column.order == null) {
        this.queryParams.orderByColumn = defaultSort.prop;
        this.queryParams.isAsc = defaultSort.order;
      } else {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
      }
      this.getList();
    },
    // 查看按钮操作
    handleSee(row) {
      this.$router.push({path: `/view/device/${row.deviceId}`})
    },
    /** 查询设备列表 */
    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,
        deviceNo: null,
        storeId: null,
        userId: null,
        modelId: null,
        deviceName: null,
        mac: null,
        mac2: null,
        totalElectriQuantity: null,
        onlineStatus: null,
        status: null,
        realTimePower: null,
        electricity: null,
        voltage: null,
        createTime: null,
        remark: null,
        set: null,
        wifi: null,
        deleted: null,
        lastPullTime: null,
        initReading: null,
        powerStatus: null,
        expireTime: null,
        customPicture: null,
        remainTime: null,
        surplusEle: null,
        lastOnlineTime: null,
        onlineStatus1: null,
        onlineStatus2: null,
        version: null,
        expireEle: null,
        lastInitReading: null,
        vxs: null,
        imsi: null,
        wxs: null,
        lastRecoverTime: 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.selectDeviceId = null;
      this.showEditDialog = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.selectDeviceId = row.deviceId || this.ids;
      this.showEditDialog = true;
    },
    /** 提交按钮 */
    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 logicDelDevice(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
