<template>
  <div class="order-content">
    <div class="order-status" v-if="order!=null">
      <el-steps :active="order.status==3?order.status+1:order.status" align-center>
        <el-step title="待支付"></el-step>
        <el-step title="待发货"></el-step>
        <el-step title="待收货"></el-step>
        <el-step title="交易完成"></el-step>
      </el-steps>
    </div>
    <div>

      <el-card shadow="never" style="margin-top: 15px">
        <div class="operate-container" v-show="order!=null">
        <span style="margin-left: 20px" class="color-danger">订单状态：
           <el-tag prop="status" v-for="(item, index) in statusOptions"
                   v-if="order.status==item.dictValue">{{ item.dictLabel }}</el-tag>
        </span>

          <div class="operate-button-container">
            <el-button size="mini" @click="handleCertificates()" v-hasPermi="['store:storeOrder:uploadCredentials']">
              上传凭证
            </el-button>
            <el-button size="mini" @click="handleEditAddress()" v-if="order.status==0||order.status==1"
                       v-hasPermi="['store:storeOrder:editAddress']">修改收货地址
            </el-button>
            <el-button size="mini" @click="handleBindCustomer()" v-hasPermi="['store:storeOrder:bindCustomer']">
              关联客户
            </el-button>
            <el-button size="mini" @click="editOrder()" v-hasPermi="['store:storeOrder:edit']">修改订单</el-button>
            <!-- <el-button size="mini" @click="handleEditUser()"  v-hasPermi="['users:user:edit']" >修改会员修改</el-button> -->
            <el-button size="mini" v-if="order.customerId!=null&&order.customerId>0" @click="handleCustomer()">
              查看客户详情
            </el-button>
          </div>
          <div class="operate-button-container" v-hasPermi="['store:storeOrder:express']">
            <el-button size="mini" @click="showExpress()">查看物流</el-button>
          </div>
          <div class="operate-button-container" v-hasPermi="['store:storeOrder:editDeliveryId']">
            <el-button size="mini" @click="editDelivery()">修改物流</el-button>
          </div>
        </div>
        <div style="margin: 20px 0px" v-if="order!=null">
        <span class="font-small">
          基本信息
        </span>
        </div>
        <el-descriptions :column="4" border>
          <el-descriptions-item label="订单编号">
                <span v-if="order!=null">
                  {{ order.orderCode }}
                </span>
            <el-tag v-for="(item, index) in createTypeOptions"
                    v-if="order!=null&&order.orderCreateType==item.dictValue">{{ item.dictLabel }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="会员">
                <span v-if="user!=null">
                  {{ user.nickname }}({{ user.phone }})
                </span>
          </el-descriptions-item>
          <!-- <el-descriptions-item label="进线时间"  >
              <span v-if="user!=null">
                {{user.registerDate}}
              </span>
          </el-descriptions-item>
          <el-descriptions-item label="推线编码"  >
              <span v-if="user!=null">
                {{user.registerCode}}
              </span>
          </el-descriptions-item> -->

          <el-descriptions-item label="收货人">
                <span v-if="order!=null ">
                  {{ order.realName }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="手机号码">
                <span v-if="order!=null ">
                  {{ order.userPhone }}
                </span>
            <el-button type="text" size="mini" @click="callNumber(0,0,orderId)"
                       v-hasPermi="['store:storeOrder:callNumber']">拨号
            </el-button>
            <el-button type="text" size="mini" @click="handleSms(order.userPhone)"
                       v-hasPermi="['store:storeOrder:sendSms']">短信
            </el-button>
            <el-button icon="el-icon-search" size="mini" @click="handlePhone()" style="margin-left: 20px;" circle
                       v-hasPermi="['store:storeOrder:queryPhone']"></el-button>
          </el-descriptions-item>
          <el-descriptions-item label="收货地址">
            <el-popover
              v-if="order!=null"
              placement="top-start"
              title="收货地址"
              width="300"
              trigger="hover"
              :content="order.userAddress">
              <span slot="reference">{{ order.userAddress }}</span>
              <el-button icon="el-icon-search" size="mini" @click="handleAddress()" style="margin-left: 20px;" circle
                         v-hasPermi="['store:storeOrder:queryAddress']"></el-button>
            </el-popover>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
                <span v-if="order!=null ">
                  <el-tag prop="orderType" v-for="(item, index) in payTypeOptions" v-if="order.payType==item.dictValue">{{
                      item.dictLabel
                    }}</el-tag>
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="订单类型">
                <span v-if="order!=null ">
                  <el-tag prop="orderType" v-for="(item, index) in orderTypeOptions"
                          v-if="order.orderType==item.dictValue">{{ item.dictLabel }}</el-tag>
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="物流公司编号">
                <span v-if="order!=null ">
                  {{ order.deliverySn }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="物流公司名称">
                <span v-if="order!=null ">
                  {{ order.deliveryName }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="快递单号">
                <span v-if="order!=null ">
                  {{ order.deliveryId }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="发货人手机号">
                <span v-if="order!=null ">
                  {{ order.senderPhone }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="物流状态">
                <span v-if="order!=null">
                  <el-tag v-for="(item, index) in deliveryStatusOptions"
                          v-if="order.deliveryStatus==item.dictValue"
                          :key="index">{{ item.dictLabel }}</el-tag>
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="物流跟踪状态">
                <span v-if="order!=null">
                  <el-tag v-for="(item, index) in deliveryTypeOptions"
                          v-if="order.deliveryType==item.dictValue"
                          :key="index">{{ item.dictLabel }}</el-tag>
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="档期归属">
            <el-tag prop="scheduleId" v-for="(item, index) in scheduleOptions"
                    v-if="order!=null&&order.scheduleId==item.id">{{ item.name }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户备注">
                <span v-if="order!=null ">
                  {{ order.mark }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="平台备注">
                <span v-if="order!=null ">
                  {{ order.remark }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item v-if="projectCode === 'ddgy'" label="交易码">
                <span v-if="order!=null ">
                  {{ order.transactionCode }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="销售名称" v-if="order!=null && order.orderType != 0">
                <span >
                  {{ order.companyUserName }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="销售公司" v-if="order!=null && order.orderType != 0">
                <span >
                  {{ order.companyName }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="所属营期" v-if="order!=null && order.orderType == 3">
                <span >
                  {{ order.periodName }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="所属小节" v-if="order!=null && order.orderType == 3">
                <span >
                  {{ order.videoName }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item label="跟随阶段" v-if="company.companyId == 174">
              <span v-if="order!=null ">
                <el-tag prop="orderVisit" v-for="(item, index) in customerUserStatusOptions"
                        v-if="order.orderVisit==item.dictValue">{{ item.dictLabel }}</el-tag>
              </span>
          </el-descriptions-item>
          <el-descriptions-item v-if="customerInfo!=null " label="客户编码">
                <span>
                  {{ customerInfo.customerCode }}
                </span>
          </el-descriptions-item>
          <el-descriptions-item v-if="customerInfo!=null " label="进线时间">
                <span>
                  {{ customerInfo.registerDate }}
                </span>
          </el-descriptions-item>

            <el-descriptions-item label="财务审核原因" v-if="isRefundOrder">
                <span>{{ financeAuditReasonText }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="财务审核备注" v-if="isRefundOrder">
                <span>{{ financeAuditRemarkText }}</span>
            </el-descriptions-item>

        </el-descriptions>
        <div style="margin: 20px 0px" v-if="order!=null">
        <span class="font-small">
          凭证信息
        </span>
        </div>
        <el-image
          v-if="this.certificates != null"
          :src="certificates"
          :preview-src-list="[certificates]"
          :style="{ width: '100px', height: '100px' }"
          @click.native="showImageDialog"
        ></el-image>
        <el-dialog :visible.sync="dialogVisibleImage" width="10%">
          <img :src="certificates" style="width: 100%" alt="">
        </el-dialog>

        <div style="margin-top: 20px">
          <span class="font-small">商品信息</span>
          <el-button
            class="select-product-btn"
            @click="openProductSelection"
            icon="el-icon-shopping-cart-2"
            size="small"
            type="primary"
            v-hasPermi="['store:storeOrderItem:add']">
            新增商品
          </el-button>
          <el-button
            class="remove-product-btn"
            @click="removeSelectedProduct"
            icon="el-icon-delete"
            size="small"
            type="danger"
            v-hasPermi="['store:storeOrderItem:remove']">
            移除商品
          </el-button>
        </div>
        <el-table
          ref="itemsTable"
          border
          v-if="items!=null"
          :data="items"
          size="small"
          style="width: 100%;margin-top: 20px"
          @selection-change="handleItemsSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="商品图片" width="150" align="center">
            <template slot-scope="scope">
              <img :src="JSON.parse(scope.row.jsonInfo).image" style="height: 80px">
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="300" align="center">
            <template slot-scope="scope">
              <p>{{ JSON.parse(scope.row.jsonInfo).productName }}</p>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="240" align="center">
            <template slot-scope="scope">
              <p>￥{{ JSON.parse(scope.row.jsonInfo).price.toFixed(2) }}</p>
            </template>
          </el-table-column>
          <el-table-column label="规格" width="240" align="center">
            <template slot-scope="scope">
              {{ JSON.parse(scope.row.jsonInfo).sku }}
            </template>
          </el-table-column>
          <el-table-column label="数量" width="180" align="center">
            <template slot-scope="scope">
              <div class="quantity-cell">
                <div class="quantity-display">
                  <span class="quantity-value">{{ scope.row.num }}</span>
                </div>
                <el-button
                  size="mini"
                  type="default"
                  icon="el-icon-edit"
                  class="edit-quantity-btn"
                  @click="showQuantityEdit(scope)"
                  v-hasPermi="['store:storeOrderItem:updateNum']">
                  修改数量
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="小计" align="center">
            <template slot-scope="scope">
              ￥{{ scope.row.num * JSON.parse(scope.row.jsonInfo).price.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <div style="float: right;margin: 20px" v-if="order!=null">
          合计：<span class="color-danger">￥{{ order.totalPrice.toFixed(2) }}</span>
        </div>

        <div style="margin: 60px 0px 20px 0px">
          <span class="font-small">费用信息</span>
        </div>
        <el-descriptions v-if="zdyInfo !== 'gzzdy'" :column="4" border>
          <el-descriptions-item label="商品合计">
              <span v-if="order!=null">
                ￥{{ order.totalPrice.toFixed(2) }}
              </span>
          </el-descriptions-item>
          <el-descriptions-item label="应付金额">
              <span v-if="order!=null">
                ￥{{ order.payPrice.toFixed(2) }}
              </span>
          </el-descriptions-item>
          <el-descriptions-item label="运费">
              <span v-if="order!=null">
                ￥{{ order.payPostage.toFixed(2) }}
              </span>
          </el-descriptions-item>
          <el-descriptions-item label="优惠券">
              <span v-if="order!=null">
                ￥{{ order.couponPrice.toFixed(2) }}
              </span>
              <span v-else>￥0.00</span>
          </el-descriptions-item>
          <el-descriptions-item label="积分抵扣">
              <span v-if="order!=null">
                ￥{{ order.deductionPrice.toFixed(2) }}
              </span>
          </el-descriptions-item>
          <el-descriptions-item label="实付金额">
              <span v-if="order!=null">
                ￥{{ order.payMoney.toFixed(2) }}
              </span>
          </el-descriptions-item>
          <el-descriptions-item label="代收金额">
              <span v-if="order!=null">
                ￥{{ order.payDelivery.toFixed(2) }}
              </span>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions v-if="zdyInfo === 'gzzdy'" :column="4" border>
          <el-descriptions-item label="商品合计">
            <span v-if="order!=null">
              ￥{{ order.totalPrice.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="应付金额">
            <span v-if="order!=null">
              ￥{{ order.payPrice.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="实付金额">
            <span v-if="order!=null">
              ￥{{ order.payMoney.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="代收金额">
            <span v-if="order!=null">
              ￥{{ order.payDelivery.toFixed(2) }}
            </span>
            <el-button
              size="mini"
              type="primary"
              plain
              class="edit-quantity-btn"
              @click="editPayDeliveryHandle()"
              v-hasPermi="['store:storeOrder:editPayDelivery']">
              修改
            </el-button>
          </el-descriptions-item>
          <el-descriptions-item label="优惠券">
            <span v-if="order!=null">
              ￥{{ order.couponPrice.toFixed(2) }}
            </span>
            <span v-else>￥0.00</span>
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 20px">
          <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
          <span class="font-small">支付信息</span>
        </div>
        <el-table
          border
          :data="payments"
          size="small"
          style="width: 100%;margin-top: 20px">
          <el-table-column label="支付单号" align="center" prop="payCode" width="120px"/>
          <el-table-column label="支付金额" align="center" prop="payMoney"/>
          <el-table-column label="类型" align="center" prop="payTypeCode"/>
          <el-table-column label="交易单号" align="center" prop="bankTransactionId"/>
          <el-table-column label="银行单号" align="center" prop="bankSerialNo"/>
          <el-table-column label="创建时间" align="center" prop="createTime"/>
          <el-table-column label="支付时间" align="center" prop="payTime"/>
        </el-table>

        <div style="margin-top: 20px">
          <span class="font-small">历史订单商品信息</span>
        </div>
        <el-table
          class="other-products-table unified-table"
          border
          :data="otherProducts"
          size="small"
          style="width: 100%; margin-top: 20px"
          :header-cell-style="{background: '#f8f9fa', color: '#000', fontWeight: '600'}"
          :empty-text="'暂无数据'"
        >
          <el-table-column label="订单编号" align="center" width="170px" prop="orderCode">
            <template slot-scope="scope">
              <div class="text-cell">
                <span class="text-content">{{ scope.row.orderCode }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" width="180px" prop="orderCreateTime">
            <template slot-scope="scope">
              <div class="text-cell">
                <span class="text-content">{{ formatDateTime(scope.row.orderCreateTime) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单金额" align="center" width="110px" prop="orderMoney">
            <template slot-scope="scope">
              <div class="text-cell">
                <span class="currency-symbol">¥</span>
                <span class="number-content">{{ scope.row.orderMoney ? parseFloat(scope.row.orderMoney).toFixed(2) : '0.00' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订金" align="center" width="110px" prop="orderPayDelivery">
            <template slot-scope="scope">
              <div class="text-cell">
                <span class="currency-symbol">¥</span>
                <span class="number-content">{{ scope.row.orderPayDelivery ? parseFloat(scope.row.orderPayDelivery).toFixed(2) : '0.00' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center" width="90px" prop="orderStatus">
            <template slot-scope="scope">
              <div class="tag-cell">
                <el-tag
                  :type="getStatusTagType(scope.row.orderStatus)"
                  size="medium"
                  effect="plain"
                >
                  <!-- 优先使用字典显示 -->
                  <span v-for="(item, index) in statusOptions" :key="index" v-if="scope.row.orderStatus == item.dictValue">
                    {{ item.dictLabel }}
                  </span>
                  <!-- 字典中找不到时使用备用方法 -->
                  <span v-if="!statusOptions.some(item => scope.row.orderStatus == item.dictValue)">
                    {{ getOrderStatusText(scope.row.orderStatus) }}
                  </span>
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="销售员" align="center" width="120px" prop="orderCompanyUserName">
            <template slot-scope="scope">
              <div class="text-cell">
                <span class="text-content">{{ scope.row.orderCompanyUserName || '未指定' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品信息" align="center" min-width="450px" prop="orderItemJson">
            <template slot-scope="scope">
              <div class="products-cell unified-cell">
                <!-- 缓存解析结果以提高性能 -->
                <div class="first-product" v-if="scope.row.orderItemJson">
                  <div v-if="cachedOrderItems(scope.row.orderItemJson).length > 0">
                    <div class="product-preview">
                      <span class="product-name">{{ cachedOrderItems(scope.row.orderItemJson)[0].productName }}</span>
                      <span class="product-count" v-if="cachedOrderItems(scope.row.orderItemJson).length > 1">
                        等{{ cachedOrderItems(scope.row.orderItemJson).length }}件商品
                      </span>
                    </div>
                  </div>
                  <div class="no-product" v-else>
                    <i class="el-icon-info"></i>
                    <span>暂无商品</span>
                  </div>
                </div>

                <!-- 根据商品数量显示不同的按钮 -->
                <div v-if="scope.row.orderItemJson" class="action-buttons">
                  <el-button
                    v-if="cachedOrderItems(scope.row.orderItemJson).length === 1"
                    class="detail-btn unified-btn"
                    @click="handleMoreOrderItems(scope.row)"
                    size="mini"
                    round
                  >
                    <i class="el-icon-view"></i>
                    查看详情
                  </el-button>
                  <el-button
                    v-else-if="cachedOrderItems(scope.row.orderItemJson).length > 1"
                    class="detail-btn unified-btn"
                    @click="handleMoreOrderItems(scope.row)"
                    size="mini"
                    round
                  >
                    <i class="el-icon-more"></i>
                    查看全部({{ cachedOrderItems(scope.row.orderItemJson).length }})
                  </el-button>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 其它商品信息分页 -->
        <pagination
          v-show="otherProducts && otherProducts.length > 0 && otherProductsTotal >= otherProductsPageSize"
          :total="otherProductsTotal"
          :page.sync="otherProductsPage"
          :limit.sync="otherProductsPageSize"
          @pagination="handleOtherProductsPagination"
        />


        <div style="margin-top: 20px">
          <span class="font-small">操作信息</span>
        </div>
        <el-table style="margin-top: 20px;width: 100%"
                  ref="orderHistoryTable"
                  :data="logs" border>
          <el-table-column label="操作时间" width="160" align="center">
            <template slot-scope="scope">
              {{ scope.row.changeTime }}
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="scope">
              {{ scope.row.changeMessage }}
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 20px">
          <span class="font-small">审批信息</span>
        </div>
        <el-table style="margin-top: 20px;width: 100%"
                  :data="auditLogs" border>
          <el-table-column label="操作时间" width="160" align="center">
            <template slot-scope="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="scope">
              {{ scope.row.content }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-dialog :title="edit.title" :visible.sync="edit.open" width="600px" append-to-body>
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="订单类型" prop="orderType">
          <el-select style="width: 200px" v-model="editForm.orderType" placeholder="请选择订单类型" clearable
                     size="small">
            <el-option
              v-for="item in orderTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="档期归属" prop="scheduleId">
          <el-select filterable style="width: 200px" v-model="editForm.scheduleId" placeholder="请选择档期" clearable
                     size="small">
            <el-option
              v-for="item in scheduleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="跟随阶段" prop="orderVisit" v-if="company.companyId == 174">
          <el-select filterable style="width: 200px" v-model="editForm.orderVisit" placeholder="请选择跟随阶段"
                     clearable size="small">
            <el-option
              v-for="item in customerUserStatusOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="mark">
          <el-input v-model="editForm.mark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="editUser.title" :visible.sync="editUser.open" width="600px" append-to-body>
      <el-form ref="editUserForm" :model="editUserForm" :rules="editUserRules" label-width="100px">
        <el-form-item label="进线时间" prop="registerDate">
          <el-date-picker clearable size="small"
                          v-model="editUserForm.registerDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择进线时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="推线编码" prop="registerCode">
          <el-input v-model="editUserForm.registerCode" placeholder="请输入推线编码"/>
        </el-form-item>
        <el-form-item label="渠道来源" prop="source">
          <el-input v-model="editUserForm.source" placeholder="请输入渠道来源"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditUserForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="editAddress.title" :visible.sync="editAddress.open" width="600px" append-to-body>
      <el-form ref="editAddressForm" :model="editAddressForm" :rules="editAddressRules" label-width="100px">
        <el-form-item label="收件人" prop="realName">
          <el-input v-model="editAddressForm.realName" placeholder="请输入收件人"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="source">
          <el-input v-model="editAddressForm.userPhone" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="收货地址" prop="district">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-select @change="provinceChange" v-model="editAddressForm.provinceId" placeholder="请选择">
                <el-option
                  v-for="item in province"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select @change="cityChange" v-model="editAddressForm.cityId" placeholder="请选择">
                <el-option
                  v-for="item in city"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select @change="districtChange" v-model="editAddressForm.districtId" placeholder="请选择">
                <el-option
                  v-for="item in district"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="editAddressForm.detail" placeholder="请输入收货人详细地址"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditAddressForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="expressDialog.title" :visible.sync="expressDialog.open" width="600px" append-to-body>
      <el-table style="margin-top: 20px;width: 100%"
                ref="orderHistoryTable"
                :data="traces" border>
        <el-table-column label="操作时间" width="160" align="center">
          <template slot-scope="scope">
            {{ scope.row.AcceptTime }}
          </template>
        </el-table-column>
        <el-table-column label="位置" align="center">
          <template slot-scope="scope">
            {{ scope.row.Location }}
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center">
          <template slot-scope="scope">
            {{ scope.row.AcceptStation }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :title="editDy.title" :visible.sync="editDy.open" width="600px" append-to-body>
      <el-form ref="editDyForm" :model="editDyForm" :rules="editDyRules" label-width="120px">
        <el-form-item label="物流公司" prop="deliverySn">
          <el-select style="width:220px" v-model="editDyForm.deliverySn" placeholder="请选择" clearable size="small">
            <el-option key="SF" label="顺丰" value="SF"/>
            <el-option key="EMS" label="邮政" value="EMS"/>
            <el-option key="ZTO" label="中通" value="ZTO"/>
            <el-option key="STO" label="申通" value="STO"/>
            <el-option key="JD" label="京东" value="JD"/>
            <el-option key="DBL" label="德邦" value="DBL"/>
            <el-option key="JTSD" label="极兔" value="JTSD"/>
            <el-option key="YD" label="韵达" value="YD"/>
            <el-option key="YTO" label="圆通" value="YTO"/>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="deliveryId">
          <el-input v-model="editDyForm.deliveryId" placeholder="请输入物流单号"/>
        </el-form-item>
        <el-form-item label="发货人手机号" prop="senderPhone">
          <el-input v-model="editDyForm.senderPhone" placeholder="请输入发货人手机号（物流订阅/查询用）" maxlength="20"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditDyForm">确 定</el-button>
        <el-button @click="editDy.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="bindCustomerDialog.title" :visible.sync="bindCustomerDialog.open" width="800px" append-to-body>
      <el-form ref="bindCustomerForm" :model="bindCustomerForm" :rules="bindCustomerRules" label-width="100px">
        <el-form-item label="客户查询">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-input v-model="bindCustomerForm.mobile" placeholder="请输入客户手机号"/>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" @click="searchCustomer">查看</el-button>
            </el-col>
          </el-row>

        </el-form-item>
        <el-form-item label="客户选择" prop="customerIds">
          <el-table @selection-change="handleSelectionChange"
                    :data="customers" border>
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="ID" align="center" prop="customerId"/>
            <el-table-column label="客户编号" width="160" align="center">
              <template slot-scope="scope">
                {{ scope.row.customerCode }}
              </template>
            </el-table-column>
            <el-table-column label="客户名称" width="160" align="center">
              <template slot-scope="scope">
                {{ scope.row.customerName }}
              </template>
            </el-table-column>
            <el-table-column label="客户手机号" width="160" align="center">
              <template slot-scope="scope">
                {{ scope.row.mobile }}
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindCustomerForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="certificateDialig.title" :visible.sync="certificateDialig.open" append-to-body>
      <el-form ref="certificateForm" :model="certificateForm" :rules="certificateRules" label-width="100px">
        <el-form-item label="凭证" prop="certificates">
          <ImageUpload v-model="photoArr" type="image" :num="10" :width="150" :height="150"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <el-drawer
      :append-to-body="true"
      size="75%"
      :title="customer.title" :visible.sync="customer.open"
    >
      <customer-details ref="customerDetails"/>
    </el-drawer>
    <el-dialog :title="addSms.title" :visible.sync="addSms.open" width="800px" append-to-body>
      <add-sms ref="sms" @close="closeSms()"></add-sms>
    </el-dialog>
    <!-- 数量修改弹窗 -->
    <el-dialog :title="quantityDialog.title" :visible.sync="quantityDialog.open" width="500px" append-to-body>
      <el-form ref="quantityForm" :model="quantityForm" :rules="quantityRules" label-width="100px">
        <el-form-item label="商品名称">
          <span class="dialog-product-name">{{ quantityForm.productName }}</span>
        </el-form-item>

        <el-form-item label="当前单价">
          <el-tag type="info" size="medium">￥{{ quantityForm.price ? quantityForm.price.toFixed(2) : '0.00' }}</el-tag>
        </el-form-item>

        <el-form-item label="当前数量">
          <el-tag type="info" size="medium">{{ quantityForm.originalNum }}</el-tag>
        </el-form-item>

        <el-form-item label="新数量" prop="newNum">
          <el-input-number
            v-model="quantityForm.newNum"
            :min="1"
            :max="999999"
            controls-position="right"
            style="width: 200px">
          </el-input-number>
        </el-form-item>

        <el-form-item label="总金额">
          <el-tag type="danger" size="medium">
            ￥{{ (quantityForm.newNum * quantityForm.price).toFixed(2) }}
          </el-tag>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="quantityDialog.open = false">取 消</el-button>
        <el-button type="primary" @click="submitQuantityForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增商品弹窗 -->
    <el-dialog :title="productOrderDialog.title" :visible.sync="productOrderDialog.open" width="1800px" append-to-body>
      <div class="app-container">
        <el-form :model="productOrderQueryParams" ref="productOrderQueryForm" :inline="true" label-width="68px">
          <el-form-item label="商品分类" prop="cateId">
            <treeselect v-model="productOrderQueryParams.cateId" style="width:205.4px" :options="categoryOptions"
                        :normalizer="normalizer" placeholder="请选择分类"/>
          </el-form-item>
          <el-form-item label="商品名称" prop="productName">
            <el-input
              v-model="productOrderQueryParams.productName"
              placeholder="请输入商品名称"
              clearable
              size="small"
              @keyup.enter.native="productOrderHandleQuery"
            />
          </el-form-item>
          <el-form-item label="商品编号" prop="barCode">
            <el-input
              v-model="productOrderQueryParams.barCode"
              placeholder="请输入商品编号"
              clearable
              size="small"
              @keyup.enter.native="productOrderHandleQuery"
            />
          </el-form-item>
          <el-form-item label="商品类型" prop="productType">
            <el-select v-model="productOrderQueryParams.productType" placeholder="请选择商品类型" clearable
                       size="small">
              <el-option
                v-for="item in productTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属公司">
            <el-select style="width: 240px" v-model="companyId" multiple placeholder="请选择企业" clearable
                       size="small">
              <el-option
                v-for="item in companyOptions"
                :key="item.companyId"
                :label="item.companyName"
                :value="item.companyId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属店铺" v-if="this.isStores">
            <el-select style="width: 240px" v-model="productOrderQueryParams.storeIds" placeholder="请选择店铺"
                       clearable size="small">
              <el-option
                v-for="item in storeOptions"
                :key="item.storeId"
                :label="item.storeName"
                :value="item.storeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="productOrderHandleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="productOrderResetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          ref="productOrderTable"
          height="500"
          border
          v-loading="productOrderLoading"
          :data="storeProductList"
          @selection-change="handleProductSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="ID" align="center" prop="productId"/>
          <el-table-column label="商品图片" align="center" width="120">
            <template slot-scope="scope">
              <el-popover
                placement="right"
                title=""
                trigger="hover">
                <img slot="reference" :src="scope.row.image" width="100">
                <img :src="scope.row.image" style="max-width: 150px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" show-overflow-tooltip align="center" prop="productName"/>
          <el-table-column label="分类" align="center" prop="cateName"/>
          <el-table-column label="所属公司" align="center" prop="companyName"/>
          <el-table-column label="所属店铺" align="center" prop="storeName" v-if="this.isStores"/>
          <el-table-column label="售价" align="center" prop="price">
            <template slot-scope="scope">
              <span v-if="scope.row.price!=null">{{ scope.row.price.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="原价" align="center" prop="otPrice">
            <template slot-scope="scope">
              <span v-if="scope.row.otPrice!=null">{{ scope.row.otPrice.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="销量" align="center" prop="sales"/>
          <el-table-column label="库存" align="center" prop="stock"/>
          <el-table-column label="类型" align="center" prop="productType">
            <template slot-scope="scope">
              <el-tag prop="productType" v-for="(item, index) in productTypeOptions"
                      v-if="scope.row.productType==item.dictValue">{{ item.dictLabel }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="isShow">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row)" prop="status">
                {{ getStatusText(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

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

        <div style="text-align: center; margin-top: 20px;">
          <el-button
            type="primary"
            size="medium"
            icon="el-icon-plus"
            @click="handleBatchAdd"
            v-hasPermi="['store:storeOrderItem:add']"
            :disabled="!ids || ids.length === 0">
            批量添加商品
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!--  修改代收金额  -->
    <el-dialog :title="editPayDelivery.title" :visible.sync="editPayDelivery.open" width="500px" append-to-body>
      <el-form ref="payDeliveryForm" :model="payDeliveryForm" :rules="payDeliveryRules" label-width="150px">
        <el-form-item label="代收金额（元）" prop="payDelivery">
          <el-input-number
            v-model="payDeliveryForm.payDelivery"
            :min="0.00"
            :precision="2"
            :step="0.01"
            size="small"
            style="width: 150px"
          >
          </el-input-number>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editPayDelivery.open = false">取 消</el-button>
        <el-button type="primary" @click="submitPayDeliveryForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 其他商品详情弹窗 -->
    <el-dialog
      :visible.sync="productDetailDialog.visible"
      width="900px"
      append-to-body
      class="unified-detail-dialog"
      :before-close="handleProductDetailClose"
    >
      <div slot="title" class="dialog-custom-title">
        <span class="font-small">{{ productDetailDialogTitle }}</span>
      </div>
      <div class="dialog-content">
        <el-table
          :data="paginatedProductDetails"
          border
          style="width: 100%"
          :header-cell-style="{background: '#f8f9fa', color: '#303133', fontWeight: '600'}"
          class="unified-dialog-table"
        >
          <el-table-column label="商品图片" width="120" align="center">
            <template slot-scope="scope">
              <div class="dialog-image-container">
                <el-image
                  :src="scope.row.image"
                  class="dialog-product-image"
                  fit="cover"
                  :preview-src-list="[scope.row.image]"
                >
                  <div slot="error" class="image-placeholder">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" min-width="200" align="center">
            <template slot-scope="scope">
              <div class="dialog-product-info">
                <div class="product-name-container">
                  <span class="dialog-product-name">{{ scope.row.productName }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="100" align="center">
            <template slot-scope="scope">
              <div class="dialog-price-cell">
                <span class="price-symbol">¥</span>
                <span class="price-value">{{ scope.row.price ? scope.row.price.toFixed(2) : '0.00' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="规格" width="120" align="center">
            <template slot-scope="scope">
              <div class="dialog-sku-cell">
                <span class="sku-value">{{ scope.row.sku || '默认' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="80" align="center">
            <template slot-scope="scope">
              <el-tag size="small" type="primary">{{ scope.row.num }}</el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 表格内容区域右下角容器 -->
        <div class="table-bottom-right-container">
          <!-- 分页组件 -->
          <div class="dialog-pagination-wrapper" v-if="productDetailDialog.products && productDetailDialog.products.length > 5">
            <div class="dialog-pagination">
              <pagination
                :total="productDetailDialog.products.length"
                :page.sync="productDetailPage"
                :limit.sync="productDetailPageSize"
                @pagination="handleProductDetailPagination"
                :page-sizes="[5, 10, 20, 50]"
                layout="prev, pager, next, jumper, ->, total"
              />
            </div>
          </div>

          <!-- 关闭按钮 -->
          <div class="dialog-close-section">
            <el-button
              class="transparent-close-btn"
              @click="productDetailDialog.visible = false"
              size="medium"
            >
              <i class="el-icon-circle-close"></i>
              关闭
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getExpress,
  getStoreOrder,
  getStoreOrderAddress,
  updateStoreOrder,
  updateStoreOrderItemJson,
  updateDeliveryId,
  bindCustomer,
  uploadCredentials,
  getUserPhone,
  editPayDelivery
} from "@/api/hisStore/storeOrder";
import {listStoreProduct} from "@/api/hisStore/storeProduct";
import {updateUser, getUser} from "@/api/users/user";
import {getTcmScheduleList} from "@/api/company/tcmScheduleReport";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getAllStoreProductCategory} from "@/api/hisStore/storeProductCategory";
import Editor from '@/components/Editor/wang';
import singleImg from '@/components/Material/single'
import {getCompanyList} from "@/api/company/company";
import {listStore} from '@/api/hisStore/store';
import {addStoreOrderItem, delStoreOrderItem, updateNumStoreOrderItem} from "../../../api/hisStore/storeOrderItem";
import {getCustomerListBySearch} from "@/api/crm/customer";
import ImageUpload from '@/components/ImageUpload'
import Material from '@/components/Material'
import {getCitys} from "@/api/hisStore/city";
import customerDetails from '../../crm/components/customerDetails.vue';
import addSms from '../../crm/components/addSms.vue';
import Pagination from '@/components/Pagination';
import {queryUserOtherOrderPage} from "../../../api/hisStore/storeOrder";

export default {
  name: "order",
  components: {customerDetails, ImageUpload, Material, addSms, Treeselect, Editor, singleImg, Pagination},
  data() {
    return {
      zdyInfo: process.env.VUE_APP_FS_USER_INFO,
      projectCode: process.env.VUE_APP_PROJECT_CODE,
      // 遮罩层
      productOrderLoading: true,
      isStores: true,
      companyId: null,
      storeId: null,
      isAudit: null,
      storeForm: {isAudit: 1, status: 1},
      // 总条数
      total: 0,
      // 商品表格数据
      storeProductList: [],
      productTypeOptions: [],
      productTuiCateOptions: [],
      isDisplayOptions: [],
      isGoodOptions: [],
      isNewOptions: [],
      isBestOptions: [],
      isHotOptions: [],
      isShowOptions: [],
      categoryOptions: [],
      // 企业列表
      companyOptions: [],
      storeOptions: [],
      // 选中的商品列表
      selectedItems: [],
      // 批量添加时选中的商品ID列表
      ids: [],
      // 是否单选
      single: true,
      // 是否多选
      multiple: true,
      // 查询参数
      productOrderQueryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productType: null,
        isShow: "1",
        barCode: null,
        companyIds: null,
        storeIds: null,
        drugRegCertNo: null,
        commonName: null,
        dosageForm: null,
        unitPrice: null,
        batchNumber: null,
        mah: null,
        mahAddress: null,
        manufacturer: null,
        manufacturerAddress: null,
        indications: null,
        dosage: null,
        adverseReactions: null,
        contraindications: null,
        precautions: null,
        excludeProductIds: [],
      },
      productOrderDialog: {
        title: "商品选择",
        open: false,
      },
      // 数量修改弹窗相关数据
      quantityDialog: {
        title: "修改商品数量",
        open: false,
      },
      quantityForm: {
        itemId: null,
        productName: null,
        price: null,
        //新数量
        newNum: null,
        //原始数量
        originalNum: null
      },
      quantityRules: {
        newNum: [
          {required: true, message: "数量不能为空", trigger: "blur"},
          {type: 'number', min: 1, message: "数量至少为1", trigger: "blur"},
          {type: 'number', max: 999999, message: "数量不能超过999999", trigger: "blur"}
        ]
      },
      // 删除商品相关
      removeProductLoading: false,

      customerUserStatusOptions: [],
      scheduleOptions: [],
      dialogVisibleImage: false,
      customerInfo: null,
      customer: {
        title: "客户详情",
        open: false,
      },
      photoArr: null,
      certificateDialig: {
        title: "上传凭证",
        open: false,
      },
      certificateForm: {
        orderCode: null,
        certificates: null,
      },
      addSms: {
        open: false,
        title: "发短信"
      },
      certificateRules: {
        certificates: [
          {required: true, message: "凭证不能为空", trigger: "change"}
        ]
      },
      customers: [],
      bindCustomerDialog: {
        title: "关联客户",
        open: false,
      },
      bindCustomerForm: {
        mobile: null,
        customerIds: null,
      },
      bindCustomerRules: {
        customerIds: [
          {required: true, message: "客户不能为空", trigger: "change"}
        ],

      },
      orderId: null,
      expressDialog: {
        title: "物流信息",
        open: false,
      },
      editDy: {
        title: "修改物流单号",
        open: false,
      },
      editDyForm: {
        id: null,
        deliverySn: null,
        deliveryId: null,
        senderPhone: null,
      },
      editDyRules: {
        deliverySn: [
          {required: true, message: "物流公司不能为空", trigger: "blur"}
        ],
        deliveryId: [
          {required: true, message: "物流单号不能为空", trigger: "blur"}
        ],
      },
      citys: [],
      province: [],
      city: [],
      district: [],
      editAddress: {
        title: "修改收货地址",
        open: false,
      },
      editAddressForm: {
        districtId: null,

      },
      editAddressRules: {},
      editUser: {
        title: "修改会员信息",
        open: false,
      },
      editUserForm: {
        registerDate: null,
        registerCode: "",
        source: "",
      },
      editUserRules: {},
      edit: {
        title: "",
        open: false,
      },
      editForm: {
        orderType: null,
        scheduleId: null,
        orderVisit: null,
        mark: "",
      },
      editRules: {},
      createTypeOptions: [],
      deliveryStatusOptions: [],
      deliveryTypeOptions: [],
      orderTypeOptions: [],
      payTypeOptions: [],
      statusOptions: [],
      certificates: null,
      order: null,
      user: {},
      logs: [],
      items: [],
      express: [],
      traces: [],
      payments: [],
      otherProducts: [],
      auditLogs: [],
      // 修改代收金额相关参数
      editPayDelivery: {
        title: "修改代收金额",
        open: false,
      },
      payDeliveryForm: {
        id: null,
        payDelivery: 0.00
      },
      payDeliveryRules: {
        payDelivery: [
          {required: true, message: "代收金额不能为空", trigger: "blur"},
        ]
      },
      // 商品详情弹窗数据
      productDetailDialog: {
        visible: false,
        products: [],
        orderCode: ''
      },
      currentOrderCode: '',
      // 其它商品详情分页数据
      productDetailPage: 1,
      productDetailPageSize: 5,
      // 其它商品信息分页数据
      otherProductsPage: 1,
      otherProductsPageSize: 5,
      otherProductsTotal: 0,
      afterSales: {
        auditReasonName: null,
        auditRemark: null,
        reasonValue1: null,
        reasonValue2: null
      }
    };
  },
  created() {
    this.getDicts("store_order_delivery_status").then((response) => {
      this.deliveryStatusOptions = response.data;
    });
    this.getDicts("store_order_delivery_type").then((response) => {
      this.deliveryTypeOptions = response.data;
    });
    this.getDicts("crm_customer_user_status").then((response) => {
      this.customerUserStatusOptions = response.data;
    });
    this.getDicts("store_order_type").then((response) => {
      this.orderTypeOptions = response.data;
    });
    this.getDicts("store_order_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("store_pay_type").then((response) => {
      this.payTypeOptions = response.data;
    });
    this.getDicts("store_order_create_type").then((response) => {
      this.createTypeOptions = response.data;
    });
    getTcmScheduleList().then(response => {
      this.scheduleOptions = response.data;
    });

  },
  computed: {
    company() {
      return this.$store.state.user.user;
    },
    // 缓存解析后的订单商品数据以提高性能
    cachedOrderItems() {
      const cache = {};
      return (orderItemJson) => {
        const key = orderItemJson;
        if (!cache[key]) {
          cache[key] = this.parseOrderItems(orderItemJson);
        }
        return cache[key];
      };
    },
    // 商品详情分页数据
    paginatedProductDetails() {
      if (!this.productDetailDialog.products || this.productDetailDialog.products.length === 0) {
        return [];
      }

      const start = (this.productDetailPage - 1) * this.productDetailPageSize;
      const end = start + this.productDetailPageSize;
      return this.productDetailDialog.products.slice(start, end);
    },
    // 商品详情弹窗标题
    productDetailDialogTitle() {
      const productCount = this.productDetailDialog.products?.length || 0;
      if (productCount === 1) {
        return `历史订单商品 ${this.currentOrderCode} - 商品详情`;
      } else if (productCount > 1) {
        return `历史订单商品 ${this.currentOrderCode} - 全部商品 (${productCount}件)`;
      }
      return `历史订单商品 ${this.currentOrderCode} - 商品详情`;
    },
    /** 退款中 / 已退款 */
    isRefundOrder() {
      if (!this.order) return false;
      const s = Number(this.order.status);
      return s === -1 || s === -2;
    },
    /** 财务审核原因：售后一级 + 二级，兼容旧数据 auditReasonName */
    financeAuditReasonText() {
      const a = this.afterSales;
      if (!a) return '—';
      const parts = [a.reasonValue1, a.reasonValue2].filter(
        x => x != null && String(x).trim() !== ''
      );
      if (parts.length > 0) return parts.join(' / ');
      if (a.auditReasonName) return a.auditReasonName;
      return '—';
    },
    financeAuditRemarkText() {
      const a = this.afterSales;
      if (!a || a.auditRemark == null || String(a.auditRemark).trim() === '') return '—';
      return a.auditRemark;
    }

  },
  methods: {
    // 防抖函数
    debounce(func, wait) {
      let timeout;
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout);
          func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
      };
    },

    // 节流函数
    throttle(func, limit) {
      let inThrottle;
      return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
          func.apply(context, args);
          inThrottle = true;
          setTimeout(() => inThrottle = false, limit);
        }
      }
    },

    getUserOtherOrder(orderId, orderUserId, pageNum, pageSize){
      const params = {
        orderId: orderId,
        orderUserId: orderUserId,
        pageNum: pageNum,
        pageSize: pageSize
      };

      queryUserOtherOrderPage(params).then(response => {
        this.otherProducts = response.rows;
        this.otherProductsTotal = response.total;
      }).catch(error => {
        console.error('获取用户其他订单失败:', error);
        this.otherProducts = [];
        this.otherProductsTotal = 0;
      });
    },

    // 格式化时间为 年-月-日 时:分:秒
    formatDateTime(dateTime) {
      if (!dateTime) return '-';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 显示修改数量弹窗
    showQuantityEdit(scope) {
      this.quantityForm.itemId = scope.row.itemId;
      // 解析商品信息并处理可能的错误
      let parsedJsonInfo;
      try {
        parsedJsonInfo = JSON.parse(scope.row.jsonInfo);
      } catch (error) {
        parsedJsonInfo = {};
      }

      this.quantityForm.productName = parsedJsonInfo.productName || '';
      this.quantityForm.originalNum = scope.row.num || 0;
      this.quantityForm.newNum = scope.row.num || 0;

      // 处理价格，确保不会为null
      const price = parsedJsonInfo.price || 0;
      this.quantityForm.price = parseFloat(price) || 0;
      this.quantityDialog.open = true;
    },

    // 提交数量修改
    submitQuantityForm() {
      this.$refs["quantityForm"].validate(valid => {
        if (valid) {
          // 验证数量是否发生变化
          if (this.quantityForm.newNum === this.quantityForm.originalNum) {
            this.msgInfo("数量未发生变化，无需修改");
            return;
          }

          updateNumStoreOrderItem(this.quantityForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("数量修改成功");
              updateStoreOrderItemJson(this.order.id, 1);
              this.quantityDialog.open = false;
              this.getOrder(this.order.id);
            } else {
              this.msgError(response.message);
            }
          }).catch(error => {
            this.$message.error('请求失败: ' + error.message)
          });
        }
      });
    },

    openProductSelection() {
      this.productOrderDialog.open = true;

      // 将已有的productId存入查询参数，用于后端过滤 (返回数组格式)
      this.productOrderQueryParams.excludeProductIds = this.items.map(item => item.productId).filter(productId => productId);

      // 加载字典和其他数据
      this.getDicts("store_product_tui_cate").then((response) => {
        this.productTuiCateOptions = response.data;
      });
      this.getDicts("store_product_enable").then((response) => {
        this.isNewOptions = response.data;
        this.isBestOptions = response.data;
        this.isHotOptions = response.data;
        this.isGoodOptions = response.data;
        this.isDisplayOptions = response.data;
      });
      this.getDicts("store_product_type").then((response) => {
        this.productTypeOptions = response.data;
        if (!this.isMedicalMall &&
          this.productTypeOptions.length === 4) {
          //删除后两项
          this.productTypeOptions.splice(2, 2);
        }
      });
      this.getDicts("store_product_is_show").then((response) => {
        this.isShowOptions = response.data;
      });
      getCompanyList().then(response => {
        this.companyOptions = response.data;
      });

      listStore(this.storeForm).then(response => {
        this.storeOptions = response.rows;
      });
      this.getTreeselect();
      this.productOrderGetList();
    },

    /** 商品表格选择变化 */
    handleItemsSelectionChange(selection) {
      this.selectedItems = selection;
    },

    /** 移除选中的商品 */
    removeSelectedProduct() {
      if (this.selectedItems.length === 0) {
        this.msgInfo("请先选择要移除的商品");
        return;
      }

      const that = this;
      this.$confirm('确定要移除选中的 ' + this.selectedItems.length + ' 个商品吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        that.removeProductLoading = true;
        // 收集所有要删除的商品ID
        const deletePromises = that.selectedItems.map(item => {
          return delStoreOrderItem(item.itemId);
        });

        // 并行删除所有选中的商品
        Promise.all(deletePromises).then(responses => {
          // 检查所有删除操作是否成功
          const allSuccess = responses.every(response => response.code === 200);
          if (allSuccess) {
            that.msgSuccess("商品移除成功");
            // 清除选择并刷新订单数据
            that.selectedItems = [];
            updateStoreOrderItemJson(this.order.id, 1);
            that.getOrder(that.order.id);
          } else {
            that.msgError("商品移除失败: " + (responses.message));
          }
        }).catch(error => {
          that.msgError("移除商品失败: " + (error.message || "网络错误"));
        })
      }).catch(() => {
        // 用户取消操作
      });
    },

    /** 查询商品列表 */
    productOrderGetList() {
      this.productOrderLoading = true;
      listStoreProduct(this.productOrderQueryParams).then(response => {
        this.storeProductList = response.rows;
        this.total = response.total;
        this.productOrderLoading = false;
      }).catch(error => {
        console.error('获取商品列表失败:', error);
        this.productOrderLoading = false;
        this.storeProductList = [];
        this.total = 0;
      });
    },

    /** 批量添加商品到订单 */
    handleBatchAdd() {
      if (!this.order || !this.order.id) {
        this.msgInfo("请先选择订单");
        return;
      }

      if (!this.ids || this.ids.length === 0) {
        this.msgInfo("请先选择要添加的商品");
        return;
      }

      const that = this;
      this.$confirm(`确定要将选中的 ${this.ids.length} 个商品添加到订单中吗？`, "确认添加", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info"
      }).then(() => {
        // 获取选中的商品列表
        const selectedProducts = this.storeProductList.filter(product =>
          this.ids.includes(product.productId)
        );

        // 创建批量添加的订单项数据
        const batchAddPromises = selectedProducts.map(product => {
          const orderItemData = {
            orderId: this.order.id,
            orderCode: this.order.orderCode,
            cartId: null,
            productId: product.productId,
            num: 1, // 默认数量为1
            jsonInfo: JSON.stringify({
              image: product.image,
              productId: product.productId,
              num: 1, // 默认数量为1
              productName: product.productName,
              barCode: product.barCode,
              price: product.price,
              sku: product.sku || '默认'
            })
          };
          return addStoreOrderItem(orderItemData);
        });

        // 并行添加所有选中的商品
        Promise.all(batchAddPromises)
          .then(responses => {
            // 检查所有添加操作是否成功
            const allSuccess = responses.every(response => response.code === 200);
            if (allSuccess) {
              that.msgSuccess(`成功添加 ${responses.length} 个商品`);

              // 更新过滤列表，包含新添加的商品ID
              const newIds = selectedProducts.map(p => p.productId);
              const currentIds = this.productOrderQueryParams.excludeProductIds || [];
              const updatedIds = [...new Set([...currentIds, ...newIds])]; // 去重
              this.productOrderQueryParams.excludeProductIds = updatedIds;
              updateStoreOrderItemJson(this.order.id, 1);
              this.productOrderDialog.open = false;
              that.getOrder(that.order.id);
            } else {
              const failedCount = responses.filter(r => r.code !== 200).length;
              that.msgError(`添加失败 ${failedCount} 个商品`);
            }
          })
          .catch(error => {
            that.msgError("批量添加商品失败: " + (error.message || "网络错误"));
          });
      }).catch(() => {
        // 用户取消操作
      });
    },

    // 多选框选中数据
    handleProductSelectionChange(selection) {
      this.ids = selection.map(item => item.productId).filter(id => id); // 过滤空值
      this.single = selection.length !== 1;
      this.multiple = !selection.length
    },
    /** 搜索按钮操作 */
    productOrderHandleQuery() {
      this.productOrderQueryParams.pageNum = 1;
      this.productOrderQueryParams.isShow = 1;
      this.productOrderQueryParams.companyIds = this.companyId + ''
      this.productOrderGetList();
    },
    /** 重置按钮操作 */
    productOrderResetQuery() {
      this.resetForm("productOrderQueryForm");
      // 重置所属公司
      this.companyId = null;
      // 重置所属店铺
      this.productOrderQueryParams.storeIds = null;
      this.productOrderQueryParams.isShow = 1;
      this.productOrderQueryParams.companyIds = null;
      this.productOrderGetList();
    },

    /** 转换商品分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.cateId,
        label: node.cateName,
        children: node.children
      };
    },
    getStatusType(row) {
      // 添加空值检查
      if (!row) {
        return 'info';
      }

      if (row.isAudit == 0) {
        return 'warning';
      }
      // 根据你的业务逻辑返回不同的类型，如：success, danger, info等
      return row.isShow == 1 ? 'success' : 'info';
    },
    getStatusText(row) {
      // 添加空值检查
      if (!row) {
        return '未知状态';
      }

      if (row.isAudit == 0) {
        return '待审核';
      }
      const option = this.isShowOptions.find(item => item.dictValue == row.isShow);
      return option ? option.dictLabel : '未知状态';
    },
    getTreeselect() {
      getAllStoreProductCategory().then(response => {
        this.categoryOptions = [];
        this.categoryOptions = this.handleTree(response.data, "cateId", "pid");
      });
    },

    closeSms() {
      this.addSms.open = false;
    },
    handleSms(mobile) {
      this.addSms.open = true;
      var that = this;
      setTimeout(() => {
        that.$refs.sms.getOrderId(this.orderId, mobile, 2);
      }, 500);

    },
    handlePhone() {
      const id = this.order.id;
      getUserPhone(id).then(response => {
        this.order.userPhone = response.userPhone;
      })
    },
    handleAddress() {
      const id = this.order.id;
      getStoreOrderAddress(id).then(response => {
        this.order.userAddress = response.address;
      })
    },
    showImageDialog() {
      this.dialogVisible = true;
    },
    handleCustomer() {
      var that = this;
      this.customer.open = true;
      setTimeout(() => {
        that.$refs.customerDetails.getDetails(this.order.customerId);
      }, 200);
    },
    handleSelectionChange(selection) {
      this.bindCustomerForm.customerIds = selection.map(item => item.customerId)
    },
    searchCustomer() {
      if (this.bindCustomerForm.mobile == null || this.bindCustomerForm.mobile == "") {
        this.msgError("请输入手机号");
        return;
      }
      var data = {mobile: this.bindCustomerForm.mobile};
      getCustomerListBySearch(data).then(response => {
        this.customers = response.data;
      });
    },
    handleBindCustomer() {
      this.customers = [];
      this.bindCustomerDialog.open = true;
      this.bindCustomerForm.mobile = null;
      this.bindCustomerForm.orderId = this.orderId;
      this.bindCustomerForm.customerIds = null;
    },
    /** 提交按钮 */
    submitBindCustomerForm() {
      this.$refs["bindCustomerForm"].validate(valid => {
        if (valid) {
          bindCustomer(this.bindCustomerForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.bindCustomerDialog.open = false;
            }
          });
        }
      });
    },
    handleCertificates() {
      this.certificateDialig.open = true;
      this.photoArr = null;
    },
    handleConfirm() {
      this.certificateForm.id = this.orderId;
      this.certificateForm.orderCode = this.order.orderCode;
      this.certificateForm.certificates = this.photoArr;
      uploadCredentials(this.certificateForm).then(response => {
        if (response.code === 200) {
          this.msgSuccess("上传成功");
          this.certificateDialig.open = false;
          this.getOrder(this.order.id);
        }
      });
    },
    showExpress() {
      this.expressDialog.open = true;
      this.traces = [];
      getExpress(this.orderId).then(response => {
        this.express = response.data;
        if (this.express != null && this.express.Traces != null) {
          this.traces = this.express.Traces
        }

      });

    },
    editDelivery() {
      this.editDy.open = true;
      this.editDyForm.id = this.order.id;
      this.editDyForm.deliveryId = this.order.deliveryId;
      this.editDyForm.deliverySn = this.order.deliverySn;
      this.editDyForm.senderPhone = this.order.senderPhone;
    },
    submitEditDyForm() {
      this.$refs["editDyForm"].validate(valid => {
        if (valid) {
          if (this.editDyForm.senderPhone == null) {
            this.editDyForm.senderPhone = '';
          }
          updateDeliveryId(this.editDyForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("操作成功");
              this.editDy.open = false;
              this.getOrder(this.order.id);
            }
          });
        }
      });
    },
    districtChange(val) {
      var item = this.district.find((item) => {
        return item.value == val;
      })

      this.editAddressForm.district = item.label;

    },
    cityChange(val) {
      // this.district=this.citys.filter(item => item.value===val )
      this.editAddressForm.districtId = null;
      var item = this.city.find((item) => {
        return item.value == val;
      })
      this.district = item.children;
      this.editAddressForm.city = item.label;


    },
    provinceChange(val) {
      // this.city=this.citys.filter(item => item.value===val )
      this.district = [];
      this.editAddressForm.cityId = null;
      this.editAddressForm.districtId = null;
      var item = this.citys.find((item) => {
        return item.value == val;
      })
      this.city = item.children;
      this.editAddressForm.province = item.label;
    },
    async getCityList() {
      try {
        const res = await getCitys();
        this.citys = res.data;
        this.province = res.data.filter(item => item.pid === 0);
        // 可选：返回数据以便链式调用
        return res.data;
      } catch (error) {
        console.error('获取城市列表失败:', error);
      }
    },
    async handleEditAddress() {
      // 等待城市数据加载完成
      await this.getCityList();

      // 初始化表单数据
      this.editAddressForm.id = this.order.id;
      this.editAddressForm.realName = this.order.realName;
      this.editAddressForm.userPhone = this.order.userPhone;

      // 初始化表单中的地址字段
      this.editAddressForm.provinceId = '';
      this.editAddressForm.cityId = '';
      this.editAddressForm.districtId = '';
      this.editAddressForm.detail = '';

      // 初始化级联数据
      this.city = [];
      this.district = [];

      // 检查是否有地址数据
      if (!this.order?.userAddress) {
        this.editAddress.open = true;
        return;
      }

      // 分割地址
      const addressParts = this.order.userAddress.trim().split(/\s+/);

      // 如果地址格式不正确，将整个地址作为详情
      if (addressParts.length < 4) {
        this.editAddressForm.detail = this.order.userAddress;
        this.editAddress.open = true;
        return;
      }

      // 解析省份
      const provinceName = addressParts[0];
      const province = this.citys?.find(item => item.label === provinceName);

      if (province) {
        this.editAddressForm.provinceId = province.value;

        // 获取城市列表
        if (Array.isArray(province.children)) {
          this.city = province.children.filter(item => item.pid === province.value);

          // 解析城市
          const cityName = addressParts[1];
          const city = this.city.find(item => item.label === cityName);

          if (city) {
            this.editAddressForm.cityId = city.value;

            // 获取区县列表
            if (Array.isArray(city.children)) {
              this.district = city.children.filter(item => item.pid === city.value);

              // 解析区县
              const districtName = addressParts[2];
              const district = this.district.find(item => item.label === districtName);

              if (district) {
                this.editAddressForm.districtId = district.value;
              }
            }
          }
        }
      }

      // 详细地址是剩余部分
      this.editAddressForm.detail = addressParts.slice(3).join(' ');

      // 打开编辑对话框
      this.editAddress.open = true;
    },
    /** 提交按钮 */
    submitEditAddressForm() {
      this.$refs["editAddressForm"].validate(valid => {
        if (valid) {
          this.editAddressForm.userAddress = this.editAddressForm.province + " " + this.editAddressForm.city + " " + this.editAddressForm.district + " " + this.editAddressForm.detail;
          updateStoreOrder(this.editAddressForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.editAddress.open = false;
              this.getOrder(this.order.id);
            }
          });
        }
      });
    },
    handleEditUser() {
      const userId = this.order.userId
      getUser(userId).then(response => {
        this.editUserForm.userId = response.data.userId;
        this.editUserForm.registerDate = response.data.registerDate;
        this.editUserForm.registerCode = response.data.registerCode;
        this.editUserForm.source = response.data.source;
        this.editUser.open = true;
      });
    },
    /** 提交按钮 */
    submitEditUserForm() {
      this.$refs["editUserForm"].validate(valid => {
        if (valid) {
          updateUser(this.editUserForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.editUser.open = false;
              this.getOrder(this.order.id);
            }
          });
        }
      });
    },
    submitEditForm() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          updateStoreOrder(this.editForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("操作成功");
              this.edit.open = false;
              this.getOrder(this.order.id);
            }
          });

        }
      });
    },
    editOrder() {
      this.edit.open = true;
      this.editForm.mark = this.order.mark
      this.editForm.id = this.order.id;
      if (this.order.orderType != null) {
        this.editForm.orderType = this.order.orderType.toString();
      }
      this.editForm.scheduleId = this.order.scheduleId;
      this.editForm.orderVisit = this.order.orderVisit;

    },
    getOrder(orderId) {
      this.orderId = orderId;
      this.certificates = null;
      getStoreOrder(orderId).then(response => {
        this.order = response.order;
        if (response.order.certificates != null) {
          this.certificates = response.order.certificates;
        }
        this.user = response.user;
        this.logs = response.logs;
        this.items = response.items;
        this.payments = response.payments;
        this.customerInfo = response.customer;
        this.auditLogs = response.auditLogs;
        this.afterSales = response.afterSales || {
          auditReasonName: null,
          auditRemark: null,
          reasonValue1: null,
          reasonValue2: null
        };

        // 调用分页接口获取其他订单商品信息
        if (this.order && this.user) {
          this.getUserOtherOrder(this.order.id, this.user.userId, this.otherProductsPage, this.otherProductsPageSize);
        }
      });
    },
    editPayDeliveryHandle() {
      this.payDeliveryForm.id = this.orderId;
      this.payDeliveryForm.payDelivery = this.order.payDelivery || 0.00;
      this.editPayDelivery.open = true;
    },
    // 提交修改代收金额
    submitPayDeliveryForm() {
      this.$refs["payDeliveryForm"].validate(valid => {
        if (valid) {
          editPayDelivery(this.payDeliveryForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.editPayDelivery.open = false;
              this.getOrder(this.order.id);
            } else {
              this.msgError(response.message);
            }
          }).catch(error => {
            this.$message.error('请求失败: ' + error.message)
          });
        }
      });
    },



    // 获取状态标签类型
    getStatusTagType(status) {
      const statusMap = {
        '0': 'info',    // 待支付
        '1': 'warning', // 待发货
        '2': 'primary', // 待收货
        '3': 'success', // 交易完成
        '-1': 'danger', // 退款中
        '-2': 'danger', // 已退款
        '-3': 'info'    // 已取消
      };
      return statusMap[status] || 'info';
    },

    // 获取订单状态文本
    getOrderStatusText(status) {
      const statusTextMap = {
        '0': '待支付',
        '1': '待发货',
        '2': '待收货',
        '3': '交易完成',
        '-1': '退款中',
        '-2': '已退款',
        '-3': '已取消'
      };
      return statusTextMap[status] || '未知状态';
    },

    // 处理其它商品信息分页（带防抖）
    handleOtherProductsPagination: function({ page, limit }) {
      // 使用防抖避免频繁请求
      const debouncedRequest = this.debounce(() => {
        this.otherProductsPage = page;
        this.otherProductsPageSize = limit;
        // 调用后端分页接口
        if (this.order && this.user) {
          this.getUserOtherOrder(this.order.id, this.user.userId, page, limit);
        }
      }, 300);

      debouncedRequest();
    },

    // 解析订单商品JSON数据
    parseOrderItems(orderItemJson) {
      try {
        if (!orderItemJson) return [];

        // 解析订单商品JSON字符串
        const items = JSON.parse(orderItemJson);

        // 提取商品信息
        return items.map(item => {
          try {
            if (item.jsonInfo) {
              return JSON.parse(item.jsonInfo);
            }
            return {};
          } catch (error) {
            return {};
          }
        }).filter(product => product && Object.keys(product).length > 0);
      } catch (error) {
        console.error('解析订单商品数据失败:', error);
        return [];
      }
    },

    // 处理更多订单商品点击事件
    handleMoreOrderItems(row) {
      try {
        // 检查数据是否存在
        if (!row || !row.orderItemJson) {
          this.msgError('数据不完整');
          return;
        }

        // 重置分页状态
        this.productDetailPage = 1;
        this.productDetailPageSize = 5;

        // 获取解析后的商品数据
        const products = this.parseOrderItems(row.orderItemJson);

        if (products.length === 0) {
          this.msgInfo('暂无商品信息');
          return;
        }

        // 设置弹窗数据
        this.currentOrderCode = row.orderCode;
        // 使用 Vue.set 确保响应式更新
        this.$set(this.productDetailDialog, 'products', products);
        this.$set(this.productDetailDialog, 'visible', true);
      } catch (error) {
        this.msgError('获取商品信息失败: ' + error.message);
      }
    },

    // 处理商品详情分页（带节流）
    handleProductDetailPagination: function({ page, limit }) {
      // 使用节流避免频繁切换
      const throttledRequest = this.throttle(() => {
        this.productDetailPage = page;
        this.productDetailPageSize = limit;
        // 强制更新视图
        this.$forceUpdate();
      }, 200);

      throttledRequest();
    },

    // 处理商品详情弹窗关闭
    handleProductDetailClose() {
      this.productDetailDialog.visible = false;
      // 重置分页
      this.productDetailPage = 1;
      this.productDetailPageSize = 5;
    },

  }
};
</script>
<style scoped>
.order-content {
  margin: 10px;
}

.operate-container {
  background: #F2F6FC;
  height: 60px;
  margin: -20px -20px 0;
  line-height: 60px;
}

.operate-button-container {
  float: right;
  margin-right: 20px
}

.select-product-btn {
  float: right;
  margin-top: -5px;
  margin-right: 15px;
  background: linear-gradient(135deg, #409EFF, #337AB7);
  border: none;
  color: white;
  border-radius: 6px;
  padding: 8px 16px;
  font-weight: 500;
  box-shadow: 0 3px 6px rgba(64, 158, 255, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.select-product-btn:hover {
  background: linear-gradient(135deg, #66b1ff, #409EFF);
  transform: translateY(-2px);
  box-shadow: 0 5px 12px rgba(64, 158, 255, 0.35);
}

.select-product-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.select-product-btn:focus {
  outline: none;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.3);
}

.select-product-btn:disabled {
  background: linear-gradient(135deg, #a0cfff, #b3d8ff);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.remove-product-btn {
  float: right;
  margin-top: -5px;
  margin-right: 15px;
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  border: none;
  color: white;
  border-radius: 6px;
  padding: 8px 16px;
  font-weight: 500;
  box-shadow: 0 3px 6px rgba(255, 107, 107, 0.15);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.remove-product-btn:hover {
  background: linear-gradient(135deg, #ff5252, #e74c3c);
  transform: translateY(-2px);
  box-shadow: 0 5px 12px rgba(255, 107, 107, 0.25);
}

.remove-product-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(255, 107, 107, 0.2);
}

.remove-product-btn:focus {
  outline: none;
  box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.3);
}

.remove-product-btn:disabled {
  background: linear-gradient(135deg, #ffcccc, #f8d7da);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.quantity-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 0 5px;
}

.quantity-display {
  display: flex;
  align-items: center;
  gap: 4px; /* 缩小数量与按钮之间的间距 */
}

.quantity-value {
  font-weight: 600;
  color: #606266;
  background-color: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
  min-width: 40px;
  text-align: center;
}

.edit-quantity-btn {
  margin-left: 4px; /* 缩小左边距 */
  padding: 4px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #409eff;
  background: transparent;
  cursor: pointer;
  transition: all 0.2s ease;
}

.edit-quantity-btn:hover {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
  color: #66b1ff;
  transform: translateY(-1px);
}

.edit-quantity-btn i {
  margin-right: 2px;
  font-size: 12px;
}

.edit-quantity-btn:hover {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
  color: #66b1ff;
  transform: translateY(-1px);
}

.edit-quantity-btn i {
  margin-right: 2px;
  font-size: 12px;
}

.dialog-product-name {
  font-weight: 500;
  color: #303133;
  word-break: break-all;
  max-width: 350px;
  display: inline-block;
  vertical-align: middle;
}

.more-products-btn:hover {
  background: linear-gradient(135deg, #66b1ff, #409eff);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.more-products-btn i {
  margin-right: 4px;
}

/* 历史订单商品信息样式 */
.order-code-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.order-code-text {
  font-weight: 500;
  color: #606266;
  font-family: 'Monaco', 'Consolas', monospace;
}

.time-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  color: #606266;
}

.amount-cell, .deposit-cell {
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 2px;
}

.amount-symbol, .deposit-symbol {
  color: #606266;
  font-weight: 600;
  font-size: 12px;
}

.amount-value, .deposit-value {
  color: #606266;
  font-weight: 600;
  font-size: 14px;
}

.status-cell {
  display: flex;
  justify-content: center;
}

.product-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px;
}

.product-name {
  font-weight: 500;
  color: #303133;
  text-align: center;
  word-break: break-all;
  max-width: 100%;
}

.product-count {
  font-size: 12px;
  color: #606266;
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 12px;
}

.no-product {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
}

.action-buttons {
  margin-top: 8px;
}

.detail-btn {
  padding: 4px 12px;
  font-size: 12px;
}

/* 统一表格样式 */
.unified-table ::v-deep .el-table__header th {
  background: #f8f9fa !important;
  color: #303133 !important;
  font-weight: 600 !important;
}

.unified-table ::v-deep .el-table__body td {
  color: #606266 !important;
}

/* 统一单元格样式 */
.unified-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 4px;
}

.order-code-cell {
  font-family: 'Monaco', 'Consolas', monospace;
}

.order-code-text {
  font-weight: 500;
  color: #606266;
}

.time-cell {
  color: #606266;
}

.amount-cell, .deposit-cell {
  gap: 2px;
}

.amount-symbol, .deposit-symbol {
  color: #606266;
  font-weight: 600;
  font-size: 12px;
}

.amount-value, .deposit-value {
  color: #606266;
  font-weight: 600;
  font-size: 14px;
}

.sales-cell {
  gap: 4px;
}

.sales-cell i {
  color: #409eff;
}

.sales-name {
  color: #606266;
  font-size: 13px;
}

.status-cell {
  justify-content: center;
}

/* 商品预览样式 */
.product-preview {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 8px;
  border: 1px solid #e9ecef;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
  max-width: 300px;
}

.product-preview:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  border-color: #409eff;
}

.unified-product-name {
  font-weight: 500;
  color: #409eff;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 13px;
}

.product-count {
  font-size: 12px;
  color: #909399;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 10px;
}

.product-name {
  font-weight: 500;
  color: #409eff;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-product {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 12px;
  color: #909399;
  font-style: italic;
}

.no-product i {
  font-size: 16px;
}

/* 操作按钮样式 */
.action-buttons {
  margin-top: 8px;
}

.unified-btn {
  background: linear-gradient(135deg, #409eff, #337ab7);
  border: none;
  color: white;
  border-radius: 16px;
  padding: 5px 12px;
  font-size: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.unified-btn:hover {
  background: linear-gradient(135deg, #66b1ff, #409eff);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.unified-btn i {
  margin-right: 4px;
}

/* 统一商品详情弹窗样式 */
.unified-detail-dialog ::v-deep .el-dialog__header {
  background: white;
  color: #303133;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.unified-detail-dialog ::v-deep .el-dialog__title {
  color: #303133;
  font-weight: 600;
  font-size: 18px;
}

/* 自定义弹窗标题样式 */
.dialog-custom-title {
  .font-small {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
  }
}

.unified-detail-dialog ::v-deep .el-dialog__headerbtn .el-dialog__close {
  color: #909399;
}

.unified-detail-dialog ::v-deep .el-dialog__headerbtn .el-dialog__close:hover {
  color: #409eff;
}

.compact-dialog-table ::v-deep .el-table__header th {
  background: #f8f9fa !important;
  color: #303133 !important;
  font-weight: 600 !important;
  padding: 6px 0 !important;
}

.compact-dialog-table ::v-deep .el-table__body td {
  padding: 4px 0 !important;
}

.dialog-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-product-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
}

.dialog-product-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
  border-radius: 6px;
}

.dialog-product-info {
  padding: 8px;
}

.product-name-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  width: 100%;
}

.dialog-product-name {
  font-weight: 500;
  color: #409eff;
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
  display: block;
  width: 100%;
}

.dialog-price-cell, .dialog-sku-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2px;
}

.dialog-pagination {
  margin-top: 3px;
  padding: 6px 10px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 4px;
  border: 1px solid #dee2e6;
}

.dialog-pagination ::v-deep .el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}

dialog-pagination ::v-deep .el-pagination button,
dialog-pagination ::v-deep .el-pagination .el-pager li {
  min-width: 24px;
  height: 24px;
  line-height: 24px;
}

/* 表格内容区域右下角容器 */
.table-bottom-right-container {
  position: relative;
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

/* 包装分页组件的容器 */
.dialog-pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background: transparent;
  padding: 0;
  border-radius: 0;
  box-shadow: none;
}

/* 分页组件样式 */
.dialog-pagination {
  display: inline-block;
  background: transparent;
  border: none;
  padding: 0;
  margin: 0;
}

.dialog-pagination ::v-deep .el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  background: transparent;
  padding: 0;
  border: none;
}

.dialog-pagination ::v-deep .el-pagination button,
.dialog-pagination ::v-deep .el-pagination .el-pager li {
  min-width: 24px;
  height: 24px;
  line-height: 24px;
  background: white;
  border: 1px solid #dcdfe6;
}

/* 关闭按钮区域样式 */
.dialog-close-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 透明关闭按钮样式 */
.transparent-close-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  border: none;
  color: white;
  padding: 8px 20px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(255, 107, 107, 0.3);
}

.transparent-close-btn:hover {
  background: linear-gradient(135deg, #ff5252, #e53935);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
}

.transparent-close-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(255, 107, 107, 0.3);
}

.transparent-close-btn i {
  margin-right: 6px;
  font-size: 16px;
  transition: transform 0.3s ease;
}

.transparent-close-btn:hover i {
  transform: rotate(90deg);
}

.compact-close-btn i {
  font-size: 14px;
}

/* 商品详情弹窗样式 */
.product-detail-dialog .el-dialog__header {
  background: linear-gradient(135deg, #409eff, #337ab7);
  color: white;
  padding: 20px;
}

.product-detail-dialog .el-dialog__title {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

.product-detail-dialog .el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.product-detail-dialog .el-dialog__headerbtn .el-dialog__close:hover {
  color: #ffd04b;
}

/* 商品信息展示样式 */
.product-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px;
}

.product-name {
  font-weight: 500;
  color: #303133;
  text-align: center;
  word-break: break-all;
  max-width: 100%;
}

.product-count {
  font-size: 12px;
  color: #606266;
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 12px;
}

.no-product {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
}

.action-buttons {
  margin-top: 8px;
}

.detail-btn {
  padding: 4px 12px;
  font-size: 12px;
}

/* 统一对齐样式 */
.text-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 4px;
  height: 100%;
}

.text-content {
  font-size: 13px;
  color: #606266;
  text-align: center;
  word-break: break-all;
}

.currency-symbol {
  color: #606266;
  font-weight: 600;
  font-size: 12px;
}

.number-content {
  color: #606266;
  font-weight: 600;
  font-size: 14px;
}

.tag-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 8px 4px;
}

.time-icon {
  color: #606266;
  font-size: 14px;
}

</style>
