<template>
  <div class="app-container">
    <el-tabs v-model="orderType" @tab-click="getTableData">
      <el-tab-pane label="全部订单" name=""></el-tab-pane>
      <el-tab-pane label="收银订单" name="cash"></el-tab-pane>
      <el-tab-pane label="小程序订单" name="miniapp"></el-tab-pane>
    </el-tabs>
    <div class="head-container">
      <el-form :model="query" label-width="100px" label-position="left">
        <el-form-item label="订单状态">
          <el-radio-group v-model="query.status">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button :label="item.key" v-for="item in orderEnum.status" :key="item.key">
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-radio-group v-model="query.payType">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button :label="item.payType" v-for="item in payTypes" :key="item.payType">
              {{ item.payName }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-radio-group v-model="timeValue" @change="timeChange">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="0">今天</el-radio-button>
            <el-radio-button label="-1">昨天</el-radio-button>
            <el-radio-button label="-7">最近7天</el-radio-button>
            <el-radio-button label="-30">最近30天</el-radio-button>
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="custom">自定义</el-radio-button>
          </el-radio-group>
          <el-date-picker v-model="query.createdAt" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" value-format="yyyy-MM-dd HH:mm:ss"
            v-if="timeValue == 'custom'">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="订单号">
          <el-input v-model="query.orderNo" placeholder="请输入订单号" style="width: 300px;"></el-input>

        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="query.productName" placeholder="请输入商品名称" style="width: 300px;"></el-input>
          <el-button type="primary" @click="getTableData">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
          <el-button icon="el-icon-download" v-loading="downloadLoading" @click="downloadHandle">
            <span v-if="!downloadLoading">导出Excel</span>
            <span v-else>下载中...</span>
          </el-button>
        </el-form-item>


      </el-form>
    </div>
    <div class="head-container">
      <div class="collect_wrap">
        <!-- <div class="item">
          <div class="icon_wrap" style="--bg-color:#C978EE">
            <i class="icon el-icon-s-goods"></i>
          </div>
          <div class="info">
            <div class="m">￥{{ payCountTotal }}</div>
            <div class="t">总金额</div>
          </div>
        </div> -->
        <!-- <div class="item" v-for="item in payCountList" :key="item.payType">
          <div class="icon_wrap" style="--bg-color:#fff">
            <el-image class="img" :src="item.icon"></el-image>
          </div>
          <div class="info">
            <div class="m">￥{{ item.payAmount || 0 }}</div>
            <div class="t">{{ item.payType }}</div>
          </div>
        </div> -->
      </div>
    </div>
    <div class="head-container">
      <el-table :data="tableData.data" v-loading="tableData.loading">
        <el-table-column label="订单号信息">
          <template v-slot="scope">
            <div class="table_order_info">
              <div class="order_no">{{ scope.row.orderNo }}</div>
              <!-- <div>会员 {{ scope.row.orderNo }}</div> -->
              <div class="type">
                【{{ scope.row.orderType | orderTypeFilter }}
                {{ scope.row.sendType | sendTypeFilter }}】
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品信息">
          <template v-slot="scope">
            <div class="goods_info">
              <div class="row" v-for="item in scope.row.detailList" :key="item.id">
                <el-image :src="item.productImg" class="cover" lazy></el-image>
                <div class="info">
                  <div class="name">
                    <span :class="[item.isVip == 1 ? 'colorStyle' : '']">
                      {{ item.productName }}
                    </span>
                    <span class="refund" v-if="item.refundNumber">(退 - {{ item.refundNumber }})</span>
                  </div>
                  <div class="sku">{{ item.productSkuName }}</div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="台桌号" prop="tableName"></el-table-column>
        <el-table-column label="订单金额">
          <template v-slot="scope">
            <!-- <div>{{ scope.row.orderType | orderTypeFilter }}</div> -->
            <div class="refund" v-if="
              scope.row.orderType == 'return'
            ">
              退款：-￥{{ scope.row.orderAmount }}
            </div>
            <div v-else>￥{{ scope.row.orderAmount }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <template v-if="
              scope.row.status == 'refund' && scope.row.orderType != 'return'
            ">
              <el-tag type="primary">已完成</el-tag>
            </template>
            <template v-else>
              <el-tag type="primary" v-if="scope.row.status == 'closed'">
                {{ scope.row.status | statusFilter }}
              </el-tag>
              <el-tag type="warning" v-if="scope.row.status != 'closed'">
                {{ scope.row.status | statusFilter }}
              </el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark"></el-table-column>
        <el-table-column label="创建时间">
          <template v-slot="scope">
            {{ scope.row.createdAt | timeFilter }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <div class="u-flex gap-10">
              <el-button type="text" @click="$refs.orderDetail.show(scope.row)">详情</el-button>
              <el-button type="text" v-if="scope.row.status == 'closed'"
                @click="$refs.Invoicing.show(scope.row)">开票</el-button>
              <el-button v-if="scope.row.status == 'unpaid'" type="primary" size="mini"
                @click="payOrder(scope.row)">结账</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="head-container">
      <el-pagination :total="tableData.total" :current-page="tableData.page + 1" :page-size="tableData.size"
        @current-change="paginationChange" @size-change="sizeChange"
        layout="total, sizes, prev, pager, next, jumper"></el-pagination>
    </div>
    <orderDetail ref="orderDetail" @close="getTableData" />
    <!-- 开票 -->
    <Invoicing ref="Invoicing" @qrcode="qrcodeEvent"></Invoicing>
    <!-- 二维码 -->
    <div class="qrStyle" v-if="isuppop">
      <div class="box">
        <div> <span></span> {{ codeinfo.type }}<i class="el-icon-close" @click="isuppopEvent()"></i> </div>
        <canvas ref="canvas" id="canvas"></canvas>
        <div>
          税率：{{ codeinfo.se_amount + '%' }}&nbsp;&nbsp;
          金额：{{ codeinfo.price }}<br />
          <div style="color: red;margin-top: 5px;"> {{ codeinfo.string1 }} </div> <br />
          <el-button type="primary" style="margin-top: 10px;" @click="printEvent(codeinfo)">打印</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import orderEnum from "./orderEnum";
import { getLodop } from "./components/LodopFuncs.js";
import { tbShopPayTypeGet } from "@/api/setting";
import { tbOrderInfoData, tbOrderInfoDownload, payCount } from "@/api/order";
import dayjs from "dayjs";
import { downloadFile } from "@/utils/index";
import QRCode from "qrcode";

import orderDetail from "./components/orderDetail";
import Invoicing from "./components/Invoicing";

export default {
  components: { orderDetail, Invoicing },
  data() {
    return {
      orderEnum,
      payTypes: [],
      timeValue: "",
      resetQuery: null,
      orderType: "",
      query: {
        id: "",
        status: "",
        payType: "",
        orderNo: "",
        createdAt: [],
        productName: ''
      },
      tableData: {
        data: [],
        page: 0,
        size: 10,
        loading: false,
        total: 0
      },
      downloadLoading: false,
      payCountList: "",
      payCountTotal: 0,
      isuppop: false,
      codeinfo: "",
    };
  },

  filters: {
    orderTypeFilter(t) {
      if (t) {
        const item = orderEnum.orderType.find(item => item.key == t);
        return t && item ? item.label : '';
      } else {
        return t;
      }
    },

    sendTypeFilter(t) {
      if (t) {
        const item = orderEnum.sendType.find(item => item.key == t);
        return item ? item.label : '';
      } else {
        return t;
      }
    },
    statusFilter(t) {
      if (t) {
        const item = orderEnum.status.find(item => item.key == t);
        return t && item ? item.label : '';
      } else {
        return t;
      }
    },
    timeFilter(time) {
      return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
    }
  },
  mounted() {


    if (this.$route.query.tableName) {
      this.query.tableName = this.$route.query.tableName
    }
    if (this.$route.query.timeValue) {
      this.timeValue = this.$route.query.timeValue
      this.timeChange(this.timeValue);
    }
    if (this.$route.query.orderNo) {
      this.query.orderNo = this.$route.query.orderNo
    }
    this.resetQuery = { ...this.query };
    this.tbShopPayTypeGet();
    this.getTableData();
    // 从商品库存-库存记录-点击订单号跳转过来
    if (this.$route.query.orderNo) {
      this.query.orderNo = this.$route.query.orderNo
      setTimeout(() => {
        this.getTableData();
      }, 200);
    }

  },
  methods: {
    printEvent(data) {
      console.log('打印方法执行', data)
      let LODOP = getLodop();
      LODOP.PRINT_INIT("打印小票");
      LODOP.SET_PRINTER_INDEX('MHT-POS58');//设置默认打印机(这里用的是打印机名称)
      // 设置打印纸大小D
      LODOP.SET_PRINT_PAGESIZE(3, 800, '', '')
      // 二维码控制大小
      LODOP.ADD_PRINT_BARCODE('', '30px', '150px', '150px', 'QRCode', data.url) //打印产品代码条码
      LODOP.SET_PRINT_MODE('PRINT_PAGE_PERCENT', 'Full-Width ') //设置打印风格，这里是等宽打印
      LODOP.SET_PRINT_STYLE("Alignment", 2);
      // 文字内容
      LODOP.ADD_PRINT_HTM(
        '150px',
        '5px',
        '100%',
        '100%',
        `<div style="width: 100%;font-size: 12px; ">项目分类:${data.article}</div>
        <div style="width: 100%;font-size: 12px; margin-top:6px;">发票类型:${data.type}</div>
        <div style="width: 100%;font-size: 12px; margin-top:6px;">生成时间:${dayjs().format('YYYY-MM-DD HH:mm:ss')}</div>
        <div style="width: 100%;font-size: 12px; margin-top:6px;">*二维码有效期30天,超过自动失效！</div>
        <div style="width: 100%;font-size: 14px; margin-top: 15px;">您可以使用微信，扫码开票</div>`
      )
      LODOP.SET_LICENSES('', 'DCFF409304DFCEB3E2C644BF96CD0720', '', '')
      LODOP.PRINT()

    },
    qrcodeEvent(d) {
      this.codeinfo = d
      this.isuppopEvent()
      setTimeout(() => {
        QRCode.toCanvas(
          this.$refs.canvas,
          this.codeinfo.url, {
          width: 160,
          height: 160,
        }, function (error) {
          console.log(error);
        }
        );
      }, 500);

    },
    isuppopEvent() {
      this.isuppop = !this.isuppop
    },
    //结账
    payOrder(order) {
      console.log(order);
      this.$router.push({
        path: "/tool/Instead/index",
        query: {
          table_name: order.tableName,
          tableId: order.tableId,
          useType: order.useType,
          masterId: order.masterId,
          orderId: order.id,
          key: 'isJieZhang'
        },
      });
    },
    // 获取订单汇总
    async payCount() {
      try {
        const res = await payCount(this.query.createdAt);
        this.payCountList = res;

        let total = 0;
        res.map(item => {
          total += item.payAmount;
        });
        this.payCountTotal = Math.floor(total * 100) / 100;
      } catch (error) {
        console.log(error);
      }
    },
    // 导出Excel
    async downloadHandle() {
      try {
        this.downloadLoading = true;
        const file = await tbOrderInfoDownload({
          orderType: this.orderType,
          shopId: localStorage.getItem("shopId"),
          ...this.query
        });
        downloadFile(file, "订单数据", "xlsx");
        this.downloadLoading = false;
      } catch (error) {
        this.downloadLoading = false;
        console.log(error);
      }
    },
    // 重置查询
    resetHandle() {
      this.timeValue = "";
      this.query = { ...this.resetQuery };
      this.page = 0;
      this.getTableData(true);
    },
    // 分页大小改变
    sizeChange(e) {
      this.tableData.size = e;
      this.getTableData();
    },
    // 分页回调
    paginationChange(e) {
      this.tableData.page = e - 1;
      this.getTableData();
    },
    // 获取商品列表
    async getTableData(switchs = false) {
      this.tableData.loading = true;
      try {
        //   this.payCount();
        const productName = this.query.productName.replace(/\s+/g, '')
        const res = await tbOrderInfoData({
          page: this.tableData.page,
          pageSize: this.tableData.size,
          orderType: this.orderType,
          ...this.query,
          productName,
          userId: switchs == true ? '' : this.$route.query.userId
        });
        this.tableData.loading = false;
        this.tableData.data = res.content;
        this.tableData.total = res.totalElements;
      } catch (error) {
        console.log(error);
      }
    },
    // 切换时间
    timeChange(e) {
      const format = ["YYYY-MM-DD 00:00:00", "YYYY-MM-DD 23:59:59"];
      switch (e) {
        case "":
          // 全部
          this.query.createdAt = [];
          break;
        case "0":
          // 今天
          this.query.createdAt = [
            dayjs().format(format[0]),
            dayjs().format(format[1])
          ];
          break;
        case "-1":
          // 昨天
          this.query.createdAt = [
            dayjs()
              .add(-1, "d")
              .format(format[0]),
            dayjs()
              .add(-1, "d")
              .format(format[1])
          ];
          break;
        case "-7":
          // 最近7天
          this.query.createdAt = [
            dayjs()
              .add(-7, "d")
              .format(format[0]),
            dayjs().format(format[1])
          ];
          break;
        case "-30":
          // 最近7天
          this.query.createdAt = [
            dayjs()
              .add(-30, "d")
              .format(format[0]),
            dayjs().format(format[1])
          ];
          break;
        case "week":
          // 本周
          this.query.createdAt = [
            dayjs()
              .startOf("week")
              .format(format[0]),
            dayjs()
              .endOf("week")
              .format(format[1])
          ];
          break;
        case "month":
          // 本周
          this.query.createdAt = [
            dayjs()
              .startOf("month")
              .format(format[0]),
            dayjs()
              .endOf("month")
              .format(format[1])
          ];
          break;
        case "custom":
          // 自定义
          this.query.createdAt = [];
          break;
        default:
          break;
      }
    },
    // 获取支付方式
    async tbShopPayTypeGet() {
      try {
        const { content } = await tbShopPayTypeGet({
          page: 0,
          size: 100,
          shopId: localStorage.getItem("shopId")
        });
        this.payTypes = content;
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>

<style scoped lang="scss">
.collect_wrap {
  display: flex;
  gap: 14px;

  .item {
    flex: 1;
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    padding: 20px;

    .icon_wrap {
      $size: 34px;
      $border: 6px;
      width: $size;
      height: $size;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: var(--bg-color);
      border-radius: 50%;
      position: relative;

      &::after {
        content: "";
        width: $size + $border;
        height: $size + $border;
        border-radius: 50%;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: var(--bg-color);
        opacity: 0.3;
      }

      .icon {
        font-size: 16px;
        color: #fff;
      }

      .img {
        width: 20px;
        height: 20px;
      }
    }

    .info {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding-left: 10px;

      .m {
        font-weight: bold;
      }

      .t {
        font-size: 12px;
        color: #999;
        padding-top: 4px;
      }
    }
  }
}

.refund {
  color: #ff9731;
  font-weight: bold;
}

.table_order_info {
  .order_no {
    color: #999;
  }

  .type {
    color: #e6a23c;
  }
}

.goods_info {
  .row {
    display: flex;

    &:not(:first-child) {
      margin-top: 10px;
    }

    .cover {
      width: 40px;
      height: 40px;
    }

    .info {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding-left: 10px;

      .sku {
        color: #999;
      }
    }
  }
}

.colorStyle {
  color: #ffc315;
}

.qrStyle {
  width: 100%;
  height: 100%;
  background-color: rgba($color: #000000, $alpha: 0.7);
  position: fixed;
  z-index: 999999;
  top: 0;
  left: 0;

  .box {
    width: 380px;
    height: 320px;
    position: absolute;
    background: #fff;
    top: 26%;
    left: 36%;
    padding: 18px;

    >div:first-child {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    #canvas {
      margin-left: 49%;
      transform: translateX(-80px);
    }

    >div:last-child {
      text-align: center;
    }
  }

}
</style>
