<template>
  <!-- 订单中心 -->
  <div class="orderPage flex-col">
    <s-header :name="'订单中心'" :noback="false"></s-header>
    <div class="orderBox">
      <van-list
        v-model:loading="loading"
        v-model:error="error"
        error-text="请求失败，点击重新加载"
        :finished="finished"
        finished-text="没有更多了"
        offset="300"
        :immediate-check="false"
        @load="onLoad"
      >
        <div class="main3 flex-col justify-center">
          <div class="outer1 flex-col justify-between">
            <div class="group4 flex-row justify-between">
              <div class="ImageText1 flex-col">
                <div class="outer2 flex-row justify-between">
                  <div class="block1 flex-col"></div>
                  <div class="TextGroup1 flex-col">
                    <span class="txt1">数据概览</span>
                  </div>
                </div>
              </div>
              <div class="ImageText2 flex-col" @click="searchClick()">
                <div class="group5 flex-row justify-between">
                  <img class="icon2" src="../../assets/order/search.png" />
                  <div class="TextGroup2 flex-col">
                    <span class="txt2">搜索</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <dateSelectList @update="update($event)"></dateSelectList>
        <typeSelectList @upselectdata="upselectdata($event)"></typeSelectList>
        <div class="outer5 flex-col">
          <div class="block5 flex-col">
            <div class="outerBox flex-row">
              <div class="main4 flex-col justify-between">
                <div class="main5 flex-row justify-center">
                  <span class="word8">&yen;</span>
                  <span class="word9">{{salesVolume}}</span>
                </div>
                <span class="info5">收入总额</span>
              </div>
              <div class="TextGroup7 flex-col">
                <div class="mod3 flex-col justify-between">
                  <span class="txt8">{{salesNumber}}</span>
                  <span class="info6">销售量</span>
                </div>
              </div>
              <div class="TextGroup8 flex-col">
                <div class="outer6 flex-col justify-between">
                  <span class="txt9">{{salesNumber}}</span> <span class="word10">订单数</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="group7 flex-col justify-center">
          <div class="main9 flex-col justify-between">
            <div class="wrap1 flex-row justify-between">
              <div class="ImageText7 flex-col">
                <div class="mod5 flex-row justify-between">
                  <div class="block3 flex-col"></div>
                  <div class="TextGroup7 flex-col">
                    <span class="info3">订单明细</span>
                  </div>
                </div>
              </div>
              <div class="ImageText8 flex-col" @click="gotoOrderExcel()">
                <div class="bd3 flex-row justify-between">
                  <span class="info4 flex-col">导出excel</span>
                  <div class="outer3 flex-col"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="section1 flex-col">
          <div class="group8 flex-col">
            <div class="section4 flex-col">
              <div v-for="(item, index) in orderList" :key="index">
                <div class="section5 flex-col" @click="orderClick(item)">
                  <div class="flex-row align-center">
                    <div class="sugerPhto">
                      <img class="sugerImg" :src="showSugerPhoto(item)" />
                    </div>
                    <div class="flex-col">
                      <div class="flex-row align-center">
                        <div class="main10 flex-col"></div>
                        <span class="txt11">{{ showOrderTime(item) }}</span>
                      </div>
                      <div class="flex-row align-center">
                        <span class="word11"
                          >设备编号：{{ showClientId(item) }}</span
                        >
                        <span class="word13"
                          >商品名称：{{ item.productName }}</span
                        >
                      </div>
                      <div class="flex-row align-end">
                        <div
                          class="pricBox flex-row align-end"
                          :class="{ orderError: item.status === 0 }"
                        >
                          <span class="txt9"
                            >{{item.statusText}}：</span
                          >
                          <span class="info5">&yen;</span>
                          <span class="word12">{{ item.price }}</span>
                        </div>
                        <span class="word14"
                          >分佣：&yen;{{ showSubcom(item) }}</span
                        >
                      </div>
                    </div>
                  </div>
                  <div v-if="typeof item.status === 'undefined'" class="main11 flex-col orderSuccess"></div>
                  <div
                    v-if="item.status === 0 || item.status === 1"
                    class="main11 flex-col"
                    :class="{
                      orderSuccess: item.status === 1,
                      orderError: item.status === 0,
                    }"
                  ></div>
                </div>
                <div class="section6 flex-col"></div>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </div>
    <nav-bar></nav-bar>
    <!-- 搜索弹出框 -->
    <orderSearch ref="searchRef" @search="search($event)"></orderSearch>
    <!-- 退款弹窗 -->
    <van-popup v-model:show="refundType" position="bottom">
      <div class="refundBox flex-col">
        <div class="section1 flex-col">
          <div class="group3 flex-col">
            <div class="TextGroup1 flex-col">
              <div class="outer1 flex-col">
                <!-- <span class="txt4">这里是设备名称</span> -->
                <span class="info1">商家</span>
                <span class="txt5">+{{ refundObject.price }}</span>
              </div>
            </div>
            <div class="layer1 flex-col"></div>
            <div class="layer2 flex-row justify-between">
              <span class="info2">订单编号</span>
              <span class="txt6">{{ refundObject.sn }}</span>
            </div>
            <div class="layer3 flex-row justify-between">
              <span class="word2">商品</span>
              <span class="info3">{{ refundObject.productName }}</span>
            </div>
            <div class="layer4 flex-row justify-between">
              <span class="word3">分销情况</span>
              <span class="word4">{{showSubcom(refundObject)}}</span>
            </div>
            <div class="layer5 flex-row justify-between">
              <span class="txt7">状态</span>
              <span class="word5">{{ showStatus(refundObject) }}</span>
            </div>
            <div class="layer6 flex-row justify-between">
              <span class="word6">支付方式</span>
              <span class="word7">{{ showPayType(refundObject) }}</span>
            </div>
            <div class="layer7 flex-row justify-between">
              <span class="word8">创建时间</span>
              <span class="info4">{{ showOrderTime(refundObject) }}</span>
            </div>
            <button
              v-if="refundObject.status === 1"
              class="Button1 flex-col align-center"
              @click="refundAjax(refundObject)"
            >
              <span class="info5">发起退款</span>
            </button>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { onMounted, reactive, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import navBar from "@/components/NavBar";
import orderSearch from "./orderSearch.vue";
import { getOrderList, refundOrder } from "@/service/order/index";
import { Toast } from "vant";
import { getLoginUser } from "@/common/js/utils";
import dateUtil from "@/utils/dateUtil";
import dateSelectList from "@/components/dateSelectList";
import typeSelectList from "@/components/typeSelectList";
import { useRouter } from 'vue-router';
import { getStatistics } from "@/service/home";

export default {
  name: "order",
  components: { sHeader, navBar, orderSearch, dateSelectList, typeSelectList },
  setup() {
    const user = getLoginUser();
    const router = useRouter();
    const searchRef = ref(null);
    const orderList = ref([]);
    const orderTotal = ref(0);
    const loading = ref(false);
    const error = ref(false);
    const finished = ref(false);
    // 滚动加载
    const onLoad = () => {
      if (!finished.value) {
        searchParams.current = searchParams.current + 1;
        getList();
      }
    };
    // 页面列表查询参数
    let searchParams = reactive({
      adminId: "", // 用户账户id
      userName: "", // 用户名 String 没有值时传null
      adminType: "", // 判断是否查全部商户 当用户为商家时，“本商户”这个选项为“所有下级用户”传入一个“all”的值，其他情况传null
      type: user.ifForeign, // 订单类型 用来区分是线上、线下订单，0：线上，1：线下。默认值一般要根据当前登录用户的类型去选择。区分的参数是admin里ifForeign的值。ifForeign=0则type=0.
      payType: "", // 支付方式 全部时传null 0：无需支付 1：硬币 2：纸币 3：硬币+纸币 4：信用卡 5：电子支付 ALIPAY_NATIVE：支付宝主扫 WEIXIN_NATIVE：微信主扫 ALIPAY_CARD：支付宝反扫 WEIXIN_CARD：微信反扫
      productNo: "", // 商品的标识 全部时传null。 Tproductd对象的属性no的值。
      clientId: "", // 设备编号 String
      dateType: "0", // 所选时间类型 String 0：创建时间 1：退款时间
      startDate: "", // 开始时间 Date
      endDate: "", // 结束时间 Date
      current: 1, // 页数
      size: 20, // 页大小
    });
    let chartType = 'day';
    // 获取订单列表数据
    const getList = async () => {
      getStatisticsFun();
      const { data } = await getOrderList(Object.assign({}, searchParams));
      if (data.code === "00000") {
        if (searchParams.current === 1) {
          orderList.value = [];
        }
        // 列表值叠加
        if (data.data) {
          orderList.value = orderList.value.concat(
            data.data.records.map((item) => {
              return {
                ...item,
                statusText: (item.status && item.status === 0) ? '待支付' : (item.status ? '线上支付' : '线下支付'),
              };
            })
          );
          orderTotal.value = data.data.total;
          if (data.data.total === 0 || (data.data.total > 0 && orderList.value.length === data.data.total) || data.data.records.length === 0) {
            finished.value = true;
          }
        } else {
          finished.value = true;
        }
        loading.value = false;
      } else {
        Toast.fail(data.message);
      }
    };
    // 搜索表单点击
    const searchClick = () => {
      console.log("searchClick", searchRef);
      searchRef.value.showSearch();
    };
    // 搜索表单初始化页面及状态查询列表
    const search = (data) => {
      searchParams = Object.assign(searchParams, data);
      finished.value = false;
      searchParams.current = 1;
      getList();
    };
    // 今日、明日、本周、本月、其他时间选择回调
    const update = (uDate) => {
      chartType = uDate.chartType;
      searchParams = Object.assign(searchParams, uDate);
      searchParams.startDate = dateUtil.formateDate(new Date(searchParams.startDate), 'dd/MM/yyyy hh:mm:ss');
      searchParams.endDate = dateUtil.formateDate(new Date(searchParams.endDate), 'dd/MM/yyyy hh:mm:ss');
      search();
    };
    // 商户、支付方式、设备、商品选择回调
    const upselectdata = (uSData) => {
      searchParams = Object.assign(searchParams, uSData);
      search();
    };
    // 初始化页面获取列表
    onMounted(async () => {
      orderList.value = [];
      searchParams.current = 1;
      if (user) {
        // searchParams.adminType = isShowAdmin() ? 'all' : null;
        searchParams.adminId = user.id;
        searchParams.userName = user.username;
        searchParams.startDate = dateUtil.formateDate(
          new Date(new Date(new Date().getTime()).setHours(0, 0, 0, 0)),
          "dd/MM/yyyy hh:mm:ss"
        );
        searchParams.endDate = dateUtil.formateDate(
          new Date(new Date(new Date().getTime()).setHours(23, 59, 59, 59)),
          "dd/MM/yyyy hh:mm:ss"
        );
        finished.value = false;
        getList();
      }
    });
    // 跳转订单导出
    const gotoOrderExcel = () => {
      router.push({ path: "/orderExport" });
    };
    // 订单详情-退款弹窗
    const refundType = ref(false);
    const refundObject = ref({});
    const orderClick = (item) => {
      refundObject.value = item;
      refundType.value = true;
    };
    // 订单商品图片路径处理
    const showSugerPhoto = (item) => {
      return require(`../../assets/order/spunSugar/${item.productName}.png`);
    };
    // 订单时间格式转换
    const showOrderTime = (item) => {
      return item && item.createDate
        ? dateUtil.formateDate(new Date(item.createDate), "yyyy-MM-dd hh:mm:ss")
        : "";
    };
    // 设备编号格式转换
    const showClientId = (item) => {
      return item && item.clientId
        ? item.clientId.substring(item.clientId.length - 6)
        : "";
    };
    // 计算分佣
    const showSubcom = (item) => {
      let subcom = "0";
      switch (item.type) {
        case 2:
          subcom = (item.price * item.agencyProportion).toFixed(2);
          break;
        case 3:
          subcom = (item.price * item.merchantProportion).toFixed(2);
          break;
        case 4:
          subcom = (item.price * item.personageProportion).toFixed(2);
          break;
      }
      return subcom;
    };
    // 弹窗订单状态
    const showStatus = (item) => {
      if (typeof item.status === 'undefined') {
        return '支付成功';
      } else {
        if (item.status === 0) { return '未支付'; }
        if (item.status === 1) { return '已支付'; }
        if (item.status === 2) { return '退款中'; }
        if (item.status === 3) { return '已退款'; }
      }
      return item;
    }
    const paySouerList = [
      { text: '全部', values: null },
      { text: '无需支付', values: 0 },
      { text: '硬币', values: 1 },
      { text: '纸币', values: 2 },
      { text: '硬币+纸币', values: 3 },
      { text: '信用卡', values: 4 },
      { text: '电子支付', values: 5 },
      { text: '支付宝主扫', values: 'ALIPAY_NATIVE' },
      { text: '微信主扫', values: 'WEIXIN_NATIVE' },
      { text: '支付宝反扫', values: 'ALIPAY_CARD' },
      { text: '微信反扫', values: 'WEIXIN_CARD' }
    ];
    // 弹窗支付上述
    const showPayType = (item) => {
      const payType = (user.ifForeign === '0') ? item.frpCode : item.payType;
      const paySoure = paySouerList.filter(i => i.values === payType);
      if (paySoure.length > 0) { return paySoure[0].text } else { return ''; }
    }
    // 退款操作
    const refundAjax = async (item) => {
      const params = { id: item.id };
      const { data } = await refundOrder(params);
      if (data.code) {
        refundType.value = false;
        Toast.success('退款成功');
        orderList.value = [];
        search({});
      } else {
        Toast.fail(data.message);
      }
      console.log(data);
    }
    const salesVolume = ref(0);
    const salesNumber = ref(0);
    // 查询图表
    const getStatisticsFun = async () => {
      const params = {
        adminId: user.id,
        chartType: chartType,
        endDate: dateUtil.formateDate(new Date(searchParams.endDate), 'yyyy-MM-dd hh:mm:ss'),
        ifForeign: user.ifForeign,
        startDate: dateUtil.formateDate(new Date(searchParams.startDate), 'yyyy-MM-dd hh:mm:ss'),
        userName: searchParams.userName,
        equipmentId: searchParams.clientId === '' ? null : searchParams.clientId
      };
      const { data } = await getStatistics(params);
      if (data.code && data.data) {
        salesVolume.value = 0;
        salesNumber.value = 0;
        data.data.series[0].data.forEach(item => {
          salesNumber.value = parseInt(salesNumber.value + item);
        });
        data.data.series[1].data.forEach(item => {
          salesVolume.value = parseInt(salesVolume.value + item);
        });
      }
    };
    return {
      loading,
      error,
      finished,
      onLoad,
      orderList,
      orderTotal,
      searchRef,
      searchClick,
      search,
      update,
      upselectdata,
      gotoOrderExcel,
      refundType,
      refundObject,
      orderClick,
      showSugerPhoto,
      showOrderTime,
      showClientId,
      showSubcom,
      showStatus,
      showPayType,
      refundAjax,
      salesVolume,
      salesNumber,
    };
  },
};
</script>
<style lang="less" scoped>
@import "../../common/style/common.less";
@import "./index.less";
</style>