<!-- 收银台订单-->
<template>
  <div>
    <div  class="cot-box">
      <div>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="" prop="staffId">
            <el-select
              v-model="queryParams.staffId"
              clearable
              placeholder="请选择操作人"
            >
              <el-option v-for="item in staffList" :key="item.id" :label="item.realName" :value="item.id">
                <span style="float: left">{{ item.realName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.mobile }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-input v-model="queryParams.orderNo" clearable placeholder="请输入订单号"></el-input>
          </el-form-item>
          <el-form-item label="" prop="payType">
            <el-select
              v-model="queryParams.payType"
              clearable
              placeholder="请选择支付方式"
            >
              <el-option v-for="item in payList"
                         :key="item.id"
                         :label="item.dictLabel"
                         :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-input v-model="queryParams.payUser" clearable placeholder="请输入付款用户"></el-input>
          </el-form-item>
          <el-form-item label="">

            <el-date-picker
              v-model="beginTime"
              style="width: 140px"
              type="date"
              placeholder="开始日期">
            </el-date-picker>
            至
            <el-date-picker
              v-model="endTime"
              style="width: 140px"
              type="date"
              placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item style="float: right">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="exportExcelCashier()">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <div class="box-gang">
          <div class="box1">
            <div class="size-bole">
              {{ orderStatistics.theTotalAmountOfTheOrder ? orderStatistics.theTotalAmountOfTheOrder : 0 }}
            </div>
            <div class="size-hui">
              <div class="nei">订单总金额</div>
              <div class="icon-img">
                <img src="../../../assets/images/cut/组 5017@2x.png" style="width: 20px;height: 20px">
              </div>
            </div>
          </div>
          <div class="box">
            <div class="size-bole">{{ orderStatistics.numberOfStrokes ? orderStatistics.numberOfStrokes : 0 }}</div>
            <div class="size-hui">
              <div class="nei">笔数</div>
              <div class="icon-img">
                <img src="../../../assets/images/cut/组 4666@2x.png" style="width: 20px;height: 20px">
              </div>
            </div>
          </div>
          <div class="box1">
            <div class="size-bole">{{
                orderStatistics.theTotalAmountPaid ? orderStatistics.theTotalAmountPaid : 0
              }}
            </div>
            <div class="size-hui">
              <div class="nei">实付总金额</div>
              <div class="icon-img">
                <img src="../../../assets/images/cut/组 5017@2x.png" style="width: 20px;height: 20px">
              </div>
            </div>
          </div>
          <div class="box1">
            <div class="size-bole">{{ orderStatistics.oilDiscounts ? orderStatistics.oilDiscounts : 0 }}</div>
            <div class="size-hui">
              <div class="nei">油品优惠</div>
              <div class="icon-img">
                <img src="../../../assets/images/cut/组 5017@2x.png" style="width: 20px;height: 20px">
              </div>
            </div>
          </div>
          <div class="box1">
            <div class="size-bole">{{ seekZeroAmount }}</div>
            <div class="size-hui">
              <div class="nei">找零总金额</div>
              <div class="icon-img">
                <img src="../../../assets/images/cut/组 5017@2x.png" style="width: 20px;height: 20px">
              </div>
            </div>
          </div>
          <div class="box1">
            <div class="size-bole">{{
                orderStatistics.theTotalAmountOfOil ? orderStatistics.theTotalAmountOfOil : 0
              }}
            </div>
            <div class="size-hui">
              <div class="nei">油品总金额</div>
              <div class="icon-img">
                <img src="../../../assets/images/cut/组 5017@2x.png" style="width: 20px;height: 20px">
              </div>
            </div>
          </div>
          <div class="box">
            <div class="size-bole">{{
                orderStatistics.numberOfStrokesByOil ? orderStatistics.numberOfStrokesByOil : 0
              }}
            </div>
            <div class="size-hui">
              <div class="nei">油品笔数</div>
              <div class="icon-img">
                <img src="../../../assets/images/cut/组 4666@2x.png" style="width: 20px;height: 20px">
              </div>
            </div>
          </div>
          <div class="box">
            <div class="size-bole">
              {{ orderStatistics.numberOfStrokesByGoods ? orderStatistics.numberOfStrokesByGoods : 0 }}
            </div>
            <div class="size-hui">
              <div class="nei">商品笔数</div>
              <div class="icon-img">
                <img src="../../../assets/images/cut/组 4666@2x.png" style="width: 20px;height: 20px">
              </div>
            </div>
          </div>
          <div class="box1">
            <div class="size-bole">
              {{ orderStatistics.theTotalAmountOfTheItem ? orderStatistics.theTotalAmountOfTheItem : 0 }}
            </div>
            <div class="size-hui">
              <div class="nei">商品总金额</div>
              <div class="icon-img">
                <img src="../../../assets/images/cut/组 5017@2x.png" style="width: 20px;height: 20px">
              </div>
            </div>
          </div>

        </div>
      </div>
      <div>
        <div class="table-box">
          <el-table
            :data="orderList"
            style="width: 100%">
            <el-table-column type="index" width="50" align="center" label="序号"/>
            <el-table-column prop="orderNo" align="center" label="订单号" width="220"></el-table-column>
            <el-table-column prop="amount" align="center" label="订单金额"></el-table-column>
            <el-table-column prop="afterDiscountAmount" align="center" label="优惠后应付金额"></el-table-column>
            <el-table-column prop="payAmount" align="center" label="实付金额"></el-table-column>
            <el-table-column prop="seekZero" align="center" label="找零金额"></el-table-column>
            <el-table-column align="center" label="订单金额组成">
              <el-table-column prop="oilOrderAmount" align="center" label="油品金额">
                <template slot-scope="scope">
                  <span>{{ scope.row.oilOrderAmount ? scope.row.oilOrderAmount : '0' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="goodsOrderAmount" align="center" label="商品金额">
                <template slot-scope="scope">
                  <span>{{ scope.row.goodsOrderAmount ? scope.row.goodsOrderAmount : '0' }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" label="实付订单金额组成">
              <el-table-column prop="oilOrderAmount" align="center" label="油品实付金额" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.oilPayAmount ? scope.row.oilPayAmount : '0' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="goodsOrderAmount" align="center" label="商品实付金额" width="110">
                <template slot-scope="scope">
                  <span>{{ scope.row.goodsPayAmount ? scope.row.goodsPayAmount : '0' }}</span>
                </template>
              </el-table-column>
            </el-table-column>

            <el-table-column prop="payUser" align="center" label="付款用户" width="110"></el-table-column>
            <el-table-column prop="status" align="center" label="状态">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 'unpaid'">未支付</el-tag>
                <el-tag type="success" v-else-if="scope.row.status === 'paid'">已支付</el-tag>
                <el-tag type="danger" v-else-if="scope.row.status === 'refund'">已退款</el-tag>
                <el-tag type="danger" v-else>支付失败</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="交易时间" align="center" width="160" prop="payTime">
              <template slot-scope="scope">
                <span>{{ scope.row.payTime ? parseTime(scope.row.payTime) : "--" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作人" align="center" prop="staffId">
              <template slot-scope="scope">
                <span>{{ getRealName(staffList, scope.row.staffId) || '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button style="width: 60px" size="mini"
                           @click="getOrdersInfo(scope.row.id)"
                           type="success" plain round>详情
                </el-button>
                <el-button style="width: 60px" size="mini"
                           @click="patchwork(scope.row)"
                           type="primary" plain round>补打
                </el-button>
                <el-button style="width: 60px" size="mini"
                           v-if="scope.row.status === 'paid'"
                           @click="refHandleRefund(scope.row.id)"
                           type="danger" plain round>退款
                </el-button>
              </template>
            </el-table-column>

          </el-table>
        </div>
        <div class="pagination-box">
          <el-pagination
            background
            v-show="total>0"
            layout="prev, pager, next"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.pageSize"
            @current-change="getList">
          </el-pagination>
        </div>

      </div>
    </div>

    <!--    订单详情-->
    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisible">
      <div>
        <el-descriptions>
          <el-descriptions-item label="收银员姓名">{{ cashierOrder.realName }}</el-descriptions-item>
          <el-descriptions-item label="收银员账号">{{ cashierOrder.mobile }}</el-descriptions-item>
          <el-descriptions-item label="订单编号">{{ cashierOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">{{ cashierOrder.amount }}</el-descriptions-item>
          <el-descriptions-item label="油品金额">{{ cashierOrder.oilOrderAmount }}</el-descriptions-item>
          <el-descriptions-item label="商品金额">{{ cashierOrder.goodsOrderAmount }}</el-descriptions-item>
          <el-descriptions-item label="油品优惠券优惠">
            <span v-if="oilInfo.length>0">{{ oilInfo[0].couponAmount || 0 }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="油品满减/折扣活动优惠">
            <span v-if="oilInfo.length>0">{{ oilInfo[0].activeAmount || 0 }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="油品会员等级优惠">
            <span v-if="oilInfo.length>0">{{ oilInfo[0].levelAmount || 0 }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="油品优惠总额">{{ cashierOrder.oilDiscountAmount }}</el-descriptions-item>
          <el-descriptions-item label="商品优惠总额">{{ cashierOrder.goodsDiscountAmount }}</el-descriptions-item>
          <el-descriptions-item label="油品实付总额">{{ cashierOrder.oilPayAmount }}</el-descriptions-item>
          <el-descriptions-item label="商品实付总额">{{ cashierOrder.goodsPayAmount }}</el-descriptions-item>
          <el-descriptions-item label="实付金额">{{ cashierOrder.payAmount }}</el-descriptions-item>
          <el-descriptions-item label="储值卡消费金额">
            <span v-if="oilInfo.length>0">{{ oilInfo[0].balanceAmount }}</span>
            <span v-else>0</span>
          </el-descriptions-item>
          <!--          <el-descriptions-item label="囤油卡消费升数">-->
          <!--            <span v-if="oilInfo.length>0">{{ oilInfo[0].oilCardAmount }}</span>-->
          <!--            <span v-else>0</span>-->
          <!--          </el-descriptions-item>-->
          <el-descriptions-item label="找零金额">{{ cashierOrder.seekZero }}</el-descriptions-item>
          <el-descriptions-item label="付款方式">
            <span v-if="cashierOrder.payType == 'CASH'">现金</span>
            <span v-else-if="cashierOrder.payType == 'WECHAT'">微信</span>
            <span v-else-if="cashierOrder.payType == 'ALIPAY'">支付宝</span>
            <span v-else-if="cashierOrder.payType == 'UNIONPAY'">银联二维码</span>
            <span v-else-if="cashierOrder.payType == 'oilCard'">囤油卡</span>
            <span v-else-if="cashierOrder.payType == 'balance'">储值卡</span>
            <span v-else-if="cashierOrder.payType == 'credit'">挂账</span>
            <span v-else>小程序码</span>
          </el-descriptions-item>
          <el-descriptions-item label="付款状态">
            <el-tag v-if="cashierOrder.status == 'unpaid'">未支付</el-tag>
            <el-tag type="success" v-else-if="cashierOrder.status == 'paid'">已支付</el-tag>
            <el-tag type="warning" v-else-if="cashierOrder.status == 'payFail'">支付失败</el-tag>
            <el-tag type="danger" v-else-if="cashierOrder.status == 'refund'">已退款</el-tag>
            <el-tag type="info" v-else>退款中</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="交易时间">
            {{ cashierOrder.payTime ? parseTime(cashierOrder.payTime) : "--" }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div style="margin-top: 30px">
        <el-descriptions :column="1" direction="vertical">
          <el-descriptions-item label="油品详情">
            <el-table
              v-loading="loading"

              :data="oilInfo"
              style="width: 100%">
              <el-table-column label="油号油枪" prop="terminal">
                <template slot-scope="scope">
                  <span>{{ getName(oilNameList, scope.row.oils) }}/{{
                      getName1(oilGunList, scope.row.oilGunNum)
                    }}</span>
                </template>
              </el-table-column>
              <el-table-column label="油品金额" align="center" prop="orderAmount">
                <template slot-scope="scope">
                  <span>{{ scope.row.orderAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="加油升数" align="center" prop="oilNum">
                <template slot-scope="scope">
                  <span>{{ scope.row.oilNum }}L</span>
                </template>
              </el-table-column>
              <el-table-column label="油品单价" align="center" prop="amount">
                <template slot-scope="scope">
                  <span>{{ scope.row.oilPrice }}/L</span>
                </template>
              </el-table-column>
              <!--              <el-table-column label="满减活动优惠" align="center" prop="activeId">-->
              <!--                <template slot-scope="scope">-->
              <!--                  <span v-if="scope.row.activeType==1">{{ scope.row.deductionAmount }}</span>-->
              <!--                  <span v-else>0</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <!--              <el-table-column label="折扣活动优惠" align="center" prop="activeId">-->
              <!--                <template slot-scope="scope">-->
              <!--                  <span v-if="scope.row.activeType==2">{{ scope.row.deductionAmount }}</span>-->
              <!--                  <span v-else>0</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
            </el-table>
          </el-descriptions-item>
          <el-descriptions-item label="商品详情">
            <el-table
              :data="goodsInfo"
              style="width: 100%">
              <el-table-column label="商品名称" prop="name"/>
              <el-table-column label="单价" align="center" prop="retailPrice">
                <template slot-scope="scope">
                  <span>{{ scope.row.retailPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="cashierOrder.payUser != '散客'" label="会员价" align="center" prop="retailPrice">
                <template slot-scope="scope">
                  <span>{{ scope.row.memberPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center" prop="num"/>
              <el-table-column label="合计金额" align="center" prop="num">
                <template slot-scope="scope">
                  <span>{{ scope.row.allAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="实付金额" align="center" prop="num">
                <template slot-scope="scope">
                  <span>{{ scope.row.payAmount }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
    <!--    订单退款-->
    <el-dialog
      :close-on-click-modal="false"
      title="订单退款"
      width="25%"
      :visible.sync="refDialogRefund">
      <div style="margin: 10px 0">
        退款密码<br/>
      </div>
      <div>
        <el-input placeholder="请输入退款密码" v-model="refPass" show-password></el-input>
        <br/>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="refDialogRefund = false">取 消</el-button>
        <el-button type="primary" @click="refHandleRefundByif()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="订单退款"
      width="25%"
      :visible.sync="dialogRefund">
      <div style="text-align: center;font-weight: bold">
        <!--        ￥<span style="font-size: 35px">{{ cashierOrder.payAmount }}</span>-->
        ￥<span style="font-size: 35px">{{ cashierOrder.goodsPayAmount + cashierOrder.oilPayAmount }}</span>
      </div>
      <div class="tk">退款金额</div>
      <div class="tk">退款单号：{{ cashierOrder.orderNo }}</div>

      <span>退款内容：</span>
      <br>
      <span>商品：</span>
      <el-checkbox v-model="isGoods" @click="calculateRefunds()">￥{{ cashierOrder.goodsPayAmount }}</el-checkbox>
      <br>


      <span>油品：</span>
      <template>
        <el-checkbox v-if="oilInfo.length > 0" v-model="isOil" @click="calculateRefunds()">

          <span v-if="oilInfo[0].payAmount && oilInfo[0].payAmount!='0.00'"> ￥{{ cashierOrder.oilPayAmount }}</span>
          <span v-if="oilInfo[0].balanceAmount>0">储值卡：{{ oilInfo[0].balanceAmount }} </span>
          <span v-if="oilInfo[0].oilCardAmount>0">屯油卡：{{ oilInfo[0].oilCardAmount }} </span>
        </el-checkbox>
        <el-checkbox v-if="isOil && oilInfo.length > 0 && oilInfo[0].couponId" v-model="isOilVouchers">优惠卷
        </el-checkbox>

        <!--        <el-checkbox v-if="oilInfo.length > 0 && oilInfo[0].balanceAmount>0" v-model="isOilCard">储值卡：{{oilInfo[0].balanceAmount}}</el-checkbox>-->
        <!--        <el-checkbox v-if="oilInfo.length > 0 && oilInfo[0].oilCardAmount>0" v-model="isOilFuel">屯油卡：{{ oilInfo[0].oilCardAmount }}</el-checkbox>-->
      </template>


      <div style="margin: 10px 0">
        退款原因<br/>
        <el-radio-group v-model="radio1" style="margin: 10px 0">
          <el-radio-button label="油号选错"></el-radio-button>
          <el-radio-button label="金额错误"></el-radio-button>
          <el-radio-button label="其他原因"></el-radio-button>
        </el-radio-group>
      </div>
      <div>
        <el-input placeholder="请输入退款原因" v-model="refundRemark"></el-input>
        <br/>
        <!--        <span style="color: grey;font-size: 12px">退款仅支持全额退款,退款金额将按照支付信息原路退回、优惠券、储值卡等原路退回处理</span>-->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRefund = false">取 消</el-button>
        <el-button type="primary" @click="refundConfirmed()">确 定</el-button>
      </span>
    </el-dialog>

    <!--    支付成功后小票打印内容-->
    <div id="reportSuccess" ref="report" class="box-center" v-show="false">
      <div class="box-title">订单统计</div>
      <div class="box-ge">
        <div v-for="item in oilInfo" :key="item.id">
          <div class="input-box">
            <div>{{ getName(oilNameList, item.oils) }}/{{ getName1(oilGunList, item.oilGunNum) }}</div>
            <div>￥{{ item.orderAmount }}</div>
          </div>
          <div class="input-box">
            <div>加油升数</div>
            <div>{{ item.oilNum }}L</div>
          </div>
        </div>
        <div v-for="item in goodsInfo" :key="item.id">
          <div class="input-box">
            <div>商品名称</div>
            <div>{{ item.name }}</div>
          </div>
          <div class="input-box">
            <div>商品数量</div>
            <div>{{ item.num }}{{ item.unit }}</div>
          </div>
          <div class="input-box" v-if="!cashierOrder.userId">
            <div>商品单价</div>
            <div>￥{{ item.retailPrice }}</div>
          </div>
          <div class="input-box" v-else>
            <div>商品单价</div>
            <div>￥{{ item.memberPrice }}</div>
          </div>
        </div>
        <div class="input-box">
          <div>支付方式</div>
          <div v-if="cashierOrder.payType == 'CASH'">现金</div>
          <div v-else-if="cashierOrder.payType == 'WECHAT'">微信</div>
          <div v-else-if="cashierOrder.payType == 'ALIPAY'">支付宝</div>
          <div v-else-if="cashierOrder.payType == 'UNIONPAY'">银联二维码</div>
          <div v-else>小程序码</div>
        </div>
        <div class="input-box">
          <div>合计</div>
          <div>￥{{ cashierOrder.amount }}</div>
        </div>
        <div class="input-box">
          <div>实付款</div>
          <div>￥{{ cashierOrder.payAmount }}</div>
        </div>
        <div class="input-box" v-if="cashierOrder.seekZero>0">
          <div>找零金额</div>
          <div>￥{{ cashierOrder.seekZero }}</div>
        </div>
      </div>
    </div>


    <div id="reportSuccess2" ref="report2" class="box-center" v-show="false">
      <div class="box-title">订单退款</div>
      <div class="box-ge">
        <div v-if="isOil" v-for="item in oilInfo" :key="item.id">
          <div class="input-box">
            <div>{{ getName(oilNameList, item.oils) }}/{{ getName1(oilGunList, item.oilGunNum) }}</div>
            <div>￥{{ item.orderAmount }}</div>
          </div>
          <div class="input-box">
            <div>加油升数</div>
            <div>{{ item.oilNum }}L</div>
          </div>
        </div>
        <div v-if="isOil">
          <div v-if="oilInfo[0].balanceAmount>0" class="input-box">
            <div>储值卡</div>
            <div>{{ oilInfo[0].balanceAmount }}</div>
          </div>
          <div v-if="oilInfo[0].oilCardAmount>0" class="input-box">
            <div>屯油卡</div>
            <div>{{ oilInfo[0].oilCardAmount }}</div>
          </div>
        </div>


        <div v-if="isGoods" v-for="item in goodsInfo" :key="item.id">
          <div class="input-box">
            <div>商品名称:</div>
            <div>{{ item.name }}</div>
          </div>
          <div class="input-box">
            <div>商品数量:</div>
            <div>{{ item.num }}{{ item.unit }}</div>
          </div>
          <div class="input-box" v-if="!cashierOrder.userId">
            <div>商品单价:</div>
            <div>￥{{ item.retailPrice }}</div>
          </div>
          <div class="input-box" v-else>
            <div>商品单价:</div>
            <div>￥{{ item.memberPrice }}</div>
          </div>
        </div>
        <div class="input-box">
          <div>支付方式</div>
          <div v-if="cashierOrder.payType == 'CASH'">现金</div>
          <div v-else-if="cashierOrder.payType == 'WECHAT'">微信</div>
          <div v-else-if="cashierOrder.payType == 'ALIPAY'">支付宝</div>
          <div v-else-if="cashierOrder.payType == 'UNIONPAY'">银联二维码</div>
          <div v-else>小程序码</div>
        </div>
        <div class="input-box">
          <div>合计:</div>
          <div>￥{{ cashierOrder.amount }}</div>
        </div>

        <div class="input-box">
          <div>实退款:</div>
          <div>￥{{ calculateRefundsV }}</div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import {
  cashierOrder,
  cashierOrderSeekZeroAmount,
  listCashierOrder,
  orderStatisticsApi
} from "@/api/cashier/cashierorder";
import {queryStaffs} from "@/api/cashier/staff";
import {oilOrderList, oilOrders} from "@/api/cashier/oilorder";
import {getOilNameList} from "@/api/cashier/oilnumgun";
import {getOrderGoods} from "@/api/cashier/goodsorder";
import {exportExcelCashierApi} from "@/api/order/exportExcel";
import {refundApi} from "@/api/cashier/refund";
import {connectFlag, getLodop} from "@/api/LodopFuncs";
import {getOilNumberGun} from "@/api/cashier/oilGuns";
import {formatDate} from "@/utils";
import ScanPayCodeDialog from "@/views/cashier/components/scanPayCodeDialog.vue";
import {printOilOrderReport, rePrintOilOrderReport} from "@/api/print";
import {ifRefPassApi} from "@/api/staff/store";
import {getDicts} from "../../../api/dict/data";

export default {
  name: "order_Cashier",
  components: {ScanPayCodeDialog},
  data() {
    return {
      calculateRefundsV: 0,
      // 退款备注
      refundRemark: "",
      refPass: "",
      radio1: "油号选错",
      // 油号列表
      oilNameList: [],
      // 油品订单详情列表
      oilInfo: [],
      // 商品订单详情列表
      goodsInfo: [],
      oilGunList: [],
      // 收银员订单详情
      cashierOrder: {},
      loading: false,
      dialogVisible: false,
      dialogRefund: false,
      refDialogRefund: false,
      // 员工列表
      staffList: [],
      // 日期范围
      dateRange: [],
      beginTime: "",
      endTime: "",
      isOilVouchers: false,
      isGoods: false,
      isOil: false,
      isOilCard: false,  // 是否推掉油卡
      isOilFuel: false, //是否推掉储值卡
      // 是否为当天时间
      isSysDate: false,
      // 收银台订单列表
      orderList: [],
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        beginTime: "",
        endTime: "",
      },
      orderStatistics: {
        numberOfStrokes: '0',
        theTotalAmountOfTheOrder: '0',
        theTotalAmountPaid: '0',
        oilDiscounts: '0',
        theTotalAmountOfOil: '0',
        theTotalAmountOfTheItem: '0',
      },
      // 支付类型列表
      payList:[],
      total: 0,
      seekZeroAmount: 0,
      getId: ""
    }
  },
  created() {
    let start = new Date();
    start.setHours(0)
    start.setMinutes(0)
    start.setSeconds(0)
    start.setMilliseconds(0)
    this.dateRange = [start, new Date()];
    this.beginTime = start
    this.endTime = new Date()
    this.isSysDate = true
    this.getList();
    // this.getOrderStatistics();
    this.getStaffList();
    this.getOilGunList();
  },
  methods: {

    exportExcelCashier() {
      let dateRange = []
      if (this.beginTime && this.endTime) {
        dateRange.push(this.beginTime.toLocaleDateString())
        dateRange.push(this.endTime.toLocaleDateString())
      }
      exportExcelCashierApi(this.addDateRange(this.queryParams, dateRange)).then(res => {
        const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        this.$download.saveAs(blob, '收银台订单统计.xLsx')
      })
    },
    // 获取订单统计信息

    getOrderStatistics() {
      let dateRange = []
      if (this.beginTime && this.endTime) {
        dateRange.push(this.beginTime.toLocaleDateString())
        dateRange.push(this.endTime.toLocaleDateString())
      }
      orderStatisticsApi(this.addDateRange(this.queryParams, dateRange)).then(res => {
        this.orderStatistics = res.data
      })
    },
    // 获取员工姓名
    getRealName(list, val) {
      let name = "";
      list.forEach(item => {
        if (item.id == val) {
          name = item.realName
        }
      })
      return name;
    },
    // 获取员工手机号
    getMobile(list, val) {
      let name = "";
      list.forEach(item => {
        if (item.id == val) {
          name = item.mobile
        }
      })
      return name;
    },

    async printLocally(data) {
      if (!connectFlag) {
        return
      }

      //初始化打印函数
      let LODOP = getLodop(); // 初始化打印
      LODOP.PRINT_INIT();
      var bodyStyle = `<style>
            .input-box{
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 14px;
                margin: 5px 0px;
              }
             .box-ge{
                border-bottom: 1px solid #000000 ;
                box-sizing: border-box;
                padding: 10px;
              }
              .box-title{
                font-size: 18px;
                text-align: center;
                align-items: center;
                margin-top: 15px;
              }
              .input-hui{
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 14px;
                margin: 15px 0px;
                background: #b2b2b2;
                box-sizing: border-box;
                padding: 5px 0px;
              }
              .input-hui-frou{
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 14px;
                margin: 15px 0px;
                background: #b2b2b2;
                box-sizing: border-box;
                padding: 5px 0px;
                div{
                  width: 25%;
                  text-align: left;
                }
              }
              .input-box-frou{
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 14px;
                margin: 5px 0px;
                div{
                  width: 25%;
                  text-align: left;
                }
              }
              .box-center{
                height: 500px;
              }
            </style>
            `
      // var fromHtml = bodyStyle+this.$refs.report.innerHTML
      var fromHtml = ''
      if (data == 'report') {
        fromHtml = bodyStyle + this.$refs.report.innerHTML
      } else {
        fromHtml = bodyStyle + this.$refs.report2.innerHTML

      }


      LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", fromHtml);

      LODOP.SET_PRINT_MODE("FULL_WIDTH_FOR_OVERFLOW", true);

      // LODOP.ADD_PRINT_BARCODE(10,40,100,100,'QRCode','123456789');
      // let preview = LODOP.PREVIEW();
      // console.log("preview",preview);
      LODOP.PRINT();

    },

    // 打印商品支付后的订单
    oilOrderReport() {
      let oilOrderR = []
      let balanceAmount = 0
      let oilCardAmount = 0


      this.oilInfo.forEach(order => {
        if (order.balanceAmount) {
          balanceAmount += order.balanceAmount
        }
        if (order.oilCardAmount) {
          oilCardAmount += order.oilCardAmount
        }
        let o = {
          oilName: this.getName(this.oilNameList, order.oils) + "-" + this.getName1(this.oilGunList, order.oilGunNum),
          amount: order.orderAmount.toString(),
          // amount : order.oilPayAmount.toString(),
          oilNum: order.oilNum.toString()
        }
        oilOrderR.push(o)
      })

      let goodsOrderR = []
      if (this.goodsInfo) {
        this.goodsInfo.forEach(order => {

          let o = {
            oilName: order.name,
            unit: order.num + "" + order.unit,
            // amount : order.memberPrice.toString()
            amount: order.retailPrice.toString()
          }
          goodsOrderR.push(o)
        })
      }

      console.log("111111111111111111111111112")

      // 支付方式
      const payTypeMap = {
        'CASH': '现金',
        'WECHAT': '微信',
        'ALIPAY': '支付宝',
        'UNIONPAY': '银联二维码',
        'credit': '挂账',
        'oilCard': '囤油卡',
        'balance': '储值卡'
      };
      let payTypeText = payTypeMap[this.cashierOrder.payType] || '小程序码';
      console.log("this.cashierOrder.amount", this.cashierOrder)
      let amount = (this.cashierOrder.payAmount - this.cashierOrder.seekZero).toFixed(2)
      // console
      let f = {
        oilOrder: oilOrderR,
        goodsOrder: goodsOrderR,
        payType: payTypeText,
        // amount:this.cashierOrder.payAmount-this.cashierOrder.seekZero,
        payAmount: this.cashierOrder.payAmount,
        amount: this.cashierOrder.amount,
        actualPay: this.cashierOrder.payAmount.toFixed(2),
        // discount:this.cashierOrder.amount-this.cashierOrder.afterDiscountAmount,
        seekZero: this.cashierOrder.seekZero,
        consumeAmount: balanceAmount,// 储值卡
        consumeRefuelMoney: oilCardAmount,// 屯油卡

      }
      // rePrintOilOrderReport(f).then(res=>{
      printOilOrderReport(f).then(res => {

      })
      // // consumeAmount:this.consumeAmount,
      // creditAmount: (this.oilAmount+(+this.goodsAmount)).toFixed(2),//挂账金额
      //   // 优惠合计
      //   discount:(this.oilDiscount + this.goodsDiscount + this.fullReduction + this.couponAmount).toFixed(2), // 油惠合计
      //   // 储值卡付款
      //   consumeAmount:this.consumeAmount,
      //   // 屯油卡付款
      //   consumeRefuelMoney:this.consumeRefuelMoney.toFixed(2),


    },

    // 打印商品支付后的订单
    reoilOrderReport() {
      let oilOrderR = []
      let balanceAmount = 0
      let oilCardAmount = 0
      this.oilInfo.forEach(order => {
        if (order.balanceAmount) {
          balanceAmount += order.balanceAmount
        }
        if (order.oilCardAmount) {
          oilCardAmount += order.oilCardAmount
        }
        let o = {
          oilName: this.getName(this.oilNameList, order.oils) + "-" + this.getName1(this.oilGunList, order.oilGunNum),
          amount: order.orderAmount.toString(),
          oilNum: order.oilNum.toString()
        }
        oilOrderR.push(o)
      })
      console.log("111111111111111111111111111")

      let goodsOrderR = []
      if (this.goodsInfo) {
        this.goodsInfo.forEach(order => {
          console.log("111111111111111111111111111")

          let o = {
            oilName: order.name,
            unit: order.num + "" + order.unit,
            amount: order.memberPrice.toString()
          }
          goodsOrderR.push(o)
        })
      }


      // 支付方式
      const payTypeMap = {
        'CASH': '现金',
        'WECHAT': '微信',
        'ALIPAY': '支付宝',
        'UNIONPAY': '银联二维码',
        'credit': '挂账',
        'oilCard': '囤油卡',
        'balance': '储值卡'
      };
      let payTypeText = payTypeMap[this.cashierOrder.payType] || '小程序码';


      let f = {
        oilOrder: oilOrderR,
        goodsOrder: goodsOrderR,
        payType: payTypeText,
        amount: this.cashierOrder.amount,
        payAmount: this.cashierOrder.amount,
        // seekZero:this.cashierOrder.payAmount,
        balanceAmount: balanceAmount,// 储值卡
        oilCardAmount: oilCardAmount,// 屯油卡
        calculateRefundsV: this.calculateRefundsV,
        type: "2",
      }
      rePrintOilOrderReport(f).then(res => {

      })
    },


    // 补打
    patchwork(data) {
      const orderNo = data.orderNo
      this.$modal.confirm('确定您要补打当前订单吗？当前订单号[' + orderNo + '],请确保云打印机正在运行中').then(function () {
        // return delUser(row.id);
      }).then(async () => {
        await cashierOrder(data.id).then(response => {
          this.cashierOrder = response.data
          this.$modal.msgSuccess("打印指令已发送打印机,请查看打印结果");
        })
        await this.getOilList(this.cashierOrder.orderNo)
        await this.getGoodsLists(this.cashierOrder.goodsOrderId)
        // this.printLocally('report')
        this.oilOrderReport()
      }).catch(() => {
      });
    },

    async refHandleRefundByif(id) {
      this.refDialogRefund = true;
      await ifRefPassApi({refPass: this.refPass}).then(res => {
        if (res.data) {
          this.handleRefund(this.getId)
          this.refDialogRefund = false;
        } else {
          this.$message({
            type: 'info',
            message: '密码错误'
          });
        }
      })
    },
    async refHandleRefund(id) {
      this.getId = id,
        this.refPass = ""
      this.refDialogRefund = true;
    },


    // 退款
    async handleRefund(id) {
      this.dialogRefund = true;
      await cashierOrder(id).then(response => {
        this.cashierOrder = response.data

        //
        this.getOilList(response.data.orderNo)
        if (response.data.status === "refund") {
          this.$message({
            type: 'info',
            message: '该订单已经退款'
          });
          this.dialogRefund = false;
        }
      })
      //退款确定
      // this.$confirm('是否将该收银台下的订单全部退款, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   this.dialogRefund = true;
      //   cashierOrder(id).then( response => {
      //     this.cashierOrder = response.data
      //     if (response.data.status === "refund") {
      //       this.$message({
      //         type: 'info',
      //         message: '该订单已经退款'
      //       });
      //       this.dialogRefund = false;
      //     }
      //   })
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消删除'
      //   });
      // });
    },

    // 计算退款总价
    calculateRefunds() {
      let refundAmt = 0
      if (this.isGoods) {
        refundAmt += this.cashierOrder.goodsPayAmount
      }
      if (this.isOil && this.cashierOrder.oilPayAmount > 0) {
        refundAmt += this.cashierOrder.oilPayAmount
      }

      this.calculateRefundsV = refundAmt;
    },

    async refundConfirmed() {
      this.calculateRefunds();
      if (!this.isOil && !this.isGoods) {
        this.$message({
          type: 'info',
          message: '请选择退款项'
        });
        return
      }
      this.dialogRefund = false;
      this.loading = true;
      console.log("cashierOrder", this.cashierOrder)


      // 计算退款总价
      let refundAmt = 0
      if (this.isGoods) {
        refundAmt += this.cashierOrder.goodsPayAmount
      }
      if (this.isOil && this.cashierOrder.oilPayAmount > 0) {
        refundAmt += this.cashierOrder.oilPayAmount
      }

      // if (this.isOilCard || this.isOilFuel) {
      //   this.isOil = true
      // }

      let map = {

        orderNo: this.cashierOrder.orderNo,
        storeId: this.cashierOrder.storeId,
        refundRemark: this.radio1 + "-" + this.refundRemark,
        type: "canRefund",
        isOilVouchers: this.isOilVouchers,
        isGoods: this.isGoods,
        isOil: this.isOil,
        isOilCard: this.isOilCard,  // 是否推掉油卡
        isOilFuel: this.isOilFuel, //是否推掉储值卡
        refundAmt: refundAmt
      }
      await refundApi(map).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'info',
            message: '退款成功'
          });
          // this.printLocally()
          this.reoilOrderReport()

        }

      })

      this.loading = false;

      this.getList();
      // this.getOrderStatistics();
      this.getStaffList();
      // this.oilOrderReport()

    },
    // 获取油枪信息
    getOilGunList() {
      getOilNumberGun().then(res => {
        res.data.forEach(item => {
          if (item.oilGunList.length > 0) {
            item.oilGunList.forEach(i => {
              i.oilName = item.oilName
              this.oilGunList.push(i)
            })
          }
        })
      })
    },
    // 获取油枪名称
    getName1(oilNameList, id) {
      let name = ""
      let _this = this;
      if (oilNameList != null && oilNameList != "") {
        oilNameList.forEach(item => {
          if (item.id == id) {
            name = item.gunName;
          }
        })
      }
      return name;
    },
    // 获取油号名称
    getName(oilNameList, id) {
      let name = ""
      let _this = this;
      if (oilNameList != null && oilNameList != "") {
        oilNameList.forEach(item => {
          if (item.id == id) {
            name = item.oilName;
            _this.oilType = item.oilType;
          }
        })
      }
      return name;
    },
    // 获取订单详情
    getOrdersInfo(id) {
      cashierOrder(id).then(response => {
        this.cashierOrder = response.data
        this.getOilList(this.cashierOrder.orderNo)
        this.getGoodsLists(this.cashierOrder.goodsOrderId)
        this.dialogVisible = true;
      })
    },
    async getOilList(orderNo) {
      await oilOrderList({orderNo: orderNo}).then(response => {
        this.oilInfo = response.data
      })
    },
    async getGoodsLists(id) {
      await getOrderGoods({orderId: id}).then(response => {
        this.goodsInfo = response.data;
      })
    },
    parseTime1(dateTime) {
      let date = new Date(dateTime);
      let y = date.getFullYear() + "-";
      let mon = ((date.getMonth() + 1 < 10) ? ('0' + date.getMonth()) : date.getMonth()) + "-";
      let d = ((date.getDate() < 10) ? ('0' + date.getDate()) : date.getDate()) + " ";
      let h = ((date.getHours() < 10) ? ('0' + date.getHours()) : date.getHours()) + ":";
      let m = ((date.getMinutes() < 10) ? ('0' + date.getMinutes()) : date.getMinutes()) + ":";
      let s = ((date.getSeconds() < 10) ? ('0' + date.getSeconds()) : date.getSeconds());
      // return new Date(y , mon , d , h , m , s);
      return y + mon + d + h + m + s;
    },
    // 获取列表信息
    getList(val) {
      if (val != undefined) {
        this.queryParams.page = val
      }

      let dateRange1 = this.dateRange
      let dateRange = []
      if (this.beginTime && this.endTime) {
        dateRange.push(this.beginTime.toLocaleDateString())
        dateRange.push(this.endTime.toLocaleDateString())
      }
      // if (this.isSysDate){
      //   dateRange.push(dateRange1[0].toLocaleDateString())
      //   dateRange.push(dateRange1[1].toLocaleDateString())
      // }else {
      //   dateRange = this.dateRange
      // }

      listCashierOrder(this.addDateRange(this.queryParams, dateRange)).then(response => {
        this.orderList = response.data.records;
        this.total = response.data.total;
        this.isSysDate = false
      })
      this.getSeekZero(val)
      this.getOrderStatistics()
    },
    getSeekZero(val) {
      if (val != undefined) {
        this.queryParams.page = val
      }
      let dateRange = []
      if (this.beginTime && this.endTime) {
        dateRange.push(this.beginTime.toLocaleDateString())
        dateRange.push(this.endTime.toLocaleDateString())
      }
      cashierOrderSeekZeroAmount(this.addDateRange(this.queryParams, dateRange)).then(response => {
        if (response.data) {
          this.seekZeroAmount = response.data
        }
      })
    },
    // 获取员工列表信息
    getStaffList() {
      queryStaffs().then(response => {
        this.staffList = response.data;
      })
      getOilNameList().then(response => {
        this.oilNameList = response.data;
      })
      getDicts("payment_type").then( response => {
        this.payList = response.data;
      })
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        page: 1,
        pageSize: 10,
      }
      this.beginTime = ""
      this.endTime = ""
      // this.resetForm("queryForm");
      this.handleQuery();
    },
  }
}
</script>

<style scoped>
.app-top {
  width: 100%;

  height: 60px;
  box-sizing: border-box;
  padding: 10px;
}

.clearfix {
  width: 100%;

}

.box-card {
  width: 100%;
  margin-bottom: 15px;
}

.box-gang {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap; /* 允许内容换行 */

}

.box {
  padding: 5px;
  margin-right: 20px;
  margin-bottom: 20px;
  padding-left: 20px;

  width: 211px;
  height: 60px;
  background: rgba(64, 158, 255, 0.05);
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #409EFF;
}

.box1 {
  padding: 5px;
  margin-right: 20px;
  margin-bottom: 20px;
  padding-left: 20px;
  width: 211px;
  height: 60px;
  background: rgba(255, 150, 85, 0.05);
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #FF9655;
}

.el-form--inline .el-form-item {
  margin-right: 44px;
}

.size-hui {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 400;
  font-size: 13px;
  color: #888888;
  text-align: left;
  font-style: normal;
  text-transform: none;

  .nei {
    width: 150px;
  }
}

.size-bole {
  height: 31px;
  font-family: YouSheBiaoTiHei;
  font-weight: 400;
  font-size: 24px;
  color: #555555;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

.icon-img {
  width: 20px;
  height: 20px;
  margin-right: 5px;

  img {

    width: 20px;
    height: 20px;
  }
}

.wgang {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;

}

.table-box {
  width: 100%;
  height: 50vh;
  overflow: auto;
}

.pagination-box {
  width: 100%;
  margin: 10px auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.top-app-sou {
  width: 20%;
}

.tk {
  text-align: center;
  color: grey;
  margin: 10px 0;
}
.cot-box {
  width: 98%;
  border-radius: 8px;
  background: #fff;
  box-sizing: border-box;
  padding: 20px;
  margin: 0 auto;
}
</style>
