<template>
  <!-- 订单中心 -->
  <div class="orderPage flex-col">
    <s-header :name="$t('orderCenter.orderCenter')" :noback="false"></s-header>
    <div class="orderBox">
      <van-list v-model:loading="loading" v-model:error="error" :error-text="$t('public.requestFailed')"
        :finished="finished" :finished-text="$t('public.noMore')" 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">{{ $t('orderCenter.dataOverview') }}</span>
                </div>
              </div>
            </div>
            <div class="flex-col">
              <div class="main5 flex-row justify-between" @click="searchClick()">
                <img class="label2" src="@/assets/device/searchIcon.png" />
              </div>
            </div>
          </div>
        </div>
        <!-- <img class="img1" referrerpolicy="no-referrer" src="@/assets/line.png" /> -->
        <dateSelectList @update="update($event)"></dateSelectList>
        <typeDownMenu @upselectdata="upselectdata($event)"></typeDownMenu>
        <div v-if="!noData(salesVolume, salesNumber, orderNumber)" class="o-plr-8 o-pt-15">
          <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="word8">{{ currencySymbol }}</span>
                    <span class="word9">{{ salesVolume.toFixed(2) }}</span>
                  </div>
                  <span class="info5">{{ $t("home.totalIncome") }}</span>
                </div>
                <div class="TextGroup7 flex-col">
                  <div class="mod3 flex-col justify-between">
                    <span class="txt8">{{ salesNumber }}</span>
                    <span class="info6">{{ $t("home.productNum") }}</span>
                  </div>
                </div>
                <div class="TextGroup8 flex-col">
                  <div class="outer6 flex-col justify-between">
                    <span class="txt9">{{ orderNumber }}</span>
                    <span class="word10">{{ $t("home.numberOfOrders") }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <kNoData v-else></kNoData>
        <!-- 时间 -->
        <div class="c-text-c" style="font-size: 18px; margin-top: 5px;">
          {{ Format_time(searchParams.startDate, 'YYYY/MM/DD') }}-{{ Format_time(searchParams.endDate, 'YYYY/MM/DD')
          }}
        </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">
                      {{ $t('orderCenter.total') }}
                      <span style="color: #df5e4c; font-size: 18px;">{{ total }}</span>
                      {{ $t('orderCenter.records') }}
                    </span>
                  </div>
                </div>
              </div>
              <div class="ImageText8 flex-col" @click="gotoOrderExcel()">
                <div class="bd3 flex-row justify-between">
                  <span class="info4 flex-col">{{ $t('orderCenter.exportToExcel') }}</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)">

                  <van-card :thumb="showSugerPhoto(item)">
                    <template #title>
                      <span class="word13">{{ $t('orderCenter.tradeName') }}：{{ item.productName }}</span>
                    </template>
                    <template #desc>
                      <span class="word11">{{ $t('orderCenter.equipmentName') }}：{{ item.es }}</span>
                    </template>
                    <template #price>
                      <div class="pricBox flex-row align-end" :class="{ orderError: item.status === 0 }">
                        <span class="txt9">{{ item.statusText }}：
                          <span v-if="user.ifForeign === '0'" class="word14 o-ptb-8">
                            {{ $t('orderCenter.dividingDomesticService') }} ：{{ currencySymbol }}{{ showSubcom(item) }}
                          </span>
                        </span>
                        <!-- 订单明细 - 线下支付 ￥ -->
                        <span class="info5">{{ currencySymbol }}</span>
                        <span class="word12" v-if="item.status === 3">{{ item.price.toFixed(2) }}</span>
                        <span class="word12" v-else>{{ item.refundAmount == null ? item.price.toFixed(2) : (item.price -
      item.refundAmount).toFixed(2) }}</span>
                      </div>
                      <!-- <span v-if="user.ifForeign === '0' && user.isDistribution === '1'" class="giveAway">
                    {{ $t('orderCenter.dividingDomesticService') }} ：{{ currencySymbol }}{{ showSubcom(item) }}
                  </span> -->
                    </template>
                    <template #price-top>
                      <span class="time_01"
                        :style="user.ifForeign == '0' ? 'margin-top: 20px;' : 'margin-top: 40px;'">{{
      $t('orderCenter.paymentTime') }}：{{ showOrderTime(item, 1) }}</span>
                    </template>
                    <template #footer>
                      <span v-if="item.status === 3">x{{ item.refundQuantity }}</span>
                      <span v-else>x{{ item.refundQuantity == null ? item.productNumber : (item.productNumber -
      item.refundQuantity) }}</span>
                    </template>
                  </van-card>
                  <div v-if="typeof item.status === 'undefined'" class="main11 flex-col orderSuccess"></div>
                  <div v-else class="main11 flex-col" :class="{
      orderSuccess: item.status === 1 && (user.ifForeign == '0' || user.ifForeign == null),
      coinOrderSuccess: item.status === 1 && user.ifForeign == '1',
      orderError: item.status === 0,
      refunding: item.status === 2,
      refunded: item.status === 3,
    }"></div>
                </div>
                <!-- <div class="section6 flex-col"></div> -->
              </div>
              <van-back-top style="background-color: #2d87c8;" />
            </div>
          </div>
        </div>
      </van-list>
    </div>
    <!-- 搜索弹出框 -->
    <orderSearch ref="searchRef" @search="search($event)"></orderSearch>
    <!-- 退款弹窗 -->
    <van-popup v-model:show="refundType" position="bottom" round closeable>
      <div class="orderPopBox flex-col">
        <!-- <div class="section1 flex-col"> -->
        <!-- <div class="group3 flex-col"> -->
        <div class="popTopBox l-flex-center">
          <div class="popTopTxtBox flex-col">
            <!-- <span class="txt4">这里是设备名称</span> -->
            <span class="business">{{ $t('orderCenter.business') }}</span>
            <span class="incomePrice">+ {{ refundObject.refundAmount == null ? refundObject.price.toFixed(2) :
      (refundObject.price - refundObject.refundAmount).toFixed(2) }}</span>
          </div>
        </div>
        <div class="line flex-col"></div>
        <!-- <div class="layer2 flex-row justify-between">
              <span class="info2">{{ $t('orderCenter.accountBalance') }}</span>
              <span class="txt6">{{ accountDetail.altAvilBalance }}</span>
            </div> -->
        <div class="orderDetailBox flex-row justify-between">
          <span class="title">{{ $t('orderCenter.orderNo') }}</span>
          <!-- <span class="content">{{ refundObject.sn }}</span> -->
          <van-text-ellipsis class="content" :content="refundObject.sn" :expand-text="$t('orderCenter.seeMore')" :collapse-text="$t('orderCenter.stow')" />
        </div>
        <div v-if="refundObject.status != 0 && user.ifForeign === '0'" class="orderDetailBox flex-row justify-between">
          <span class="title">{{ $t('orderCenter.orderSerialNumberLabel') }}</span>
          <!-- <span class="content">{{ refundObject.trxNo }}</span> -->
          <van-text-ellipsis class="content" :content="refundObject.trxNo" :expand-text="$t('orderCenter.seeMore')" :collapse-text="$t('orderCenter.stow')" />
        </div>
        <div class="orderDetailBox flex-row justify-between">
          <span class="title">{{ $t('orderCenter.commodity') }}</span>
          <!-- <span class="content">{{ refundObject.productName }}</span> -->
          <van-text-ellipsis class="content" :content="refundObject.productName" :expand-text="$t('orderCenter.seeMore')" :collapse-text="$t('orderCenter.stow')" />
        </div>
        <div v-if="user.ifForeign === '0' && user.isDistribution === '1'" class="orderDetailBox flex-row justify-between">
          <span class="title">{{ $t('orderCenter.distribution') }}</span>
          <span class="content">{{ showSubcom(refundObject) }}</span>
        </div>
        <div class="orderDetailBox flex-row justify-between">
          <span class="title">{{ $t('orderCenter.equipmentNo') }}</span>
          <!-- <span class="content">{{ refundObject.clientId }}</span> -->
          <van-text-ellipsis class="content" :content="refundObject.clientId" :expand-text="$t('orderCenter.seeMore')" :collapse-text="$t('orderCenter.stow')" />
        </div>
        <div class="orderDetailBox flex-row justify-between">
          <span class="title">{{ $t('orderCenter.state') }}</span>
          <span class="content">{{ showStatus(refundObject) }}</span>
        </div>
        <div class="orderDetailBox flex-row justify-between">
          <span class="title">{{ $t('orderCenter.paymentMethod') }}</span>
          <!-- <span class="content">{{ showPayType(refundObject) }}</span> -->
          <van-text-ellipsis class="content" :content="showPayType(refundObject)" :expand-text="$t('orderCenter.seeMore')" :collapse-text="$t('orderCenter.stow')" />
        </div>
        <div class="orderDetailBox flex-row justify-between">
          <span class="title">
            {{ refundObject.status === 1 ? $t('orderCenter.paymentTime') : refundObject.status === 3 ?
      $t('orderCenter.refundTime') : $t('orderCenter.creationTime') }}
          </span>
          <!-- <span class="content">{{ showOrderTime(refundObject, 1) }}</span> -->
          <van-text-ellipsis class="content" :content="showOrderTime(refundObject, 1)" :expand-text="$t('orderCenter.seeMore')" :collapse-text="$t('orderCenter.stow')" />
        </div>
        <div v-if="refundObject.status === 3" class="orderDetailBox flex-row justify-between">
          <span class="title">{{ $t('orderCenter.refunded') }}</span>
          <span class="content">{{ refundObject.refundAmount }}</span>
        </div>
        <div v-if="refundObject.status === 3 && orderType == '3'" class="orderDetailBox flex-row justify-between">
          <span class="title">退款原因</span>
          <span class="content">{{ refundObject.refundReason }}</span>
        </div>
        <div class="orderDetailBox flex-row justify-between l-flex-center"
          v-if="(refundObject.status != 0 && refundObject.status != 2) && orderType == '3'">
          <span class="title">是否开发票</span>
          <van-radio-group v-model="isInvoice" direction="horizontal">
            <van-radio :name="1">是</van-radio>
            <van-radio :name="0">否</van-radio>
          </van-radio-group>
          <van-button color="#2c87c8" type="primary" size="small" class="o-p-20" @click="updateInvoice(refundObject.id)"
            style="padding: 10px; margin-left: 20px;">更新</van-button>
        </div>
        <van-field v-if="refundObject.status === 1 && user.ifForeign === '0' && user.type < 2 && orderType != '3'"
          v-model="customerPhone" center label="联系方式" placeholder="消费者联系方式，没有则不填">
        </van-field>
        <!-- 发起退款 -->
        <!-- 非已付款订单，线下订单要隐藏按钮 -->
        <div style="display: flex; justify-content: center; padding-bottom: 20px;">
          <van-button size="small"
            v-if="refundObject.status === 1 && user.ifForeign === '0' && user.type < 2 && orderType != '3'"
            @click="sentRefundMessage(refundObject)" round type="primary" style="padding: 15px 15px; margin-top: 20px;"
            color="#4dc193">
            退款提醒
          </van-button>
          <div v-if="refundObject.status === 1 && user.ifForeign === '0' && user.type < 2" style="width: 20px;">
          </div>
          <van-button size="small"
            v-if="refundObject.status === 1 && user.ifForeign === '0' && isRefund"
            @click="noticeClk(refundObject)" round type="primary" style="padding: 15px 15px; margin-top: 20px;">
            {{ $t('orderCenter.initiateRefund') }}
          </van-button>
        </div>
      </div>
    </van-popup>
    <!-- 退款弹窗 -->
    <kDialog :isCloseForConfirm="false" :dialogTitle="$t('orderCenter.refundTip')"
      :confirmBtnTxt="$t('orderCenter.refundSubmit')" ref="kDialogRef" @confirmclk="confirmClk">
      <template #content>
        <div class="refundBox l-flex-RC" style="overflow-y: auto; overflow-x: hidden; max-height: 40vh;">
          <div v-for="(item, index) in orderDetails" :key="index" class="card01">
            <van-checkbox :disabled="item.price.toFixed(2) <= 0" checked-color="#2c87c8" v-model="isChecked[index]" @change="checkGood(index)"
              icon-size="0.5rem"></van-checkbox>
            <van-card :price="item.price.toFixed(2)" :title="item.productName" :thumb="showSugarPic(item.productNo)">
              <template #footer>
                <van-stepper v-if="item.price.toFixed(2) > 0" v-model="refundNum[index]" @plus="plusRefundGood(index)"
                  @minus="minusRefundGood(index)" theme="round" button-size="22" disable-input
                  :max="item.refundQuantity == null ? item.productNumber : (item.productNumber - item.refundQuantity)" />
                <span v-else>
                  已优惠减免
                </span>
              </template>
            </van-card>
          </div>
        </div>
        <div class="o-mt-5" style="height: 1px; background: #d7d7e2"></div>
        <van-field v-if="orderType === '3'" v-model="cofficentForm.refundReason" rows="2" autosize label="退款原因"
          type="textarea" maxlength="30" :clearable="true" placeholder="请输入退款原因" show-word-limit />
        <div class="btnFooter">
          <!-- <van-checkbox class="checkAllBtn o-mt-5" v-model="checkedAll" @click="checkAll">全选</van-checkbox> -->
          <span></span>
          <div class="o-mt-5">
            <span class="">{{ $t('orderCenter.totalRefund') }}：</span>
            <span class="totalRefund o-pr-15">{{ currencySymbol }} {{ totalRefund.toFixed(2) }}</span>
          </div>
        </div>
      </template>
    </kDialog>
  </div>
</template>
<script>
// import { Api_getOnlineExport } from "../../service/order";
// 导入接口
import { getAdminMch } from "../../service/merchantManage";
// 导入弹窗
import kDialog from "../../components/commom/kDialog/index.vue";
// 导入无数据组件
import { showDialog, showConfirmDialog, showSuccessToast } from 'vant';
import kNoData from "../../components/commom/kNoData/index.vue";
import { onMounted, reactive, ref } from "vue";
import sHeader from "../../components/SimpleHeader";
import orderSearch from "./orderSearch.vue";
import { getOrderList, refundOrder, refundWechatOrder, updateIsInvoice, sentMessage, exportOrder, refundSqbOrder } from "../../service/order/index";
import { showFailToast, showToast, showLoadingToast } from "vant";
import { getLoginUser, $M_IsDate, Format_time, $M_ExportFile, styleUrl } from "../../common/js/utils";
import { getHuifuId } from "../../service/huifuMch/index";
import dateUtil from "../../utils/dateUtil";
import dateSelectList from "../../components/dateSelectList";
import typeDownMenu from "../../components/typeDownMenu";
import { getStatistics } from "../../service/home";
import { useI18n } from "vue-i18n";
export default {
  name: "order",
  components: { sHeader, orderSearch, dateSelectList, typeDownMenu, kNoData, kDialog },
  setup() {
    // 批量修改弹窗
    const kDialogRef = ref(null);
    // 订单明细
    const orderDetails = ref([]);
    // 订单总数
    const total = ref(0);
    // 退款商品选择状态
    const isChecked = ref([]);
    // 全选状态
    const checkedAll = ref(false);
    // 退款总额
    const totalRefund = ref(0);
    // 退款商户数量
    const refundNum = ref([]);
    // 订单类型
    const orderType = ref('');
    // 是否开发票
    const isInvoice = ref(0);
    // 更新是否开发票
    const updateInvoice = (id) => {
      const params = {
        id,
        isInvoice: isInvoice.value,
      }
      showConfirmDialog({
        message: '是否确认更新',
      }).then(() => {
        const { data } = updateIsInvoice(params);
        console.log(data);
      }).catch(() => {
        return;
      });
    }
    // 加载状态
    // const isLoading = ref(false);
    // 监控退款选择框状态
    const checkGood = (index) => {
      if (isChecked.value[index]) {
        totalRefund.value = parseFloat((totalRefund.value + (refundNum.value[index] * orderDetails.value[index].price)).toFixed(2));
      } else {
        if (totalRefund.value > 0) {
          totalRefund.value = parseFloat((totalRefund.value - (refundNum.value[index] * orderDetails.value[index].price)).toFixed(2));
        }
      }
      // 如果都为true，都为全选
      if (isChecked.value.every((value) => value === true)) {
        checkedAll.value = true;
      } else {
        checkedAll.value = false;
      }
    }
    // 点击增加按钮
    const plusRefundGood = (index) => {
      if (isChecked.value[index]) {
        totalRefund.value = parseFloat((totalRefund.value + orderDetails.value[index].price).toFixed(2));
      }
    }
    // 点击减少按钮
    const minusRefundGood = (index) => {
      if (isChecked.value[index]) {
        totalRefund.value = parseFloat((totalRefund.value - orderDetails.value[index].price).toFixed(2));
      }
    }
    // 点击弹出退款弹窗
    const noticeClk = (row) => {
      if (row.orderDetails.length > 0) {
        isChecked.value = [];
        orderDetails.value = [];
        refundNum.value = [];
        checkedAll.value = false;
        totalRefund.value = 0;
        // cofficentForm.price = row.price;
        // cofficentForm.maxPrice = row.price;
        cofficentForm.id = row.id;
        // cofficentForm.maxNumber = row.productNumber;
        // cofficentForm.productNumber = row.productNumber;
        row.orderDetails.forEach(item => {
          if (item.refundStatus == '1' || item.refundStatus == '2') {
            orderDetails.value.push(item);
            if (item.refundQuantity != null) {
              refundNum.value.push(item.productNumber - item.refundQuantity);
            } else {
              refundNum.value.push(item.productNumber);
            }
          }
        });
        // 根据orderDetails的长度，向isChecked添加相应数量的false
        isChecked.value = Array.from({ length: orderDetails.value.length }, () => false);
        kDialogRef.value.openDialog();
      } else {
        showToast("请联系管理员");
        return;
      }
    };
    // 点击全选按钮
    const checkAll = () => {
      isChecked.value.forEach((item, index) => {
        if (checkedAll.value) {
          isChecked.value[index] = true;
        } else {
          isChecked.value[index] = false;
        }
      })
    }
    // 点击确定按钮
    const confirmClk = () => {
      cofficentForm.note = "";
      cofficentForm.productNumber = 0;
      cofficentForm.price = 0;
      isChecked.value.forEach((isCheckedValue, index) => {
        if (isCheckedValue) {
          cofficentForm.note = cofficentForm.note + orderDetails.value[index].id + "-" + refundNum.value[index] + ","
          cofficentForm.productNumber = cofficentForm.productNumber + refundNum.value[index];
        }
      })
      cofficentForm.price = totalRefund.value;
      if (cofficentForm.note === "" || cofficentForm.price === 0 || cofficentForm.price === "") {
        showToast(t('orderCenter.refundPlace'));
        return;
      }
      if (orderType.value === '3' && (cofficentForm.refundReason === "" || cofficentForm.refundReason === null)) {
        showToast('请填写退款原因');
        return;
      }
      showConfirmDialog({
        // title: "提示",
        message: t('orderCenter.refundCheck'),
      }).then(() => {
        // isLoading.value = true; // 开始加载
        refundAjax();
        // isLoading.value = false; // 加载完成

        kDialogRef.value.closeDialog();
      }).catch(() => {
        return;
      });
    }
    const customerPhone = ref(''); // 消费者号码
    // 发送退款提醒短信
    const sentRefundMessage = async (row) => {
      const params = {
        id: row.id,
        customerPhone: customerPhone.value,
      }
      showConfirmDialog({
        message: '是否确认发送短信？',
      }).then(async () => {
        const { data } = await sentMessage(params);
        if (data.code) {
          showSuccessToast(data.data);
        } else {
          showFailToast(data.data);
        }
      }).catch(() => {
        return;
      });
    }
    // 退款操作
    const refundAjax = async () => {
      try {
        // 如果为微信退款
        let data = null;
        if (orderType.value === '3') {
          data = await refundWechatOrder(cofficentForm);
        } else if (orderType.value === '4') {
          data = await refundSqbOrder(cofficentForm);
        } else {
          data = await refundOrder(cofficentForm);
        }
        console.log(data);
        if (data.data.code && data.data.code !== 'B0001') {
          showDialog({
            message: t('orderCenter.refundSucceeded'),
          }).then(() => {
            refundType.value = false;
            // on close
            orderList.value = [];
            search({});
          });
        } else {
          showFailToast(data.data.message);
        }
      } catch (error) {
        showFailToast(t('orderCenter.requestFailed'));
      }
    };
    // 修改的价格
    const cofficentForm = reactive({
      price: 0,
      id: "",
      productNumber: 0,
      note: 0,
      refundReason: "",
    });
    // 引入语言
    const { t } = useI18n();
    // 订单商品图片路径处理
    const showSugerPhoto = (row) => {
      if (row.orderDetails != null) {
        if (row.orderDetails.length > 0) {
          return require(`../../assets/order/spunSugar/goods/${row.orderDetails[0].productNo}.png`);
        } else {
          if (row.productNo != null) {
            return require(`../../assets/order/spunSugar/goods/${row.productNo}.png`);
          }
          if (row.machineType == null || row.machineType == '0') {
            return require(`../../assets/order/spunSugar/goods/A01.png`);
          } else {
            return require(`../../assets/order/spunSugar/goods/B01.png`);
          }
        }
      } else {
        if (row.machineType == null || row.machineType == '0') {
          return require(`../../assets/order/spunSugar/goods/A01.png`);
        } else {
          return require(`../../assets/order/spunSugar/goods/B01.png`);
        }
      }
    };
    // 订单明细商品图片路径处理
    const showSugarPic = (row) => {
      return require(`../../assets/order/spunSugar/goods/${row}.png`);
    };
    // 如果是空数据
    const noData = (volumes, nums) => {
      if (!volumes && !nums) {
        return true;
      }
      return false;
    };
    const user = getLoginUser();
    const searchRef = ref(null);
    const huifuId = ref(null);
    const orderList = ref([]);
    const orderTotal = ref(0);
    const loading = ref(true);
    const error = ref(false);
    const finished = ref(false);
    // 滚动加载
    const onLoad = () => {
      if (!finished.value) {
        loading.value = true;
        searchParams.current = searchParams.current + 1;
        getList();
      }
    };

    // 自定义货币符号
    const currencySymbol = ref("￥");
    if (user.currencySymbol) {
      currencySymbol.value = user.currencySymbol;
    } else {
      currencySymbol.value = "￥";
    }

    // 页面列表查询参数
    let searchParams = reactive({
      adminId: "", // 用户账户id
      userName: "", // 用户名 String 没有值时传null
      adminType: "", // 判断是否查全部商户 当用户为商家时，“本商户”这个选项为“所有下级用户”传入一个“all”的值，其他情况传null
      type: user.ifForeign, // 订单类型 用来区分是国内、海外订单，0：国内，1：海外。默认值一般要根据当前登录用户的类型去选择。区分的参数是admin里ifForeign的值。ifForeign=0则type=0.
      // ifForeign现在用于区分国内0，海外1
      // isAir海外又分为两种情况，0/null为线下，1是线上
      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: 0, // 页数
      size: 15, // 页大小
      status: 1,//支付状态
      companyType: "", // 公司平台
      machineType: "", // 设备类型
      ifForeign: "",
      username: "",
    });

    let chartType = "day";
    // 获取订单列表数据
    const getList = async () => {
      finished.value = false;
      getStatisticsFun();
      // 因为订单的时间格式不一样
      const params = Object.assign({}, searchParams);
      if ($M_IsDate(params.startDate)) {
        params.startDate = dateUtil.formateDate(
          new Date(params.startDate),
          "yyyy-MM-dd hh:mm:ss"
        );
      } else {
        params.startDate = "";
      }
      if ($M_IsDate(params.endDate)) {
        params.endDate = dateUtil.formateDate(
          new Date(params.endDate),
          "yyyy-MM-dd hh:mm:ss"
        );
      } else {
        params.endDate = "";
      }

      // 获取订单列表
      const { data } = await getOrderList(Object.assign({}, params));
      total.value = 0;
      if (data.code === "00000") {
        if (data.data.total === 0) {
          finished.value = true;
        } else {
          // orderTotal.value = data.data.total;
          total.value = data.data.total;
          if (params.current === 1) {
            orderList.value = [];
            orderTotal.value = 0;
          }
          // 列表值叠加
          if (data.data.records.length > 0) {
            orderList.value = orderList.value.concat(
              data.data.records.map((item) => {
                return {
                  ...item,
                  statusText:
                    item.altInfo != null
                      ? t('orderCenter.onlinePayment')
                      : t('orderCenter.offlinePayment'),
                };
              })
            );
            orderTotal.value = data.data.records.length + orderTotal.value;
            if (orderTotal.value === data.data.total) {
              finished.value = true;
            }
          } else {
            finished.value = true;
          }
        }
        loading.value = false;
      } else {
        // error.value = true;
        showToast(t('orderCenter.noOrderData'));
        finished.value = true;
        loading.value = false;
      }
    };
    // 搜索表单点击
    const searchClick = () => {
      searchRef.value.showSearch();
    };
    // 搜索表单初始化页面及状态查询列表
    const search = (data) => {
      searchParams = Object.assign(searchParams, data);
      // 这个会导致请求两次接口
      // finished.value = false;
      orderList.value = [];
      loading.value = true;
      searchParams.current = 1;
      getList();
    };
    // 今日、明日、本周、本月、其他时间选择回调
    const update = (uDate) => {
      chartType = uDate.chartType;
      searchParams = Object.assign(searchParams, uDate);
      searchParams.type = searchParams.ifForeign;
      search();
    };
    // 商户、支付方式、设备、商品选择回调
    const upselectdata = (uSData) => {
      // console.log('uSData', uSData)
      searchParams = Object.assign(searchParams, uSData);
      // console.log('searchParams', searchParams)
      searchParams.type = searchParams.ifForeign;
      search();
    };
    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      styleUrl('orderCenter');
      // orderList.value = [];
      // searchParams.current = 1;
      if (user) {
        searchParams.adminId = user.id;
        searchParams.userName = user.username;
        const { data } = await getHuifuId({
          adminId: user.id,
        });
        if (data.code === '00000') {
          if (data.data != null) {
            huifuId.value = data.data.huifuId;
          }
        }

        // 获取当天
        let now = new Date();
        let startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
        searchParams.startDate = dateUtil.formateDate(startDate, "yyyy-MM-dd hh:mm:ss");

        let endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
        searchParams.endDate = dateUtil.formateDate(endDate, "yyyy-MM-dd hh:mm:ss");

        // finished.value = false;
        // loading.value = true;
        // getList();
        onLoad();
        addEventListener('load', onLoad);
        // 获取账户详情
        if (user.ifForeign === '0') {
          getAccountDetail(user.id);
        }
      }
    });

    // 查询是否有退款权限
    const isRefund = user.menuCodeList.some((item) => {
      return item === "M16";
    });

    // 跳转订单导出
    const gotoOrderExcel = async () => {
      if (total.value > 30000) {
        showToast(t('orderCenter.exportTips'));
        return;
      }
      if (searchParams.type == null || searchParams.type == '') {
        searchParams.type = user.ifForeign;
      }
      // 显示加载框
      const downloadOrder = showLoadingToast({
        forbidClick: true,
        duration: 0,
      });
      try {
        // const { headers, data } = await Api_getOnlineExport(searchParams);
        const { headers, data, status } = await exportOrder(searchParams);
        // 请求完成后隐藏加载框
        // downloadOrder.close();
        $M_ExportFile(data, headers);
        if (status == 200) {
          downloadOrder.close();
          showSuccessToast({
            message: t('orderCenter.exportSuccess'),
            forbidClick: true,
            duration: 2000,
          });
        } else {
          downloadOrder.close();
        }
        // 处理返回的数据
      } catch (error) {
        // 请求发生错误时隐藏加载框
        downloadOrder.close();
        // 处理错误情况
        console.error(error);
      } finally {
        downloadOrder.close();
      }
    };
    // 订单详情-退款弹窗
    const refundType = ref(false);
    const refundObject = ref({});
    const orderClick = (item) => {
      //查询商户余额，要用admin的type去区分 TODO
      refundObject.value = item;
      orderType.value = item.payPlatform;
      isInvoice.value = item.isInvoice;
      refundType.value = true;
    };
    const accountDetail = ref({});
    // 获取账户详情
    const getAccountDetail = (id) => {
      getAdminMch({ id }).then(res => {
        accountDetail.value = res.data.data;
      })
    };
    // 订单时间格式转换
    const showOrderTime = (item, idx) => {
      if (idx === 1) {
        switch (item.status) {
          case 1:
            return dateUtil.timeZoneDate(new Date(dateUtil.formateDate(new Date(item.payDate), "yyyy/MM/dd hh:mm:ss")));
          case 3:
            return dateUtil.timeZoneDate(new Date(dateUtil.formateDate(new Date(item.refundDate), "yyyy/MM/dd hh:mm:ss")));
          default:
            return dateUtil.timeZoneDate(new Date(dateUtil.formateDate(new Date(item.createDate), "yyyy/MM/dd hh:mm:ss")));
        }
      } else {
        return item && item.createDate
          ? dateUtil.timeZoneDate(new Date(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";
      if (item.altInfo) {
        const altInfo = JSON.parse(item.altInfo);
        if (altInfo && altInfo.length > 0) {
          // altInfo这个属性里，最后一个实体的altAmount的值就是他的分佣。
          subcom = altInfo[altInfo.length - 1]['altAmount'];
        }
      }
      if (item.acctSplitBunch) {
        const data = JSON.parse(item.acctSplitBunch);
        const targetObj = data.acct_infos.find(obj => obj.huifu_id === huifuId.value);
        if (targetObj) {
          subcom = targetObj.div_amt;
        }
      }
      return subcom;
    };
    // 弹窗订单状态
    const showStatus = (item) => {
      if (typeof item.status === "undefined") {
        return t('orderCenter.paymentSucceeded');
      } else {
        if (item.status === 0) {
          return t('orderCenter.unpaid');
        }
        if (item.status === 1) {
          return t('orderCenter.paid');
        }
        if (item.status === 2) {
          return t('orderCenter.refundInProgress');
        }
        if (item.status === 3) {
          return t('orderCenter.refunded');
        }
      }
      return item;
    };
    const paySouerList = [
      { text: t('orderCenter.whole'), values: null },
      { text: t('orderCenter.noPaymentRequired'), values: 0 },
      { text: t('orderCenter.coin'), values: 1 },
      { text: t('orderCenter.notes'), values: 2 },
      { text: t('orderCenter.coinsNotes'), values: 3 },
      { text: t('orderCenter.creditCard'), values: 4 },
      { text: t('orderCenter.electronicPayment'), values: 5 },
      { text: t('orderCenter.mainSweepOfAlipay'), values: "ALIPAY_NATIVE" },
      { text: t('orderCenter.weChatScanning'), values: "WEIXIN_NATIVE" },
      { text: t('orderCenter.antiScanningOfAlipay'), values: "ALIPAY_CARD" },
      { text: t('orderCenter.weChatBackScanning'), values: "WEIXIN_CARD" },
      { text: t('orderCenter.weChatBackScanning'), values: "WEIXIN_PAYCODE" },
      { text: t('orderCenter.eCNYBackeScanning'), values: 'ECNY_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 salesVolume = ref(0);
    const salesNumber = ref(0);
    const orderNumber = ref(0);
    // 查询图表
    const getStatisticsFun = async () => {
      // console.log('searchParams', searchParams)
      const params = {
        adminId: user.id,
        chartType: chartType,
        endDate: searchParams.endDate,
        ifForeign: searchParams.ifForeign == '' ? user.ifForeign : searchParams.ifForeign,
        startDate: searchParams.startDate,
        userName: searchParams.userName,
        username: searchParams.username,
        clientId:
          searchParams.clientId === "" ? null : searchParams.clientId,
        equipmentId:
          searchParams.equipmentId === "" ? null : searchParams.equipmentId,
        payType:
          searchParams.payType === "" ? null : searchParams.payType,
        companyType: searchParams.companyType,
        machineType: searchParams.machineType,
        isAir: searchParams.isAir === "" ? null : searchParams.isAir,
      };
      const { data } = await getStatistics(params);
      if (data.code && data.data) {
        salesVolume.value = 0;
        salesNumber.value = 0;
        orderNumber.value = 0;
        data.data.series[0].data.forEach((item) => {
          salesNumber.value = parseInt(salesNumber.value + item);
        });
        data.data.series[1].data.forEach((item) => {
          salesVolume.value = parseFloat(salesVolume.value) + parseFloat(item);
        });
        data.data.series[2].data.forEach((item) => {
          orderNumber.value = parseInt(orderNumber.value + item);
        });
      }
    };
    return {
      user,
      loading,
      error,
      finished,
      onLoad,
      orderList,
      orderTotal,
      searchRef,
      searchClick,
      search,
      update,
      upselectdata,
      gotoOrderExcel,
      refundType,
      refundObject,
      orderClick,
      showSugerPhoto,
      showOrderTime,
      showClientId,
      showSubcom,
      showStatus,
      showPayType,
      salesVolume,
      salesNumber,
      orderNumber,
      noData,
      kDialogRef,
      noticeClk,
      confirmClk,
      sentRefundMessage,
      customerPhone,
      cofficentForm,
      accountDetail,
      Format_time,
      searchParams,
      orderDetails,
      huifuId,
      showSugarPic,
      isChecked,
      refundNum,
      checkAll,
      checkedAll,
      totalRefund,
      checkGood,
      plusRefundGood,
      minusRefundGood,
      // isLoading,
      isRefund,
      currencySymbol,
      orderType,
      isInvoice,
      updateInvoice,
      total,
    };
  },
};
</script>
<style lang="less" scoped>
@import "../../common/style/common.less";
@import "../../styles/orderCenter/index.less";
</style>