<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="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入所属店铺"
          clearable
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分区" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入所属分区"
          clearable
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卡座名称" prop="boothName">
        <el-input
          v-model="queryParams.boothName"
          placeholder="请输入卡座名称"
          clearable
          @input="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-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:booth: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:booth:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="isSysAdmin()"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-has-permi="['bst:booth:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="boothList" @selection-change="handleSelectionChange" :default-sort="defaultSort"  @sort-change="onSortChange">
      <el-table-column type="selection" width="25" align="center" />
      <el-table-column label="ID" align="center" prop="boothId" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.boothId }}</span>
          <booth-sn
            :sn="scope.row.boothId"
            style="margin-left: 8px; vertical-align: middle"
          >
            <el-button
              type="text"
              icon="el-icon-picture"
              size="mini"
              class="qrcode-btn"
            >卡座二维码</el-button>
          </booth-sn>
        </template>
      </el-table-column>
      <el-table-column label="卡座名称" align="center" prop="boothName">
        <template slot-scope="{row}">
            <i class="el-icon-takeaway-box"/>
            <booth-link
              :id="row.boothId"
              :text="row.boothName"
              size="mini"
            />
        </template>
      </el-table-column>
      <el-table-column label="所属" align="center" prop="partName" >
        <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"
            />
            {{ row.parentName ? '/' + row.parentName : '' }}/{{ row.partName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="卡座图片" align="center" prop="picture" >
        <image-preview slot-scope="d" :src="d.row.picture" :width="50" :height="50"/>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="orderNum" width="60"/>
      <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="handleSee(scope.row)"
            v-has-permi="['bst:booth:query']"
          >详情</el-button>
          <el-button
            size="mini"
            icon="el-icon-circle-plus"
            type="text"
            @click="handleBindDevice(scope.row)"
            :loading="bindLoading">
            增加设备
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-has-permi="['bst:booth:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-has-permi="['bst:booth: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"
    />

    <device-select-dialog
      :visible.sync="deviceDialogVisible"
      :loading="deviceLoading"
      :device-list="deviceList"
      @confirm="handleDeviceConfirm"
    />

    <!-- 添加或修改卡座对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <form-col label="选择分区" prop="partId">
            <el-cascader
              v-model="form.partId"
              :options="parentOptions"
              :props="cascaderProps"
              clearable
              :show-all-levels="false"
              :display-render="{
              render: ({ labels }) => labels.join('/')
                    }"
            >
              <template slot-scope="{ node, data }">
                <span v-if="node.level === 1">{{ data.partName }}（{{ data.storeName }}）</span>
                <span v-else>{{ data.partName }}</span>
              </template>
            </el-cascader>
          </form-col>
          <form-col :span="span"  label="卡座名称" prop="boothName">
            <el-input v-model="form.boothName" placeholder="请输入卡座名称" />
          </form-col>
          <form-col :span="span"  label="卡座图片" prop="picture">
            <image-upload v-model="form.picture" type="textarea" placeholder="请输入内容" />
          </form-col>
          <form-col :span="span"  label="显示顺序" prop="orderNum" >
            <el-input-number v-model="form.orderNum" controls-position="right" :min="1"></el-input-number>
          </form-col>
        </el-row>
      </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>
  </div>
</template>

<script>
import {listBooth, getBooth, delBooth, addBooth, updateBooth, bindBooth} from "@/api/bst/booth";
import { $showColumns } from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import {listStore} from "@/api/bst/store";
import {listPart} from "@/api/bst/part";
import DeviceSn from "@/views/bst/device/components/DeviceSn.vue";
import BoothSn from "@/views/bst/booth/components/BoothSn.vue";
import StoreLink from "@/views/bst/store/StoreLink.vue";
import BoothLink from "@/views/bst/booth/components/BoothLink.vue";
import {listDevice} from "@/api/bst/device";
import DeviceSelectDialog from "@/views/bst/device/components/DeviceSelectDialog.vue";
import {isSysAdmin} from "@/utils/permission";

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

export default {
  name: "Booth",
  mixins: [$showColumns],
  components: {DeviceSelectDialog, BoothLink, StoreLink, BoothSn, DeviceSn, FormCol},
  data() {
    return {
      currentBooth: null,    // 当前操作的卡座
      selectedDevice: null,  // 选中的设备
      bindLoading: false,
      parentOptions: [], // 父区域树数据
      deviceDialogVisible: false,
      deviceList: [],
      deviceLoading: false,
      cascaderProps: {
        value: 'partId',
        children: 'children',
        label: 'fullName',
        checkStrictly: true,// 可单选任意级
        emitPath:false
      },
      span: 24,
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 店铺选项
      storeOptions: [],
      // 分区选项
      partOptions: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 卡座表格数据
      boothList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        partId: null,
        boothName: null,
        picture: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        partId: [
          { required: true, message: "分区不能为空", trigger: "blur" }
        ],
        boothNo: [
          { required: true, message: "卡座编号不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getStoreList().then(() => {
      this.getPartList();
      this.getList();
    });
  },
  methods: {
    isSysAdmin,
    handleDeviceConfirm(device) {
      this.selectedDevice = device
      this.bindDeviceToBooth();
    },
    async bindDeviceToBooth() {
      if (!this.selectedDevice || !this.currentBooth) return;

      try {
        this.bindLoading = true;
        await bindBooth(this.selectedDevice,this.currentBooth.boothId);
        this.$modal.msgSuccess("设备绑定成功");
        this.deviceDialogVisible = false;
        this.getList(); // 刷新列表
      } catch (error) {
        this.$modal.msgError("设备绑定失败");
      } finally {
        this.bindLoading = false;
      }
    },

    async handleBindDevice(row) {
      try {
        this.currentBooth = row; // 保存当前卡座
        this.deviceLoading = true;
        const res = await listDevice({ userId: row.mchId, isUnbound: true });
        this.deviceList = res.rows;
        this.deviceDialogVisible = true;
      } catch (error) {
        this.$modal.msgError("加载设备失败");
      } finally {
        this.deviceLoading = false;
      }
    },
    handleSee(row) {
      this.$router.push({path: `/view/booth/${row.boothId}`})
    },

    /** 查询店铺列表 */
    getStoreList() {
      this.loading = true;
      return listStore().then(response => { // 添加 return
        this.storeOptions = (response.rows || []).map(item => ({
          value: item.storeId,
          label: item.storeName
        }));
        this.loading = false;
        return response; // 返回数据用于链式调用
      });
    },
    /** 当排序按钮被点击时触发 **/
    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();
    },
    /** 查询卡座列表 */
    getList() {
      this.loading = true;
      listBooth(this.queryParams).then(response => {
        this.boothList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        boothId: null,
        partId: null,
        boothName: null,
        picture: null,
        createTime: 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.boothId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加卡座";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const boothId = row.boothId || this.ids
      getBooth(boothId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改卡座";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.boothId != null) {
            updateBooth(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBooth(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const boothIds = row.boothId || this.ids;
      this.$modal.confirm('是否确认删除卡座编号为"' + boothIds + '"的数据项？').then(function() {
        return delBooth(boothIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/booth/export', {
        ...this.queryParams
      }, `booth_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
