<!--商品交易列表-->
<template>
  <div class="app-container">
    <div class="box-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px">
        <el-form-item label="" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单号"
            clearable
            @input="$forceUpdate"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="" prop="terminal">
          <el-select
            v-model="queryParams.terminal"
            placeholder="请选择订单类型"
            clearable
            style="width: 240px"
          >
            <el-option v-for="item in terminalList"
                       :key="item.id"
                       :label="item.dictLabel"
                       :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <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="" prop="payUser">
          <el-input
            v-model="queryParams.payUser"
            placeholder="请输入付款用户"
            clearable
            @input="$forceUpdate"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="" prop="payType">
          <el-select
            v-model="queryParams.payType"
            placeholder="请选择支付方式"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in payList"
              :key="item.id"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="status">
          <el-select
            v-model="queryParams.status"
            clearable
            placeholder="请选择订单状态"
          >
            <el-option v-for="item in payStatusList"
                       :key="item.id"
                       :label="item.dictLabel"
                       :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="beginTime"
            style="width: 160px"
            type="date"
            placeholder="开始日期">
          </el-date-picker>
          至
          <el-date-picker
            v-model="endTime"
            style="width: 160px"
            type="date"
            placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item style="float: right;margin-right: 0px
">
          <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="exportExcelGoodsOrder()">导出</el-button>

        </el-form-item>
      </el-form>

      <div class="table-box">
        <el-table
          :data="list"
          border
          style="width: 100%">
          <el-table-column type="index" width="50" align="center" label="序号"/>
          <el-table-column label="订单号" align="center" prop="orderNo" width="220"/>
          <el-table-column label="订单类型" align="center" prop="terminal"/>
          <el-table-column label="商品数量" align="center" prop="goodsNum">
            <template slot-scope="scope">
              <el-tag @click="getGoods(scope.row.id)">{{ scope.row.goodsNum }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="订单金额(元)" align="center" prop="amount"/>
          <el-table-column label="优惠金额(元)" align="center" prop="discount"/>
          <el-table-column label="实收金额(元)" align="center" prop="payAmount"/>

          <el-table-column label="付款用户" align="center" prop="payUser"/>
          <el-table-column label="支付方式" align="center" prop="payType">
            <template slot-scope="scope">
              <span v-if="scope.row.payType=='credit'">挂账</span>
              <span v-else-if="scope.row.payType == 'CASH'">现金</span>
              <span v-else-if="scope.row.payType == 'WECHAT'">微信</span>
              <span v-else-if="scope.row.payType == 'ALIPAY'">支付宝</span>
              <span v-else-if="scope.row.payType == 'UNIONPAY'">银联二维码</span>
              <span v-else-if="scope.row.payType == '0'">兑换券核销</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center" prop="payType">
            <template slot-scope="scope">
              <div v-if="scope.row.status == 'unpaid'" style="color: #F44522">未支付</div>
              <div v-else-if="scope.row.status == 'paid'" style="color: #0DC291">支付成功</div>
              <div v-else-if="scope.row.status === 'refund'" style="color: #F44522">退款成功</div>
              <div v-else style="color: #F44522">支付失败</div>
            </template>
          </el-table-column>
          <!--        <el-table-column label="订单类型" align="center" prop="type"/>-->
          <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="150" prop="payTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单完成时间" align="center" width="150" prop="payTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.payTime) }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">-->
          <!--            <template slot-scope="scope">-->
          <!--              <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="handleRefund(scope.row.id)"-->
          <!--                         type="danger" plain round>退款</el-button>-->
          <!--            </template>-->
          <!--          </el-table-column>-->

        </el-table>
      </div>
      <div class="pagination-box">
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>

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

      <!-- 商品购买详情 -->
      <el-dialog center :close-on-click-modal="false" :title="title" :visible.sync="open" width="700px" append-to-body>
        <el-table ref="tables" v-loading="loading" :data="goodsList" :default-sort="defaultSort">
          <el-table-column label="商品名称" align="center" prop="name"/>
          <el-table-column label="商品数量" align="center" prop="num"/>
          <el-table-column label="商品单价" align="center" prop="retailPrice"/>
          <el-table-column label="会员价" align="center" prop="memberPrice"/>
        </el-table>
        <div style="height: 20px"></div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import {getGoodsOrder, getOrderGoods, listOrder, orderStatisticsApi} from "@/api/order/goodsorder";
import {queryStaffs} from "@/api/order/staff";
import {getDicts} from "@/api/order/data";
import {exportExcelGoodsOrderApi} from "@/api/order/exportExcel";
import {getOrderInfoApi, refundApi} from "@/api/order/refund";

export default {
  name: "order_Cashier",
  data() {
    return {
      // 终端列表
      terminalList: [],
      // 订单状态列表
      payStatusList: [],
      // 员工列表
      staffList: [],
      // 日期范围
      dateRange: [],
      beginTime: "",
      endTime: "",
      // 遮罩层
      loading: false,
      loadingRes: true,
      // 标题
      title: "",
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      goodsList: [],
      // 是否显示弹出层
      open: false,
      // 默认排序
      defaultSort: {prop: 'createTime', order: 'descending'},
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
      },
      orderGoods: '',
      // 支付列表
      payList: [],
      dialogRefund: false,
      radio1: "油号选错",
      goods: {},
      refundRemark: "",

      orderStatistics: {
        numberOfProducts: '0',
        theTotalAmount: '0',
        theTotalNumberOfUnits: '0',
        discountAmount: '0',
        wechat: '0',
        alipay: '0',
        cash: '0',
      },
      // 是否为当天时间
      isSysDate: false,
    }
  },
  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.getPayList();
  },
  methods: {
    exportExcelGoodsOrder() {
      this.$confirm('是否导出列表中的数据！', '提示', {
        confirmButtonText: '导出',
        cancelButtonText: '取消'
      }).then(() => {
        let dateRange = []
        if (this.beginTime && this.endTime) {
          dateRange.push(this.beginTime.toLocaleDateString())
          dateRange.push(this.endTime.toLocaleDateString())
        }
        exportExcelGoodsOrderApi(this.addDateRange(this.queryParams, dateRange)).then(res => {
          const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
          this.$download.saveAs(blob, '商品订单统计.xLsx')
        })
      }).catch(() => {

      });
    },
    // 订单统计
    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;

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

      await getGoodsOrder({"id": id}).then(response => {
        this.goods = response.data
        if (response.data.status === "refund") {
          this.$message({
            type: 'info',
            message: '该订单已经退款'
          });
          this.dialogRefund = false;
        }
      })


      let title = '是否将该收银台下的订单全部退款'
      await getOrderInfoApi({
        orderNo: this.goods.orderNo,
        type: 'goods'
      }).then(res => {
        if (res.code === 200) {
          if (res.data.type === "1") {
            title = '该订单下有其它商品订单，是否一并退款'
            this.goods.payAmount = res.data.money
          }
        }
      });

      this.$confirm(title + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogRefund = true;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退款'
        });
        this.dialogRefund = false;
      });

    },
    // 退款接口
    async refundConfirmed() {
      this.dialogRefund = false;
      this.loadingRes = true;
      console.log("cashierOrder", this.goods)
      let map = {
        orderNo: this.goods.orderNo,
        storeId: this.goods.storeId,
        refundRemark: this.radio1 + "-" + this.refundRemark,
        type: "canRefund"
      }
      await refundApi(map).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'info',
            message: '退款成功'
          });
        }
      })
      this.loadingRes = false;
      this.created()

    },
    // 根据员工id查询员工信息
    queryStaf(list, id) {
      let name = "";
      list.forEach(item => {
        if (item.id == id) {
          name = `${item.realName}(${item.mobile})`
        }
      })
      return name;
    },
    getVal(list, val) {
      let name = "";
      list.forEach(item => {
        if (item.dictValue == val) {
          name = item.dictLabel
        }
      })
      return name;
    },
    // 获取付款类型列表
    getPayList() {
      getDicts("payment_type").then(response => {
        this.payList = response.data;
      })
      getDicts("terminal").then(response => {
        this.terminalList = response.data;
      })
      getDicts("pay_status").then(response => {
        this.payStatusList = response.data;
      })
    },
    // 获取商品详情
    getGoods(id) {
      getOrderGoods({orderId: id}).then(response => {
        this.goodsList = response.data
        this.open = true;
        this.title = "商品详情"
      })
    },
    // 获取员工姓名
    getRealName(list, id) {
      var name = "";
      list.forEach(item => {
        if (item.id == id) {
          name = item.realName;
        }
      })
      return name;
    },
    // 获取员工列表
    getStaffList() {
      queryStaffs().then(response => {
        this.staffList = response.data;
      })
    },
    // 查询订单
    getList() {
      // let dateRange = []
      // if (this.isSysDate){
      //   dateRange.push(dateRange1[0].toLocaleDateString())
      //   dateRange.push(dateRange1[1].toLocaleDateString())
      // }else {
      //   dateRange = this.dateRange
      // }
      let dateRange = []
      if (this.beginTime && this.endTime) {
        dateRange.push(this.beginTime.toLocaleDateString())
        dateRange.push(this.endTime.toLocaleDateString())
      }

      this.loading = true;
      listOrder(this.addDateRange(this.queryParams, dateRange)).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.loading = false;
        this.isSysDate = false
      })
      // const app = this;
      // app.loading = true;
      // app.queryParams.storeIds = app.storeIds ? app.storeIds.join(",") : '';
      // getOrderList(app.queryParams).then( response => {
      //     this.list = response.data.paginationResponse.content;
      //     this.total = response.data.paginationResponse.totalElements;
      //     this.typeList = response.data.typeList;
      //     this.statusList = response.data.statusList;
      //     this.payStatusList = response.data.payStatusList;
      //     this.orderModeList = response.data.orderModeList;
      //     this.payTypeList = response.data.payTypeList;
      //     this.storeList = response.data.storeList;
      //     this.loading = false;
      //   }
      // );
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
      this.getOrderStatistics();
    },
    // 重置按钮操作
    resetQuery() {
      this.dateRange = [];
      this.queryParams.status = '';
      this.queryParams.mobile = '';
      this.queryParams.orderMode = '';
      this.queryParams.orderSn = '';
      this.queryParams.storeIds = '';
      this.storeIds = [];
      this.beginTime = ""
      this.endTime = ""
      this.resetForm("queryForm");
      this.handleQuery();
    },
  }
}
</script>

<style scoped lang="scss">

.app-container {
  width: 100%;
  height: 100%;
  background: #f6f8f9;
}

.app-top {
  width: 100%;

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

.clearfix {
  width: 100%;

}

.box-card {
  width: 100%;
  height: 89vh;
  border-radius: 8px;
  background: #fff;
  box-sizing: border-box;
  padding: 10px;
  margin-bottom: 15px;
}

.box-gang {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;

}

.box {
  //box-sizing: border-box;
  padding: 5px;
  //background: #f9f9f9;
  margin-right: 20px;
  padding-left: 20px;
  margin-bottom: 20px;

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

}

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

.size-hui {
  display: flex;
  align-items: center;
  //width: 200px;
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 400;
  font-size: 13px;
  color: #888888;
  //line-height: 0px;
  text-align: left;
  font-style: normal;
  text-transform: none;

  .nei {
    width: 150px;
  }
}

.size-bole {
  //font-weight: bold;

  //width: 53px;
  height: 31px;
  font-family: YouSheBiaoTiHei;
  font-weight: 400;
  font-size: 24px;
  color: #555555;
  //line-height: 0px;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

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

}

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

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

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

.icon-img {
  //margin-left: 110px;
  width: 100%;
  height: 20px;
  margin-right: 5px;

  img {
    float: right;
    //width: 100%;
    width: 20px;
    height: 100%;
  }
}

.box1 {
  //box-sizing: border-box;
  padding: 5px;
  //background: #f9f9f9;
  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;
}
</style>
