<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-if="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>
           <el-tag v-if="order.deliveryExceptionStatus === 1" type="danger" size="mini" style="margin-left: 8px;">物流异常</el-tag>
        </span>
        <div class="operate-button-container" v-if="deliveryAbnormalMode && order.deliveryExceptionStatus !== 2" v-hasPermi="['store:storeDeliveryAbnormalOrder:handle']">
          <el-button size="mini" type="danger" @click="openDeliveryExceptionDialog">确认状态</el-button>
        </div>
        <div class="operate-button-container" v-if="!deliveryAbnormalMode" >
          <el-button size="mini" @click="editOrder()"  v-hasPermi="['store:storeOrder:edit']" >修改订单</el-button>
        </div>
        <div class="operate-button-container"  v-hasPermi="['store:storeOrder:finishOrder']" v-if="!deliveryAbnormalMode && order.status===2">
          <el-button size="mini" @click="finishOrder()" >确认收货</el-button>
        </div>
        <div class="operate-button-container" v-if="!deliveryAbnormalMode && (order.status==1||order.status==2)"  v-hasPermi="['store:storeOrder:refundOrderMoney']"  >
          <el-button size="mini" @click="refundOrderMoney()" >退款</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-if="!deliveryAbnormalMode && order.tuiMoneyStatus==0"  v-hasPermi="['store:storeOrder:editTuiMoney']"  >
          <el-button size="mini" @click="editTuiMoney1()" >解冻</el-button>
        </div>
        <div class="operate-button-container" v-if="!deliveryAbnormalMode && order.tuiMoneyStatus==1"  v-hasPermi="['store:storeOrder:editTuiMoney']"  >
          <el-button size="mini" @click="editTuiMoney2()" >冻结</el-button>
        </div>

        <div class="operate-button-container" v-if="!deliveryAbnormalMode && order.status==3&&order.tuiMoneyStatus==null"  v-hasPermi="['store:storeOrder:addTuiMoney']"  >
          <el-button size="mini" @click="addTuiMoney()" >分佣</el-button>
        </div>

<!--        <div class="operate-button-container" v-if="order.extendOrderId!=null"  v-hasPermi="['store:storeOrder:getEroOrder']"  >
          <el-button size="mini" @click="showErpOrder()" >查看ERP订单信息</el-button>
        </div>-->
        <div class="operate-button-container" v-if="!deliveryAbnormalMode && order.isPayRemain!=null&&order.isPayRemain==1"  v-hasPermi="['store:storeOrder:auditPayRemain']"  >
          <el-button size="mini" @click="auditPayRemain()" >尾款审核</el-button>
        </div>
        <div class="operate-button-container" v-if="!deliveryAbnormalMode" >
          <el-button size="mini" @click="editDelivery()"  v-hasPermi="['store:storeOrder:editDeliveryId']" >修改物流</el-button>
        </div>
        <div class="operate-button-container" v-if="!deliveryAbnormalMode && order.status===0" >
          <el-button size="mini" @click="editPayPostageOpen()"  v-hasPermi="['store:storeOrder:edit']" >修改运费</el-button>
        </div>
        <div class="operate-button-container" v-if="!deliveryAbnormalMode && order.status >=1 && order.extendOrderId == null && order.deliveryId == null"  v-hasPermi="['store:storeOrder:createErpOrder']"  >
          <el-button size="mini" @click="addErpOrder()" >创建ERP订单信息</el-button>
        </div>
        <!-- <div class="operate-button-container" v-show="order.status===2">
          <el-button size="mini"  >去发货</el-button>
          <el-button size="mini" >备注订单</el-button>
        </div>
        <div class="operate-button-container" v-show="order.status===4">
          <el-button size="mini"  >订单跟踪</el-button>
          <el-button size="mini"  disabled>备注订单</el-button>
        </div> -->
      </div>
      <div style="margin: 20px 0px">
        <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="支付方式"  >
              <el-tag prop="payType" v-for="(item, index) in payTypeOptions"    v-if="order!=null&&order.payType==item.dictValue">{{item.dictLabel}}
              </el-tag>
            </el-descriptions-item>
<!--            <el-descriptions-item label="订单类型"  >
              <el-tag prop="orderType" v-for="(item, index) in orderTypeOptions"    v-if="order!=null&&order.orderType==item.dictValue">{{item.dictLabel}}</el-tag>
            </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">
                  <el-tag prop="deliveryId" v-for="(item, index) in deliveryStatusOptions"    v-if="order!=null&&order.deliveryStatus==item.dictValue">{{item.dictLabel}}</el-tag>
                </span>
            </el-descriptions-item>
            <el-descriptions-item :label="deliveryAbnormalMode ? '异常状态' : '物流跟踪状态'"  >
                <span v-if="order!=null">
                  <template v-if="deliveryAbnormalMode">{{ formatDeliveryTypeText(order.deliveryType) }}</template>
                  <template v-else>
                    <el-tag prop="deliveryId" v-for="(item, index) in deliveryTypeOptions" v-if="order.deliveryType==item.dictValue">{{item.dictLabel}}</el-tag>
                  </template>
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="处理状态" v-if="deliveryAbnormalMode && order!=null">
              <el-tag v-if="order.deliveryExceptionStatus === 1" type="danger" size="mini">待处理</el-tag>
              <el-tag v-else-if="order.deliveryExceptionStatus === 2" type="success" size="mini">已处理</el-tag>
              <span v-else>-</span>
            </el-descriptions-item>
            <el-descriptions-item label="异常备注" v-if="deliveryAbnormalMode && order!=null">
              <span>{{ order.deliveryExceptionRemark || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="物流异常备注" v-if="!deliveryAbnormalMode && order!=null && order.deliveryExceptionRemark">
                <span>{{ order.deliveryExceptionRemark }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="物流结算费用"  >
                <span v-if="order!=null&&order.deliveryPayMoney!=null ">
                  {{order.deliveryPayMoney.toFixed(2) }}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="快递帐单日期"  >
                <span v-if="order!=null ">
                  {{order.deliveryTime }}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="快递结算日期"  >
                <span v-if="order!=null ">
                  {{order.deliveryPayTime }}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="推广佣金"  >
                <span v-if="order!=null ">
                  {{order.tuiMoney }}
                </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 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="虚拟号码"  >
                <span v-if="order != null ">
                  {{order.virtualPhone }}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="发货人手机号"  >
                <span v-if="order != null ">
                  {{order.senderPhone }}
                </span>
            </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="档期归属"  >
              <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="销售名称" 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="afterSales!=null && afterSales.auditReasonName">
                <span>
                  {{ afterSales.auditReasonName }}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="财务审核备注" v-if="afterSales!=null && afterSales.auditRemark">
                <span>
                  {{ afterSales.auditRemark }}
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="退款类型" v-if="isRefundedOrder">
                <span>{{ refundScopeType || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="退款金额" v-if="isRefundedOrder">
                <span>{{ displayRefundAmount != null ? displayRefundAmount : '-' }}</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="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).barCode}}</p>
          </template>
        </el-table-column>
        <el-table-column label="商品组合编码" width="300" align="center">
          <template slot-scope="scope">
            <p>{{JSON.parse(scope.row.jsonInfo).groupBarCode}}</p>
          </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="处方药" width="240" align="center">
          <template slot-scope="scope">
            {{scope.row.isPrescribe!=null&&scope.row.isPrescribe==1?'是':'否'}}
          </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!=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 && !isBeiJingZhuoMei">
                ￥{{order.payMoney.toFixed(2)}}
              </span>
            <span v-else-if="order!=null && isBeiJingZhuoMei && order.status != -3">
                ￥{{order.payMoney.toFixed(2)}}
              </span>
              <span v-else>
                ￥0
              </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!=null">
                ￥{{order.couponPrice.toFixed(2)}}
              </span>
              <span v-else>￥0.00</span>
          </el-descriptions-item>
      </el-descriptions>

      <div style="margin-top: 20px">
        <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 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">
        <!-- <svg-icon icon-class="marker" style="color: #606266"></svg-icon> -->
        <span class="font-small">分佣信息</span>
      </div>
      <el-table
        border
        :data="tuiMoneyLogs"
        size="small"
                style="width: 100%;margin-top: 20px" >
          <el-table-column label="公司名称" align="center" prop="companyName" width="120px" />
          <el-table-column label="金额" align="center" prop="money" />
          <el-table-column label="余额" align="center" prop="balance" />
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column label="备注" align="center" prop="remark" />
      </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="status" >
           <el-select style="width:220px" v-model="editForm.status" placeholder="请选择状态" clearable size="small">
            <el-option key="0"  label="待支付" value="0" />
            <el-option key="1"  label="待发货" value="1" />
             <el-option key="2"  label="待收货" value="2" />
             <el-option key="3"  label="交易成功" value="3" />
             <el-option key="-1"  label="退款中" value="-1" />
             <el-option key="-2"  label="已退款" value="-2" />
             <el-option key="-3"  label="已取消" value="-3" />
           </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="userAddress"  >
          <el-input v-model="editForm.userAddress" placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item label="erp单号" prop="extendOrderId"  >
          <el-input v-model="editForm.extendOrderId" placeholder="请输入" />
        </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="editDy.title" :visible.sync="editDy.open" width="600px" append-to-body>
      <el-form ref="editDyForm" :model="editDyForm" :rules="editDyRules" label-width="120px">
<!--      <div  v-hasPermi="['store:storeOrder:updateErpOrder']"  style="margin-bottom: 20px;" >
        <el-button size="mini" @click="updateErpOrder" >同步物流单号信息</el-button>
      </div>-->
        <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-item label="虚拟手机号" prop="virtualPhone"  >
          <el-input v-model="editDyForm.virtualPhone" placeholder="请输入虚拟手机号" />
        </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="expressDialog.title" :visible.sync="expressDialog.open" width="600px" append-to-body>
      <div  v-hasPermi="['store:storeOrder:syncExpress']"  >
        <el-button size="mini" @click="syncExpress()" >同步快递鸟物流状态</el-button>
      </div>
      <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="erpDialog.title" :visible.sync="erpDialog.open" width="600px" append-to-body>
      <div v-if="order!=null&&order.extendOrderId!=null&&order.status==1"  v-hasPermi="['store:storeOrder:updateExpress']"  >
        <el-button size="mini" @click="updateExpress()" >同步物流发货</el-button>
      </div>
      <div class="table-layout"  v-if="erpOrder!=null">
        <el-row>
          <el-col :span="6" class="table-cell-title">订单编号</el-col>
          <el-col :span="6" class="table-cell-title">是否代收</el-col>
          <el-col :span="6" class="table-cell-title">快递编号</el-col>
          <el-col :span="6" class="table-cell-title">快递名称</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">
            {{erpOrder.code}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.cod?'是':'否'}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.express_code}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.express_name}}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell-title">收货人</el-col>
          <el-col :span="6" class="table-cell-title">电话</el-col>
          <el-col :span="6" class="table-cell-title">地址</el-col>
          <el-col :span="6" class="table-cell-title">运单号</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">
            {{erpOrder.receiver_name}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.receiver_mobile}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.receiver_address}}
          </el-col>
          <el-col :span="6" class="table-cell">
            {{erpOrder.deliverys!=null&&erpOrder.deliverys.length>0?erpOrder.deliverys[0].mail_no:''}}
          </el-col>

        </el-row>
      </div>
    </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="handleSelectionChange">
        <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 :title="editPayPostageDialog.title" :visible.sync="editPayPostageDialog.open" width="500px" append-to-body>
      <el-form ref="payPostageForm" :model="payPostageForm" :rules="payPostageRules" label-width="120px">
        <el-form-item label="运费（元）" prop="payPostage">
          <el-input-number
            v-model="payPostageForm.payPostage"
            :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="editPayPostageDialog.open = false">取 消</el-button>
        <el-button type="primary" @click="submitPayPostageForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="确认状态" :visible.sync="deliveryExceptionDialog.open" width="480px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="异常状态">
          <span>{{ formatDeliveryTypeText(order && order.deliveryType) }}</span>
        </el-form-item>
        <el-form-item label="异常备注">
          <el-input
            v-model="deliveryExceptionDialog.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入异常备注（非必填）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deliveryExceptionDialog.open = false">取 消</el-button>
        <el-button type="primary" @click="submitDeliveryExceptionConfirm">确 认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addTuiMoney,
  auditPayRemain,
  createErpOrder,
  editTuiMoney,
  finishOrder,
  getEroOrder,
  getExpress,
  getStoreOrder,
  getStoreOrderAddress,
  getStoreOrderPhone,
  refundOrderMoney,
  syncExpress,
  updateDeliveryId,
  updateErp,
  updateExpress,
  updateStoreOrder,
  updateStoreOrderItemJson,
  editPayDelivery,
  editPayPostage
} from "@/api/hisStore/storeOrder";
import { getDeliveryAbnormalOrder, handleDeliveryException } from "@/api/hisStore/storeDeliveryAbnormalOrder";
import {listStoreProduct} from "@/api/hisStore/storeProduct";
import {getTcmScheduleList} from "@/api/company/schedule";
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 Material from '@/components/Material'
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{ getSignProjectName } from '@/api/course/qw/courseWatchLog'


export default {
  name: "order",
  props: {
    deliveryAbnormalMode: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Treeselect,
    Editor,
    Material,
    singleImg,
  },
  data() {
    return {
      isBeiJingZhuoMei:false,
      zdyInfo: process.env.VUE_APP_FS_USER_INFO,
      isMedicalMall: this.$store.state.user.medicalMallConfig.medicalMall,
      dialogVisibleImage: false,
      createTypeOptions:[],
      deliveryStatusOptions:[],
      deliveryTypeOptions:[],
      scheduleOptions:[],
      schedules:[],
      // 遮罩层
      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:[],
      orderId:null,
      // 选中的商品列表
      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:[],
        isAudit: 1,
      },
      erpDialog:{
        title:"ERP订单信息",
        open:false,
      },
      expressDialog:{
        title:"物流信息",
        open:false,
      },
      edit:{
        title:"",
        open:false,
      },
      editDy:{
        title:"修改物流单号",
        open:false,
      },
      productOrderDialog:{
        title:"商品选择",
        open:false,
      },
      editDyForm:{
        deliverySn:null,
        deliveryId:null,
        senderPhone: null,
        virtualPhone: null,
      },
      editForm:{
        orderType:null,
        status:null,
        userAddress:null,
        scheduleId:null,
        mark:"",
      },

      editDyRules:{
        deliverySn: [
          { required: true, message: "物流公司不能为空", trigger: "blur" }
        ],
        deliveryId: [
          { required: true, message: "物流单号不能为空", trigger: "blur" }
        ],
      },
      editRules:{
        userAddress: [
          { required: true, message: "收货地址不能为空", trigger: "blur" }
        ],

      },
      orderTypeOptions:[],
      payTypeOptions:[],
      statusOptions:[],
      certificates:null,
      orderStatus:null,
      order:null,
      user:{},
      logs:[],
      items:[],
      express:null,
      traces:[],
      payments:[],
      tuiMoneyLogs:[],
      erpOrder:null,
      auditLogs: [],
      afterSales: null,
      // 数量修改弹窗相关数据
      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" }
        ]
      },
      // 修改代收金额相关参数
      editPayDelivery: {
        title: "修改代收金额",
        open: false,
      },
      payDeliveryForm: {
        id: null,
        payDelivery: 0.00
      },
      payDeliveryRules: {
        payDelivery: [
          { required: true, message: "代收金额不能为空", trigger: "blur" },
        ]
      },
      editPayPostageDialog: {
        title: "修改运费",
        open: false
      },
      payPostageForm: {
        id: null,
        payPostage: 0.00
      },
      payPostageRules: {
        payPostage: [
          { required: true, message: "运费不能为空", trigger: "blur" }
        ]
      },
      deliveryExceptionDialog: {
        open: false,
        remark: ''
      },
      // 删除商品相关
      removeProductLoading: false
    };
  },
  computed: {
    isRefundedOrder() {
      if (!this.order || this.order.status == null) {
        return false;
      }
      const status = Number(this.order.status);
      return status === -1 || status === -2;
    },
    displayRefundAmount() {
      if (!this.isRefundedOrder) {
        return null;
      }
      let amount = null;
      if (this.afterSales && this.afterSales.refundAmount != null) {
        amount = this.afterSales.refundAmount;
      } else if (this.order.refundPrice != null) {
        amount = this.order.refundPrice;
      }
      if (amount == null) {
        return null;
      }
      return Number(amount).toFixed(2);
    },
    refundScopeType() {
      if (!this.isRefundedOrder) {
        return '';
      }
      const refundRaw = this.afterSales && this.afterSales.refundAmount != null
        ? this.afterSales.refundAmount
        : this.order.refundPrice;
      const payRaw = this.order.payMoney != null ? this.order.payMoney : this.order.payPrice;
      if (refundRaw == null || payRaw == null) {
        return '';
      }
      return Number(refundRaw) < Number(payRaw) ? '部分退款' : '全额退款';
    }
  },
  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("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;
    });
    this.checkProjectName()
  },
  methods: {
    // 显示修改数量弹窗
    showQuantityEdit(scope) {
      this.quantityForm.itemId = scope.row.itemId;
      // 解析商品信息并处理可能的错误
      let parsedJsonInfo;
      try {
        parsedJsonInfo = JSON.parse(scope.row.jsonInfo);
      } catch (error) {
        console.error('解析商品信息失败:', 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(() => {
        // 用户取消操作
      });
    },

    // 多选框选中数据
    handleSelectionChange(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.isAudit == 0) {
        return 'warning';
      }
      // 根据你的业务逻辑返回不同的类型，如：success, danger, info等
      return row.isShow == 1 ? 'success' : 'info';
    },
    getStatusText(row) {
      if (row.isAudit == 0) {
        return '待审核';
      }
      const option = this.isShowOptions.find(item => item.dictValue == row.isShow);
      return option ? option.dictLabel : '未知状态';
    },

    handleAddress(){
        const id = this.order.id;
        getStoreOrderAddress(id).then(response =>{
            this.order.userAddress = response.address;
        })
      },
      handlePhone(){
        const id = this.order.id;
        getStoreOrderPhone(id).then(response =>{
            this.order.userPhone = response.userPhone;
        })
      },
    showImageDialog() {
      this.dialogVisible = true;
    },
    syncExpress(){
      var that=this;
        this.$confirm('确定同步物流状态吗', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={orderId:that.order.id}
          return syncExpress(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getOrder(this.order.id);
        }).catch(function() {});
    },
    updateErpOrder(){
      var that=this;
        this.$confirm('确定同步物流单号信息吗', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={orderId:that.order.id}
          return updateErp(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getOrder(this.order.id);
          this.editDy.open = false
        }).catch(function() {});
    },
    updateExpress(){
      var that=this;
        this.$confirm('确定同步物流信息吗，同步后将自动发货', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={orderId:that.order.id}
          return updateExpress(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getOrder(this.order.id);
        }).catch(function() {});
    },
    showErpOrder(){
      this.erpDialog.open=true;
      var data={extendOrderId:this.order.extendOrderId};
      getEroOrder(data).then(response => {
          this.erp = response.data;
          if(response.data.orders!=null&&response.data.orders.length==1){
            this.erpOrder=response.data.orders[0]
          }

      });
    },
    showExpress(){
      this.expressDialog.open=true;
      getExpress(this.orderId).then(response => {
          this.express = response.data;
          if(this.express!=null&&this.express.Traces!=null){
              this.traces=this.express.Traces
          }

      });

    },
    getTreeselect() {
      getAllStoreProductCategory().then(response => {
      this.categoryOptions = [];
        this.categoryOptions=this.handleTree(response.data, "cateId", "pid");
      });
    },
    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);
            }
          });

        }
      });
    },
    submitEditDyForm(){
        this.$refs["editDyForm"].validate(valid => {
        if (valid) {
          if (!this.editDyForm.virtualPhone) {
            this.editDyForm.virtualPhone = '';//如果为null就设置为空字符串
          }
          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);
            }
          });

        }
      });
    },
    editTuiMoney1(){
      var that=this;
        this.$confirm('是否冻结此订单推广佣金吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={orderId:that.order.id}
          return editTuiMoney(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getOrder(this.order.id);
        }).catch(function() {});
    },
    editTuiMoney2(){
      var that=this;
        this.$confirm('是否解冻此订单推广佣金吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={orderId:that.order.id}
          return editTuiMoney(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getOrder(this.order.id);
        }).catch(function() {});
    },
    addTuiMoney(){
      var that=this;
        this.$confirm('确定手动分佣金吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={orderId:that.order.id}
          return addTuiMoney(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getOrder(this.order.id);
        }).catch(function() {});
    },
    refundOrderMoney(){
        var that=this;
        this.$confirm('确认退款吗', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={orderId:that.order.id}
          return refundOrderMoney(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getOrder(this.order.id);
        }).catch(function() {});
    },
    finishOrder(){
        var that=this;
        this.$confirm('是否确认客户已收货?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={orderId:that.order.id}
          return finishOrder(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getOrder(this.order.id);
        }).catch(function() {});
    },
    auditPayRemain(){
        var that=this;
        this.$confirm('是否确认已收尾款?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={orderId:that.order.id}
          return auditPayRemain(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getOrder(this.order.id);
        }).catch(function() {});
    },
    editOrder(){
        this.edit.open=true;
        this.editForm.id=this.order.id;
        this.editForm.mark=this.order.mark
        this.editForm.orderType=this.order.orderType.toString();
        this.editForm.status = this.order.status.toString();
        this.editForm.userAddress = this.order.userAddress.toString();
        this.editForm.scheduleId = this.order.scheduleId;
        // this.editForm.extendOrderId = this.order.extendOrderId.toString();

    },
    //推送管易按钮
    addErpOrder(){
        var that=this;
        this.$confirm('是否确认推送erp?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var data={orderCode:that.order.orderCode}
          return createErpOrder(data);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getOrder(this.order.id);
        }).catch(function() {});
    },
    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;
      this.editDyForm.virtualPhone = this.order.virtualPhone;
    },
    getOrder(orderId){
        this.orderId=orderId;
        this.certificates = null;
        const getFn = this.deliveryAbnormalMode ? getDeliveryAbnormalOrder : getStoreOrder;
        getFn(orderId).then(response => {
            this.order = response.order;
            if(response.order.certificates != null){
              this.certificates = response.order.certificates;
            }
            if(response.order.status != null){
              this.orderStatus = response.order.status;
            }
            this.user = response.user;
            this.logs = response.logs;
            this.items = response.items;
            this.payments=response.payments;
            this.tuiMoneyLogs=response.tuiMoneyLogs;
            this.auditLogs = response.auditLogs;
            this.afterSales = response.afterSales;
        });
     },
    formatDeliveryTypeText(value) {
      if (!value) {
        return '-';
      }
      const item = this.deliveryTypeOptions.find(d => d.dictValue === value || d.dictValue === String(value));
      return item ? `${item.dictValue} ${item.dictLabel}` : value;
    },
    openDeliveryExceptionDialog() {
      this.deliveryExceptionDialog.remark = this.order.deliveryExceptionRemark || '';
      this.deliveryExceptionDialog.open = true;
    },
    submitDeliveryExceptionConfirm() {
      handleDeliveryException({
        orderId: this.order.id,
        deliveryExceptionStatus: 2,
        deliveryExceptionRemark: this.deliveryExceptionDialog.remark
      }).then(() => {
        this.msgSuccess('处理成功');
        this.deliveryExceptionDialog.open = false;
        this.getOrder(this.order.id);
        if (this.deliveryAbnormalMode) {
          this.$emit('refresh');
        }
      });
    },
    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)
          });
        }
      });
    },
    editPayPostageOpen() {
      this.payPostageForm.id = this.orderId;
      this.payPostageForm.payPostage = this.order.payPostage != null ? Number(this.order.payPostage) : 0;
      this.editPayPostageDialog.open = true;
    },
    submitPayPostageForm() {
      this.$refs["payPostageForm"].validate(valid => {
        if (valid) {
          editPayPostage(this.payPostageForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.editPayPostageDialog.open = false;
              this.getOrder(this.order.id);
            } else {
              this.msgError(response.msg || response.message);
            }
          }).catch(error => {
            this.$message.error("请求失败: " + (error.message || ""));
          });
        }
      });
    },
    checkProjectName() {
      getSignProjectName().then(r=>{
        this.isBeiJingZhuoMei = r.signProjectName === '北京卓美';
      });
    },
  },
};
</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
}
.container {
  position: relative;
}
.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;
}
</style>
