<template>
  <div class="app-container">
    <el-row :gutter="20" class="retail-container">
      <!-- 左侧会员信息和购物车 -->
      <el-col :span="8" class="left-panel">
        <el-card class="member-card">
          <!-- 会员搜索 -->
          <div class="member-search">
            <el-input
              v-model="queryParams.phoneNumber"
              placeholder="请输入会员手机号"
              clearable
              prefix-icon="el-icon-user"
              @clear="clearAppUserInfo"
              maxlength="11"
              @keyup.enter.native="searchUser"
            >
              <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
            </el-input>
          </div>

          <!-- 会员信息展示 -->
          <div class="member-info" v-if="appUserInfo">
            <div class="member-header">
              <div class="avatar">
                <i class="el-icon-user-solid"></i>
              </div>
              <div class="basic-info">
                <div class="name">{{appUserInfo.realName || '未设置姓名'}}</div>
                <div class="level">账户余额：￥{{formatMoney(appUserInfo.rechargeBalance + appUserInfo.giveBalance + appUserInfo.welfareBalance)}}</div>
              </div>
            </div>
            <div class="balance-info">
              <div class="balance-item">
                <div class="label">现金余额</div>
                <div class="value">￥{{formatMoney(appUserInfo.rechargeBalance)}}</div>
              </div>
              <div class="balance-item">
                <div class="label">赠送余额</div>
                <div class="value">￥{{formatMoney(appUserInfo.giveBalance)}}</div>
              </div>
              <div class="balance-item">
                <div class="label">福利余额</div>
                <div class="value">￥{{formatMoney(appUserInfo.welfareBalance)}}</div>
              </div>
            </div>
          </div>


          <!-- 购物车列表 -->
          <div class="cart-container">
            <div class="cart-header">
              <div class="title">
                <i class="el-icon-shopping-cart-2"></i>
                <span>购物车</span>
                <span class="count" v-if="addGoodsList.length">({{addGoodsList.length}})</span>
              </div>
              <el-button type="text" @click="clearCart" v-if="addGoodsList.length">
                <i class="el-icon-delete"></i>
                清空
              </el-button>
            </div>

            <div class="cart-list" :class="{'empty': !addGoodsList.length}">
              <div v-if="addGoodsList.length">
                  <div class="cart-item" v-for="(item, i) in addGoodsList" :key="i">
                    <el-button type="text" class="delete-btn" @click="deleteGoods(item)">
                      <i class="el-icon-delete"></i>
                    </el-button>
                    <div class="item-header">
                      <div class="goods-info">
                        <div class="goods-name">{{item.goodsName}}</div>
                        <div class="goods-spec">{{formatSpec(item.specValLists)}}</div>
                      </div>
                      <div class="price" style="margin-top: 5px;">
                        <div>
                          <span style="font-size: 10px;">￥</span>
                          <span>{{formatMoney(item.salePrice)}}</span>
                        </div>
                        <el-input-number
                          v-model="getPurchaseCount(item).count"
                          :min="1"
                          :max="item.stock"
                          size="mini"
                          style="width: 100px;"
                          @change="countPrice"
                        ></el-input-number>
                        <!-- <span class="subtotal">￥{{formatMoney(item.salePrice * getPurchaseCount(item).count)}}</span> -->
                      </div>
                    </div>

                  </div>
              </div>
              <!-- <el-table
                v-if="addGoodsList.length"
                :data="addGoodsList"
                size="midium"
                :header-cell-style="{background:'#f5f7fa'}"
                :cell-style="{padding: '5px 0'}"
              >
                <el-table-column label="商品信息" min-width="200">
                  <template slot-scope="scope">
                    <div class="goods-info">
                      <div class="goods-name">{{scope.row.goodsName}}</div>
                      <div class="goods-spec">{{formatSpec(scope.row.specValLists)}}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="数量" width="180" align="center">
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="getPurchaseCount(scope.row).count"
                      :min="1"
                      :max="scope.row.stock"
                      size="mini"
                      @change="countPrice"
                    ></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="小计" width="100" align="right">
                  <template slot-scope="scope">
                    <span class="subtotal">￥{{formatMoney(scope.row.salePrice * getPurchaseCount(scope.row).count)}}</span>
                  </template>
                </el-table-column>
                <el-table-column width="80" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" class="delete-btn" @click="deleteGoods(scope.row)">
                      <i class="el-icon-delete"></i>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table> -->
              <div v-else class="empty-cart">
                <img
                    :src="noGoodsImage"
                    :onerror="defaultImageError"
                    alt="商品图片"
                  >
                <p>购物车是空的</p>
              </div>
            </div>

            <!-- 结算区域 -->
            <div class="settlement-panel">
              <div class="amount-info">
                <div class="total-row">
                  <span>商品数量：</span>
                  <span class="number">{{calculateTotalCount}}件</span>
                </div>
                <div class="total-row">
                  <span>商品总额：</span>
                  <span class="amount">￥{{formatMoney(calculateTotalPrice)}}</span>
                </div>
              </div>
              <el-button
                type="primary"
                class="settle-btn"
                @click="submitCash"
                :disabled="!appUserInfo || !addGoodsList.length"
              >
                <i class="el-icon-wallet"></i>
                收银结算
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧商品选择区域 -->
      <el-col :span="16" class="right-panel">
        <el-card>
          <!-- 搜索栏 -->
          <div class="search-bar">
            <el-radio-group v-model="goodsType"  @change="getCategoryList">
              <el-radio-button label="0">普通商品</el-radio-button>
              <el-radio-button label="2">生活服务</el-radio-button>
              <el-radio-button label="3">汽车美容</el-radio-button>
            </el-radio-group>
            <el-input
              v-model="searchQuery"
              placeholder="请输入商品条码/名称"
              clearable
              @clear="handleSearchClear"
              @keyup.enter.native="handleSearch"
              style="flex: 1; margin-left: 10px;"
            >

              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
            
          </div>

          <!-- 商品分类标签页 -->
          <el-tabs
            v-model="activeCategory"
            @tab-click="handleCategoryChange"
            class="goods-tabs"
          >
            <el-tab-pane
              v-for="category in categoryList"
              :key="category.id"
              :label="category.categoryName"
              :name="category.id.toString()"
            >
              <!-- 商品列表 -->
              <div class="goods-container">
                <div class="goods-grid">
                  <el-card
                    v-for="goods in goodsList"
                    :key="goods.goodsCode"
                    shadow="hover"
                    class="goods-item"
                    :class="{'out-of-stock': goods.stock <= 0}"
                    @click.native="goods.stock > 0 && selectSpec(goods)"
                  >
                    <img
                      :src="goods.goodsImg || defaultImage"
                      :onerror="defaultImageError"
                      class="goods-img"
                      alt="商品图片"
                    >
                    <div class="goods-info">
                      <div class="goods-name" :title="goods.goodsName">{{goods.goodsName}}</div>
                      <div class="goods-price">￥{{formatMoney(goods.salePrice)}}</div>
                      <div class="goods-stock" :class="{'low-stock': goods.stock <= 5 && goods.stock > 0}">
                        库存: {{goods.stock}}
                      </div>
                    </div>
                    <div class="stock-overlay" v-if="goods.stock <= 0">
                      <i class="el-icon-warning"></i>
                      <span>无库存</span>
                    </div>
                  </el-card>
                </div>

                <!-- 分页器 -->
                <div class="pagination-container">
                  <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryParamsGoods.pageNum"
                    :page-sizes="[20, 40, 60, 80]"
                    :page-size="queryParamsGoods.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    background
                  >
                  </el-pagination>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 选择规格弹窗 -->
    <el-dialog title="选择规格" :visible.sync="skuOpen" width="500px" append-to-body>
      <el-table :data="goodsSkuList" v-loading="skuLoading">
        <el-table-column label="规格" prop="specVoList">
          <template slot-scope="scope">
            {{formatSpec(scope.row.specValLists)}}
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="salePrice" width="100" align="right">
          <template slot-scope="scope">
            ￥{{formatMoney(scope.row.salePrice)}}
          </template>
        </el-table-column>
        <el-table-column label="库存" prop="stock" width="80" align="center"/>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="addGoods(scope.row)" :disabled="scope.row.stock <= 0">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 收银结算弹窗 -->
    <el-dialog
      title="收银结算"
      :visible.sync="payOpen"
      width="600px"
      :close-on-click-modal="false"
      custom-class="settlement-dialog"
      append-to-body
    >
      <!-- 订单信息概览 -->
      <div class="order-summary">
        <div class="summary-row">
          <div class="summary-item">
            <div class="label">商品总数</div>
            <div class="value highlight-blue">{{calculateTotalCount}}件</div>
          </div>
          <div class="summary-item">
            <div class="label">商品总额</div>
            <div class="value highlight-red">￥{{formatMoney(calculateTotalPrice)}}</div>
          </div>
          <div class="summary-item">
            <div class="label">会员余额</div>
            <div class="value highlight-green">￥{{formatMoney(appUserInfo ? appUserInfo.rechargeBalance + appUserInfo.giveBalance + appUserInfo.welfareBalance : 0)}}</div>
          </div>
        </div>
      </div>

      <el-form ref="payFrom" :model="payFrom" label-width="100px" class="settlement-form">
        <!-- 优惠信息 -->
        <div class="section-card">
          <div class="section-title">
            <i class="el-icon-ticket"></i>
            优惠信息
          </div>
          <el-form-item label="抵扣金额" prop="deductAmount">
            <el-input-number
              v-model="payFrom.deductAmount"
              :min="0"
              :max="calculateTotalPrice"
              :precision="2"
              :step="1"
              :controls="true"
              style="width: 200px"
              placeholder="请输入抵扣金额"
            ></el-input-number>
            <span class="form-tip">最大可抵扣: ￥{{formatMoney(calculateTotalPrice)}}</span>
          </el-form-item>
          <div class="amount-display">
            <span>折后应付：</span>
            <span class="highlight-amount">￥{{formatMoney(calculatePayMoney)}}</span>
          </div>
        </div>

        <!-- 支付方式 -->
        <div class="section-card">
          <div class="section-title">
            <i class="el-icon-wallet"></i>
            支付方式
          </div>
          <div class="payment-methods">
            <el-radio-group v-model="payFrom.payType" @change="changePayType" size="large">
              <el-radio-button label="3">
                <i class="el-icon-money"></i>
                余额支付
              </el-radio-button>
              <el-radio-button label="2">
                <i class="el-icon-coin"></i>
                现金支付
              </el-radio-button>
              <el-radio-button label="0">
                <i class="el-icon-chat-dot-square"></i>
                微信/支付宝
              </el-radio-button>
            </el-radio-group>
          </div>

          <!-- 根据支付方式显示不同的输入项 -->
          <div class="payment-details" v-if="payFrom.payType">
            <!-- 余额支付 -->
            <template v-if="payFrom.payType === '3'">
              <div class="balance-info" v-if="appUserInfo">
                <div class="info-item">
                  <span class="label">会员姓名：</span>
                  <span class="value">{{appUserInfo.realName || '- -'}}</span>
                </div>
                <div class="info-item">
                  <span class="label">可用余额：</span>
                  <span class="value highlight-green">￥{{formatMoney(appUserInfo.rechargeBalance + appUserInfo.giveBalance + appUserInfo.welfareBalance)}}</span>
                </div>
                <div class="info-item" v-if="calculatePayMoney > (appUserInfo.rechargeBalance + appUserInfo.giveBalance + appUserInfo.welfareBalance)">
                  <span class="value highlight-red">余额不足，需额外支付：￥{{formatMoney(calculatePayMoney - (appUserInfo.rechargeBalance + appUserInfo.giveBalance + appUserInfo.welfareBalance))}}</span>
                </div>
                <div class="info-item">
                  <span class="label">额外支付方式：</span>
                  <el-radio-group v-model="otherPayType">
                    <el-radio :label="2">现金</el-radio>
                    <el-radio :label="0">微信/支付宝</el-radio>
                  </el-radio-group>
                </div>
                <div class="info-item">
                  <div class="value" v-if="otherPayType == 0 && getOtherPayPrice() > 0">
                    <el-input ref="authOtherCode" v-model="payFrom.authCode" placeholder="请扫描客户付款码" prefix-icon="el-icon-camera" clearable autofocus style="width: 300px"> </el-input>
                  </div>
                </div>
              </div>
            </template>

            <!-- 现金支付 -->
            <template v-if="payFrom.payType === '2'">
              <el-form-item label="收款金额" prop="thisPayMoney" class="cash-payment">
                <el-input-number
                  v-model="payFrom.thisPayMoney"
                  :min="calculatePayMoney"
                  :precision="2"
                  :step="10"
                  :controls="true"
                  style="width: 200px"
                  placeholder="请输入收款金额"
                ></el-input-number>
                <div class="change-amount" v-if="payFrom.thisPayMoney >= calculatePayMoney">
                  <span class="label">找零：</span>
                  <span class="value highlight-blue">￥{{formatMoney(payFrom.thisPayMoney - calculatePayMoney)}}</span>
                </div>
              </el-form-item>
            </template>

            <!-- 微信支付 -->
            <template v-if="payFrom.payType === '0'">
              <el-form-item label="付款码" prop="wxBarcode">
                <el-input
                  v-model="payFrom.wxBarcode"
                  style="width: 300px"
                  placeholder="请扫描付款码"
                  prefix-icon="el-icon-scan"
                  autofocus
                ></el-input>
              </el-form-item>
            </template>

          </div>
        </div>
      </el-form>

      <!-- 结算按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="payOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitSettlement" :loading="submitting">
          确认结算
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getGoodsListToGoodsRetail, getGoodsSkuListToGoodsRetail, purchaseListSku } from '@/api/core/sku'
import { listCategory } from '@/api/core/category'
import { findUserByPhoneNumber } from '@/api/app/user'
import { listBrand } from '@/api/core/brand'
import { insertRetailOrderGoods, getGoods, orderGoodsPay } from '@/api/order/goods'
import { getLodop } from "@/utils/lodopUtils";
import { printGoods } from '@/api/order/clothItem'


export default {
  name: "goodsRetail",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 客户信息
      appUserInfo: null,
      // 商品列表等待
      goodsLoading: false,
      // 物料列表等待
      skuLoading: false,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层 物料页面弹框
      skuOpen: false,
      // 收银支付页面弹框
      payOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 查询分类+品牌的查询参数
      queryParams2: {
        pageNum: 1,
        pageSize: 9999,
        status: '0',
        goodsType: null,
      },
      // 查询参数
      queryParamsGoods: {
        pageNum: 1,
        pageSize: 20,
        goodsCategoryId: null,
        keywords: ''
      },
      // 支付表单参数
      payFrom: {
      },
      // 表单校验
      rules: {
      },
      goodsType: null,
      // 分类id
      goodsCategoryId: null,
      // 可选商品集合
      goodsList: null,
      // 可选商品物料集合
      goodsSkuList: null,
      // 已选商品集合
      addGoodsList: [],
      // 左侧分类集合
      categoryList: null,
      // 品牌list
      brandList: {},
      // 自定义一个计算数量的临时对象集合
      purchaseCountVOList: [],
      // 总金额
      totalPrice: 0,
      // 总件数
      totalCount: 0,
      // 提交的参数对象
      submitGoodsOrderDTO: {},
      // 需要支付的金额
      payMoney: null,

      LODOP: null,
      number: 1,
      pointerList: [],
      userInfoVO: null,
      activeCategory: '', // 当前选中的分类
      noGoodsImage: require("@/assets/images/nogoods.png"), // 添加默认图片
      defaultImage: require("@/assets/images/profile.jpg"), // 添加默认图片
      defaultImageError: 'this.src="' + require("@/assets/images/profile.jpg") + '"' , // 图片加载失败时的处理
      searchQuery: '', // 搜索关键词
      searchType: 'name', // 搜索类型
      submitting: false,
      otherPayType: 2
    };
  },
  created() {
    this.handleUser();
    this.goodsType = this.getUrlParam('goodsType');
    this.getCategoryList().then(() => {
      if (this.categoryList && this.categoryList.length > 0) {
        this.activeCategory = this.categoryList[0].id.toString();
        this.goodsCategoryId = this.categoryList[0].id;
        // this.getGoodsList();
      }
    });
    this.getBrandList();
  },
  mounted() {
    this.number = 1;
    const printerTime = setInterval(() => {
      this.LODOP = getLodop();
      this.number++
      if (this.number == 25) {
        clearInterval(printerTime);
      }
      if (this.LODOP) {
        clearInterval(printerTime);
      }
    }, 200)

    this.pointerList = JSON.parse(this.$cache.local.get("printerSeting"));
  },
  computed: {
    calculateTotalCount() {
      this.totalCount = 0;
      this.addGoodsList.forEach(vo => {
        let number = this.purchaseCountVOList.find(item => item.goodsSkuStoreId == vo.goodsSkuStoreId).count;
        this.totalCount = this.totalCount + number;
      });
      return this.totalCount;
    },
    calculateTotalPrice() {
      this.totalPrice = 0;
      this.addGoodsList.forEach(vo => {
        let number = this.purchaseCountVOList.find(item => item.goodsSkuStoreId == vo.goodsSkuStoreId).count;
        this.totalPrice = this.totalPrice + (number * vo.salePrice);
      });
      return this.totalPrice;
    },
    calculatePayMoney() {
      this.payMoney = this.payFrom.deductAmount ? this.totalPrice - this.payFrom.deductAmount : this.totalPrice;
      return this.payMoney;
    }
  },

  methods: {
    handleUser() {
      this.userInfoVO = this.getUserInfo();
    },
    // 切换支付方式
    changePayType() {
      delete this.payFrom.thisPayMoney
    },
    // 收银
    submitCash() {
      if (this.appUserInfo == null) {
        this.$message.error("请选择客户");
        return;
      }
      if (this.calculateTotalCount == 0) {
        this.$message.error("请选择商品");
      }
      this.payOpen = true;
    },
    // 清空用户数据
    clearAppUserInfo() {
      this.appUserInfo = null;
    },
    //搜索用户
    searchUser() {
      if (this.queryParams.phoneNumber == null || this.queryParams.phoneNumber == '') {
        return;
      }
      findUserByPhoneNumber(this.queryParams).then(res => {
        this.appUserInfo = res.data;
      })
    },
    // 获取商品分类列表
    getCategoryList() {
      return listCategory({ ...this.queryParams2, ...{ goodsType: this.goodsType } }).then(response2 => {
        this.categoryList = response2.rows;
        if (response2.rows.length > 0) {
          this.activeCategory = response2.rows[0].id.toString();
          this.goodsCategoryId = response2.rows[0].id;
          this.getGoodsList();
        }
      });
    },
    // 获取品牌
    getBrandList() {
      listBrand({ ...this.queryParams2, ...{ goodsType: this.goodsType } }).then(response1 => {
        this.brandList = response1.rows;
      });
    },
    // 已选择列表中，删除商品按钮
    deleteGoods(row) {
      this.addGoodsList = this.addGoodsList.filter((item) => {
        return item.goodsSkuStoreId !== row.goodsSkuStoreId;
      })
      this.purchaseCountVOList = this.purchaseCountVOList.filter((item) => {
        return item.goodsSkuStoreId !== row.goodsSkuStoreId;
      })
    },
    // 未选列表中，添加按钮
    addGoods(row) {
      if (row.stock <= 0) {
        this.$message.warning("该商品已售罄");
        return;
      }
      if (this.addGoodsList.length > 0) {
        let match = this.addGoodsList.findIndex(item => item.goodsSkuStoreId == row.goodsSkuStoreId)
        if (match !== -1) {
          let purchaseVo = this.purchaseCountVOList.find(item => item.goodsSkuStoreId == row.goodsSkuStoreId);
          if (purchaseVo.count >= row.stock) {
            this.$message.warning("库存不足");
            return;
          }
          purchaseVo.count++;
          this.skuOpen = false;
          this.$forceUpdate();
          return;
        }
      }

      this.addGoodsList.push(row);
      this.purchaseCountVOList.push({
        'goodsSkuStoreId': row.goodsSkuStoreId,
        'goodsCategoryId': this.goodsCategoryId,
        'goodsCategoryName': this.categoryList.find(item => item.id == this.goodsCategoryId).categoryName,
        'skuName': this.formatSpec(row.specValLists),
        'count': 1
      })
      this.skuOpen = false;
      this.$forceUpdate();
    },
    // 操作数量增减时，计算价格
    countPrice(e) {
      console.log(e)
      this.totalPrice = 0;
      this.totalCount = 0;
      this.addGoodsList.forEach(vo => {
        let number = !e ? 1 : this.purchaseCountVOList.find(item => item.goodsSkuStoreId == vo.goodsSkuStoreId).count;
        this.totalPrice = this.totalPrice + (number * vo.salePrice);
        this.totalCount = this.totalCount + number;
      })
    },
    // 左侧商品分类列表，单击事件
    handleNodeClick(data) {
      this.goodsCategoryId = data.id;
      this.getGoodsList();
    },
    // 获取商品列表
    getGoodsList() {
      this.goodsLoading = true;
      if (this.goodsCategoryId == null) {
        this.goodsList = [];
        this.goodsLoading = false;
        return;
      }
      this.queryParamsGoods.goodsCategoryId = this.goodsCategoryId;

      getGoodsListToGoodsRetail(this.queryParamsGoods).then(response => {
            this.goodsList = response.rows;
        this.total = response.total; // 假设后端返回total字段
        this.goodsLoading = false;
      }).catch(() => {
          this.goodsLoading = false;
        });
    },
    // 选择商品规格
    selectSpec(row) {
      if (row.stock <= 0) {
        this.$message.warning("该商品已售罄");
        return;
      }

      this.skuLoading = true;
      getGoodsSkuListToGoodsRetail(row.id).then(response => {
        this.goodsSkuList = response.data;
        this.skuLoading = false;
        this.skuOpen = true;
      });
    },
    getOtherPayPrice() {
      return this.payMoney - this.appUserInfo.rechargeBalance + this.appUserInfo.giveBalance + this.appUserInfo.welfareBalance
    },
    // 结算
    submitSettlement() {
      this.$confirm('是否确认结算？').then(() => {
        if (this.totalCount == 0) {
          this.$message.error("请选择商品");
          return;
        }
        if (this.payFrom.payType == null || this.payFrom.payType == '') {
          this.$message.error("请选择支付方式");
          return;
        }
        if (this.payFrom.deductAmount != null || this.payFrom.deductAmount != '') {
          if (this.payFrom.deductAmount > this.payMoney) {
            this.$message.error("抵扣金额不能大于支付金额");
            return;
          }
        }
        if (this.payFrom.payType == '3') {
          if (this.appUserInfo.rechargeBalance + this.appUserInfo.giveBalance + this.appUserInfo.welfareBalance == 0) {
            this.$message.error("用户余额不足");
            return;
          }
        }
        if (this.payFrom.payType == '2') {
          if (this.payFrom.thisPayMoney < this.payMoney) {
            this.$message.error("现金金额不够支付");
            return;
          }
        }
        this.submitGoodsOrderDTO = {};
        // 设置订单基础信息
        this.submitGoodsOrderDTO.totalPrice = this.totalPrice;
        this.submitGoodsOrderDTO.goodsType = this.goodsType;
        this.submitGoodsOrderDTO.deductAmount = this.payFrom.deductAmount;
        this.submitGoodsOrderDTO.appUserId = this.appUserInfo.id;
        this.submitGoodsOrderDTO.payAmount = this.payMoney;
        this.submitGoodsOrderDTO.payType = this.payFrom.payType;
        // 设置订单商品物料信息
        this.submitGoodsOrderDTO.retailGoodsVOList = [];
        this.addGoodsList.forEach(vo => {
          let purchaseVO = this.purchaseCountVOList.find(item => item.goodsSkuStoreId == vo.goodsSkuStoreId)
          let purchaseGoodsVO = {};
          purchaseGoodsVO.skuId = vo.id;
          purchaseGoodsVO.goodsId = vo.goodsId;
          purchaseGoodsVO.goodsName = vo.goodsName;
          purchaseGoodsVO.goodsImg = vo.goodsImg;
          purchaseGoodsVO.goodsCategoryId = purchaseVO.goodsCategoryId;
          purchaseGoodsVO.goodsCategoryName = purchaseVO.goodsCategoryName;
          purchaseGoodsVO.salePrice = vo.salePrice;
          purchaseGoodsVO.buyNum = purchaseVO.count;
          purchaseGoodsVO.skuName = purchaseVO.skuName;

          this.submitGoodsOrderDTO.retailGoodsVOList.push(purchaseGoodsVO);
        });

        insertRetailOrderGoods(this.submitGoodsOrderDTO).then(response => {
          let params = {
            appUserId: this.appUserInfo.id,
            orderNo: response.data.orderNo,
            authCode: this.payFrom.authCode,
            payType: this.payFrom.payType,
            payAmount: this.payMoney,
          }
          if (this.payFrom.payType == '3') {
            if (this.getOtherPayPrice() > 0) {
              params.memberPayAmount = this.appUserInfo.rechargeBalance + this.appUserInfo.giveBalance + this.appUserInfo.welfareBalance
              params.payType = 8
              params.otherPayType = this.otherPayType
            }
          }
          orderGoodsPay(params).then(res => {
            this.$modal.msgSuccess("订单支付成功");
            this.addGoodsList = [];
            this.purchaseCountVOList = [];
            this.submitGoodsOrderDTO = {};
            this.searchUser();
            // this.appUserInfo= {}
            this.payOpen = false;
            this.btn_lodop(response.data.orderId);
          })
         
        });
      }).catch((e) => {
        console.log(e)
        this.payOpen = false; });
    },
    btn_lodop(id) {
      if (!this.LODOP) {
        this.$modal.msgError("请安装打印机软件");
        return
      }

      let p_name = '';

      this.pointerList.forEach(pointer => {
        if (pointer.printType == 0) {
          p_name = pointer.printName
        }
      })
      printGoods(id).then((res) => {
        if (this.userInfoVO.userType == '02') {
          const obj = {
            name: this.userInfoVO.storeName,
            contactPhone: this.userInfoVO.phonenumber,
            user: this.userInfoVO.nickName,
          }
          res.data.sysOrg = obj
        }
        res.data.newTime = this.formatDates(new Date(), 1)
        this.goodsPrinter(this.LODOP, res.data, p_name)
      });
    },
    // 格式化规格信息
    formatSpec(specList) {
      if (!specList || !specList.length) return '默认规格';
      return specList.join(' ');
    },

    // 格式化金额
    formatMoney(value) {
      if (!value) return '0.00';
      return Number(value).toFixed(2);
    },

    // 切换商品分类
    handleCategoryChange(tab) {
      this.goodsCategoryId = tab.name;
      this.queryParamsGoods.pageNum = 1; // 切换分类时重置到第一页
      this.getGoodsList();
    },

    // 清空购物车
    clearCart() {
      this.$confirm('确认清空购物车？', '提示', {
        type: 'warning'
      }).then(() => {
        this.addGoodsList = [];
        this.purchaseCountVOList = [];
      });
    },

    // 获取商品购买数量
    getPurchaseCount(goods) {
      let sku = this.purchaseCountVOList.find(item => item.goodsSkuStoreId === goods.goodsSkuStoreId)
      if (!sku.count) {
        sku.count = 1;
      }
      return sku
    },

    // 处理搜索
    handleSearch() {
      this.queryParamsGoods.keywords = this.searchQuery;
      this.queryParamsGoods.searchType = this.searchType;
      this.queryParamsGoods.pageNum = 1; // 重置到第一页
      this.getGoodsList();
    },

    // 清除搜索
    handleSearchClear() {
      this.searchQuery = '';
      this.queryParamsGoods.keywords = '';
      this.getGoodsList();
    },

    // 处理分页大小改变
    handleSizeChange(val) {
      this.queryParamsGoods.pageSize = val;
      this.getGoodsList();
    },

    // 处理页码改变
    handleCurrentChange(val) {
      this.queryParamsGoods.pageNum = val;
      this.getGoodsList();
    },
  }
};
</script>
<style lang="scss" scoped>
.head-container-two {
    height: calc(100vh - 250px);
    display: block;
    overflow-y: scroll;
}
.head-column1 {
    height: calc(50vh - 130px);
    display: block;
    overflow-y: scroll;
}
.head-goods {
    height: auto;
    display: block;
    overflow-y: scroll;
}
.box-shadow {
    font-size: 18px;
}
.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); // 减小商品卡片的最小宽度
  gap: 10px; // 减小间距
  padding: 10px;

  .goods-item {
    position: relative;
    cursor: pointer;
    transition: all 0.3s;

    &.out-of-stock {
      cursor: not-allowed;
      opacity: 0.7;

      &:hover {
        transform: none;
        box-shadow: none;
      }
    }

    .el-card__body {
      padding: 8px; // 减小内边距
    }

    .goods-img {
      width: 100%;
      height: 120px; // 减小图片高度
      object-fit: cover;
      border-radius: 4px;
      background-color: #f5f7fa;
    }

    .goods-info {
      padding: 5px 0;

      .goods-name {
        font-size: 12px;
        margin-bottom: 3px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #303133;
      }

      .goods-price {
        color: #f56c6c;
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 3px;
      }

      .goods-stock {
        font-size: 12px;
        color: #67c23a;

        &.low-stock {
          color: #e6a23c;
        }
      }
    }

    .stock-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 14px;

      i {
        font-size: 24px;
        margin-bottom: 5px;
      }
    }
  }
}

// 优化右侧面板的滚动
.right-panel {
  .el-card {
    height: 100%;

    .el-card__body {
      height: 100%;
      padding: 10px;

      .el-tabs {
        height: 100%;
        display: flex;
        flex-direction: column;

        .el-tabs__content {
          flex: 1;
          overflow-y: auto;

          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
  }
}

// 添加滚动条样式
.right-panel {
  ::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  ::-webkit-scrollbar-thumb {
    background: #dcdfe6;
    border-radius: 3px;
  }

  ::-webkit-scrollbar-track {
    background: #f5f7fa;
  }
}

// 优化分类标签样式
.el-tabs__item {
  height: 30px;
  line-height: 30px;
  font-size: 13px;
}

.left-panel {
  height: 100%;

  .member-card {
    height: 100%;
    display: flex;
    flex-direction: column;

    .member-search {
      padding: 15px;
      border-bottom: 1px solid #ebeef5;

      .el-input {
        .el-input__inner {
          border-radius: 20px 0 0 20px;
        }
        .el-input-group__append {
          border-radius: 0 20px 20px 0;
          background-color: #409EFF;
          border-color: #409EFF;
          color: white;
        }
      }
    }

    .member-info {
      padding: 15px;
      background: #f8f9fa;
      border-radius: 8px;
      margin: 15px;

      .member-header {
        display: flex;
        align-items: center;
        margin-bottom: 15px;

        .avatar {
          width: 50px;
          height: 50px;
          border-radius: 25px;
          background: #e6f2ff;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;

          i {
            font-size: 24px;
            color: #409EFF;
          }
        }

        .basic-info {
          .name {
            font-size: 16px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 4px;
          }

          .level {
            font-size: 12px;
            color: #909399;
          }
        }
      }

      .balance-info {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;

        .balance-item {
          text-align: center;
          padding: 10px;
          background: white;
          border-radius: 6px;

          .label {
            font-size: 12px;
            color: #909399;
            margin-bottom: 5px;
          }

          .value {
            font-size: 16px;
            font-weight: bold;
            color: #f56c6c;
          }
        }
      }
    }

    .no-member {
      text-align: center;
      padding: 30px 0;
      color: #909399;

      i {
        font-size: 48px;
        margin-bottom: 10px;
      }

      p {
        font-size: 14px;
      }
    }

    .cart-container {
      flex: 1;
      display: flex;
      flex-direction: column;
      margin: 0 15px;

      .cart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #ebeef5;

        .title {
          display: flex;
          align-items: center;

          i {
            font-size: 18px;
            margin-right: 5px;
            color: #409EFF;
          }

          .count {
            font-size: 12px;
            color: #909399;
            margin-left: 5px;
          }
        }
      }

      .cart-list {
        // flex: 1;
        height: calc(100vh - 420px);
        overflow-y: auto;

        &.empty {
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .empty-cart {
          text-align: center;
          color: #909399;

          i {
            font-size: 48px;
            margin-bottom: 10px;
          }

          p {
            font-size: 14px;
          }
        }

        .cart-item {
          // display: flex;
          // align-items: center;
          padding: 15px 10px;
          border-bottom: 1px dashed #ebeef5;
          position: relative;
          width: 100%;

          &:last-child {
            border-bottom: none;
          }
          .item-body {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            justify-content: space-between;
          }

          .price {
            display: flex;
            align-items: center;
            justify-content: space-between;
          }
        }

        .goods-info {
          .goods-name {
            font-size: 13px;
            color: #303133;
            margin-bottom: 3px;
          }

          .goods-spec {
            font-size: 12px;
            color: #909399;
          }
        }

        .subtotal {
          color: #f56c6c;
          font-weight: bold;
        }

        .delete-btn {
          padding: 0;
          position: absolute;
          top: 16px;
          right: 10px;

          i {
            font-size: 16px;
            color: #909399;

            &:hover {
              color: #f56c6c;
            }
          }
        }
      }

      .settlement-panel {
        border-top: 1px solid #ebeef5;
        padding: 15px 0;

        .amount-info {
          margin-bottom: 15px;

          .total-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;

            &:last-child {
              margin-bottom: 0;
            }

            .number {
              color: #409EFF;
              font-weight: bold;
            }

            .amount {
              color: #f56c6c;
              font-size: 20px;
              font-weight: bold;
            }
          }
        }

        .settle-btn {
          width: 100%;
          height: 40px;
          border-radius: 20px;
          font-size: 16px;

          i {
            margin-right: 5px;
          }
        }
      }
    }
  }
}

.settlement-dialog {
  .order-summary {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;

    .summary-row {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;

      .summary-item {
        text-align: center;

        .label {
          font-size: 14px;
          color: #606266;
          margin-bottom: 8px;
        }

        .value {
          font-size: 20px;
          font-weight: bold;

          &.highlight-blue { color: #409EFF; }
          &.highlight-red { color: #f56c6c; }
          &.highlight-green { color: #67c23a; }
        }
      }
    }
  }

  .section-card {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.05);

    .section-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 20px;
      display: flex;
      align-items: center;

      i {
        margin-right: 8px;
        font-size: 18px;
        color: #409EFF;
      }
    }

    .form-tip {
      margin-left: 10px;
      color: #909399;
      font-size: 13px;
    }

    .amount-display {
      margin-top: 15px;
      text-align: right;
      font-size: 16px;

      .highlight-amount {
        color: #f56c6c;
        font-size: 24px;
        font-weight: bold;
        margin-left: 10px;
      }
    }
  }

  .payment-methods {
    margin-bottom: 20px;

    .el-radio-group {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      // gap: 10px;

      .el-radio-button {
        display: block;
        width: 100%;

        ::v-deep .el-radio-button__inner {
          width: 100%;
          height: 60px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 0;
          border-radius: 4px;

          i {
            font-size: 24px;
            margin-bottom: 5px;
          }
        }
      }
    }
  }

  .payment-details {
    padding: 20px;
    background: #f8f9fa;
    border-radius: 4px;

    .balance-info {
      .info-item {
        margin-bottom: 10px;
        display: flex;
        align-items: center;

        .label {
          width: 100px;
          color: #606266;
        }

        .value {
          font-weight: bold;
          &.highlight-green { color: #67c23a; }
          &.highlight-red { color: #f56c6c; }
        }
      }
    }

    .cash-payment {
      .change-amount {
        margin-top: 10px;

        .label {
          color: #606266;
        }

        .value {
          font-size: 20px;
          font-weight: bold;
        }
      }
    }
  }
}

.right-panel {
  .search-bar {
    padding: 15px 0;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    align-items: center;

    .el-input {
      width: 100%;
      max-width: 600px;
    }
  }

  .goods-tabs {
    height: calc(100% - 80px); // 减去搜索栏的高度

    ::v-deep .el-tabs__content {
      height: calc(100% - 40px); // 减去标签页头部的高度
    }
  }

  .goods-container {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .goods-grid {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 15px;

    .goods-item {
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
      }
    }
  }

  .pagination-container {
    padding: 15px;
    text-align: right;
    background: #fff;
    border-top: 1px solid #ebeef5;
    height: 35px;
  }
}
</style>
