<template>
  <div class="order-center-container">
    <!-- 头部 -->
    <s-header :name="$t('orderCenter.orderCenter')" class="app-header" />

    <!-- 主内容区 -->
    <main class="main-content">
      <div class="overview-header">
        <div class="header-content">
          <h2 class="section-title">
            <van-icon name="bill" color="#637de6"></van-icon>
            {{ $t("orderCenter.dataOverview") }}
          </h2>
          <div class="header-actions">
            <van-icon
              v-if="user.type < 2"
              name="refund-o"
              class="action-btn"
              @click="pushPageList('/refundReminder')"
              size="25"
              color="#ea6754"
            />
            <van-icon
              name="search"
              class="action-btn"
              @click="searchClick()"
              size="25"
              color="#4d6add"
            />
          </div>
        </div>
      </div>
      <!-- 过滤工具栏 -->
      <dateSelectList @update="update($event)"></dateSelectList>
      <typeDownMenu @upselectdata="upselectdata($event)"></typeDownMenu>

      <!-- 数据概览 -->
      <div class="data-overview">
        <!-- 时间 -->
        <div class="metric-cards">
          <div class="metric-card income">
            <div class="card-content">
              <div class="metric-value">
                <span class="currency">{{ currencySymbol }}</span>
                {{ salesVolume.toFixed(2) }}
              </div>
              <div class="metric-label">{{ $t("home.totalIncome") }}</div>
            </div>
          </div>

          <div class="metric-card secondary">
            <div class="card-content">
              <div class="metric-value">{{ salesNumber }}</div>
              <div class="metric-label">{{ $t("home.productNum") }}</div>
            </div>
          </div>
        </div>
      </div>
      <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="order-list-section">
        <div class="list-header">
          <div class="total-records">
            {{ $t("orderCenter.total") }}
            <span class="highlight">{{ total }}</span>
            {{ $t("orderCenter.records") }}
          </div>
          <van-icon
            name="upgrade"
            class="export-btn"
            @click="gotoOrderExcel"
            size="1rem"
            color="#4d6add"
          />
        </div>

        <van-list
          v-model:loading="loading"
          :finished="finished"
          :error="error"
          :error-text="$t('public.requestFailed')"
          :finished-text="$t('public.noMore')"
          @load="onLoad"
        >
          <!-- 订单项 -->
          <div
            v-for="(item, index) in orderList"
            :key="index"
            class="order-item"
            @click="orderClick(item)"
          >
            <div class="order-status-badge" :class="statusClass(item)">
              {{ showPayType(item) }}
            </div>

            <van-card :thumb="showSugerPhoto(item)" :title="item.productName">
              <template #desc>
                <div class="order-meta">
                  <span class="meta-item">
                    <van-icon name="cluster" />
                    {{ item.es }}
                  </span>
                  <span class="meta-item">
                    <van-icon name="clock" />
                    {{ showOrderTime(item, 1) }}
                  </span>
                </div>
              </template>

              <template #price>
                <div class="price-display">
                  <span class="currency">{{ currencySymbol }}</span>
                  <span class="amount" v-if="item.status === 3">{{
                    item.price.toFixed(2)
                  }}</span>
                  <span class="amount" v-else>
                    {{
                      item.refundAmount == null
                        ? item.price.toFixed(2)
                        : (item.price - item.refundAmount).toFixed(2)
                    }}</span
                  >
                  <span class="quantity" v-if="item.status === 3"
                    >x{{ item.refundQuantity }}</span
                  >
                  <span class="quantity" v-else
                    >x{{
                      item.refundQuantity == null
                        ? item.productNumber
                        : item.productNumber - item.refundQuantity
                    }}</span
                  >
                </div>
                <div
                  class="commission-display"
                  v-if="user.ifForeign === '0' && user.isDistribution === '1'"
                >
                  <span class="label">{{
                    $t("orderCenter.dividingDomesticService")
                  }}</span>
                  <span class="value"
                    >{{ currencySymbol }}{{ showSubcom(item) }}</span
                  >
                </div>
                <div
                  class="commission-display"
                  v-if="user.ifForeign === '1' && item.tax != null"
                >
                  <span class="label">{{ $t("orderCenter.tax") }}</span>
                  <span class="value"
                    >{{ currencySymbol
                    }}{{
                      item.tax != null ? item.tax.toFixed(2) : "0.00"
                    }}</span
                  >
                </div>
              </template>
            </van-card>
          </div>
          <van-back-top right="20" bottom="40" />
        </van-list>
      </div>
    </main>

    <!-- 搜索弹出框 -->
    <orderSearch ref="searchRef" @search="search($event)"></orderSearch>
    <!-- 退款弹窗 -->
    <van-popup v-model:show="refundType" position="bottom" round closeable>
      <div class="orderPopBox flex-col">
        <div class="popTopBox l-flex-center">
          <div class="popTopTxtBox flex-col">
            <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="orderDetailBox flex-row justify-between"
          v-if="user.ifForeign === '0' && user.type === 2"
        >
          <span class="title">{{ $t("orderCenter.accountBalance") }}</span>
          <span class="content">{{ "¥ " + balance }} </span>
        </div>
        <div class="orderDetailBox flex-row justify-between">
          <span class="title">{{ $t("orderCenter.orderNo") }}</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>
          <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>
          <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
          v-if="user.ifForeign === '1' && refundObject.tax != null"
          class="orderDetailBox flex-row justify-between"
        >
          <span class="title">{{ $t("orderCenter.tax") }}</span>
          <span class="content">{{
            refundObject.tax != null ? refundObject.tax.toFixed(2) : "0.00"
          }}</span>
        </div>
        <div
          v-if="refundObject.memberCode != null"
          class="orderDetailBox flex-row justify-between"
        >
          <span class="title">{{ $t("orderCenter.memberCode") }}</span>
          <span class="content">{{ refundObject.memberCode }}</span>
        </div>
        <div class="orderDetailBox flex-row justify-between">
          <span class="title">{{ $t("orderCenter.equipmentNo") }}</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>
          <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>
          <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="#4d6add"
            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="clickSendList(refundObject.sn)"
            round
            type="primary"
            style="padding: 15px 15px; margin-top: 20px"
            color="#9F79EE"
          >
            提醒记录
          </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' &&
              user.type < 2 &&
              orderType != '3'
            "
            @click="showSendDialog = true"
            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>

          <!-- 短信发送确认弹窗 -->
          <van-dialog
            v-model:show="showSendDialog"
            title="提醒"
            :showCancelButton="true"
            class="complaint-dialog"
            @confirm="sentRefundMessage(refundObject)"
          >
            <div class="dialog-content">
              <!-- 消费者号码输入 -->
              <div class="input-group">
                <label class="input-label">消费者号码</label>
                <van-field
                  v-model="customerPhone"
                  class="input-field"
                  type="tel"
                  placeholder="没有不填"
                  clearable
                />
              </div>

              <!-- 投诉原因输入 -->
              <div class="input-group">
                <label class="input-label required">投诉原因</label>
                <van-field
                  v-model="reason"
                  class="input-field"
                  rows="3"
                  type="textarea"
                  autosize
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入投诉原因"
                  :border="false"
                />
              </div>
            </div>
          </van-dialog>
        </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"
              v-model="isChecked[index]"
              @change="checkGood(index)"
              icon-size="20px"
              style="width: 25px"
            ></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="0.55rem"
                  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">
          <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>
    <van-dialog
      v-model:show="sendListshow"
      title="提醒记录"
      class="record-dialog"
    >
      <div class="record-list">
        <!-- 表格头部 -->
        <div class="list-header van-hairline--bottom">
          <div class="header-item">发送时间</div>
          <div class="header-item">接收状态</div>
        </div>

        <!-- 数据列表 -->
        <div class="scroll-wrapper">
          <template v-if="sendList.length > 0">
            <div
              v-for="(item, index) in sendList"
              :key="index"
              class="list-item van-hairline--bottom"
            >
              <div class="item-cell time">
                {{ Format_time(item.createDate, "YYYY/MM/DD HH:mm:ss") }}
              </div>
              <div class="item-cell">
                <van-tag :type="getStatusType(item.status)" size="medium">
                  {{ getStatusText(item.status) }}
                </van-tag>
              </div>
            </div>
          </template>

          <!-- 空状态 -->
          <div v-else class="empty-tip">
            <van-icon name="info" />
            暂无提醒记录
          </div>
        </div>
      </div>
    </van-dialog>
  </div>
</template>
<script>
// 导入接口
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, checkBalance } from "../../service/huifuMch/index";
import dateUtil from "../../utils/dateUtil";
import dateSelectList from "../../components/dateSelectList";
import { refundRecord } from "@/service/taskMessage";
import typeDownMenu from "../../components/typeDownMenu";
import { getStatistics } from "../../service/home";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";

export default {
  name: "order",
  components: { sHeader, orderSearch, dateSelectList, typeDownMenu, 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 balance = ref(0);
    // 提醒记录弹窗
    const sendListshow = ref(false);
    // 提醒记录
    const sendList = ref([]);
    // 短信确认弹窗
    const showSendDialog = ref(false);
    const router = useRouter();
    // 更新是否开发票
    const updateInvoice = async (id) => {
      const params = {
        id,
        isInvoice: isInvoice.value,
      };
      showConfirmDialog({
        message: "是否确认更新",
      })
        .then(async () => {
          const { data } = await updateIsInvoice(params);
          if (data.code) {
            showSuccessToast(data.data);
          } else {
            showFailToast(data.data);
          }
        })
        .catch(() => {
          return;
        });
    };
    // 监控退款选择框状态
    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) => {
      cofficentForm.refundReason = "";
      if (row.orderDetails.length > 0) {
        isChecked.value = [];
        orderDetails.value = [];
        refundNum.value = [];
        checkedAll.value = false;
        totalRefund.value = 0;
        cofficentForm.id = row.id;
        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((value, 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({
        message: t("orderCenter.refundCheck"),
      })
        .then(() => {
          refundAjax();
          kDialogRef.value.closeDialog();
        })
        .catch(() => {
          return;
        });
    };
    const customerPhone = ref(""); // 消费者号码
    const reason = ref(""); // 投诉原因
    // 发送退款提醒短信
    const sentRefundMessage = async (row) => {
      const params = {
        id: row.id,
        customerPhone: customerPhone.value,
        adminId: user.id,
        reason: reason.value,
      };
      const { data } = await sentMessage(params);
      if (data.code === "00000") {
        showSuccessToast("发送成功");
      } else {
        showFailToast(data.message);
      }
    };
    // 退款操作
    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);
        }
        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 { 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 cofficentForm = reactive({
      price: 0,
      id: "",
      productNumber: 0,
      note: 0,
      refundReason: "",
      type: user.type,
    });
    // 滚动加载
    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: "",
    });

    let chartType = "day";
    // 获取订单列表数据
    const getList = async () => {
      if (user.type === 4 && user.username === searchParams.userName) {
        loading.value = false;
        finished.value = true;
        return;
      }
      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 {
          total.value = data.data.total;
          // orderTotal.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) => {
      searchParams = Object.assign(searchParams, uSData);
      searchParams.type = searchParams.ifForeign;
      search();
    };
    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      styleUrl("orderCenter");
      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") {
          if (user.payPlatform === "0" || user.payPlatform === null) {
            getAccountDetail(user.id);
          } else if (user.payPlatform === "1") {
            getHuifuBalance(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({
        // message: '加载中...',
        forbidClick: true,
        duration: 0,
      });
      try {
        // const { headers, data } = await Api_getOnlineExport(searchParams);
        const { headers, data, status } = await exportOrder(searchParams);
        // 请求完成后隐藏加载框
        $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();
      }
    };
    // 订单详情-退款弹窗
    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;
        balance.value = res.data.data.altMainBalance;
      });
    };
    // 查询汇付账户余额
    const getHuifuBalance = (id) => {
      checkBalance({ adminId: id }).then((res) => {
        balance.value = res.data.data;
      });
    };
    // 订单时间格式转换
    const showOrderTime = (item, idx) => {
      if (idx === 1) {
        switch (item.status) {
          case 1:
            // if (user.timeZone) {
            //   return DateTime.fromMillis(item.payDate, { zone: user.timeZone }).toFormat('yyyy/MM/dd HH:mm:ss');
            // }
            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 () => {
      const params = {
        adminId: searchParams.adminId === null ? user.id : searchParams.adminId,
        chartType: chartType,
        endDate: searchParams.endDate,
        ifForeign:
          searchParams.ifForeign == ""
            ? user.ifForeign
            : searchParams.ifForeign,
        startDate: searchParams.startDate,
        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);
        });
      }
    };
    // 短信提醒记录弹窗
    const clickSendList = async (sn) => {
      sendListshow.value = true;
      const searchParams = reactive({
        sendAdminId: user.id, // 当前登录账户的id
        current: 1, // 当前页
        size: 20, // 页大小
        sn: sn, // 订单编号
      });
      const { data } = await refundRecord(Object.assign({}, searchParams));
      if (data.code === "00000") {
        sendList.value = data.data.records;
        console.log(sendList.value);
      }
    };
    const getStatusText = (status) => {
      return (
        {
          0: "等待返回",
          1: "接收成功",
          2: "接受失败",
        }[status] || "未知状态"
      );
    };
    const getStatusType = (status) => {
      return (
        {
          0: "warning",
          1: "success",
          2: "error",
        }[status] || "未知状态"
      );
    };
    // 跳转
    const pushPageList = (url) => {
      router.push(url);
    };
    // 订单状态
    const statusClass = (item) => {
      return {
        success: item.status === 1, // 成功订单
        refunded: item.status === 0, // 未支付订单
        refunding: item.status === 2, // 退款中
        error: item.status === 3, // 已退款
      };
    };
    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,
      balance,
      sendListshow,
      clickSendList,
      sendList,
      getStatusText,
      getStatusType,
      pushPageList,
      statusClass,
      showSendDialog,
      reason,
    };
  },
};
</script>
<style lang="less" scoped>
@import "../../common/style/common.less";
// @import "../../styles/orderCenter/index.less";

.order-center-container {
  --primary-color: #4d6add;
  --secondary-color: #07c160;
  --text-primary: #2d354d;
  --text-secondary: #666f8c;
  --background: #f5f7fa;
  --card-radius: 12px;
  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

  background: var(--background);
  min-height: 100vh;

  .app-header {
    box-shadow: var(--shadow);
  }

  .main-content {
    height: calc(100% - 50px);
    overflow: auto;
    overflow-x: hidden;
  }

  /* 过滤工具栏 */
  .filter-toolbar {
    margin-bottom: 20px;

    .filter-item {
      flex: 1;
      background: white;
      border-radius: var(--card-radius);
      box-shadow: var(--shadow);
      padding: 12px;
    }
  }

  .overview-header {
    background: white;
    border-radius: var(--card-radius);
    padding: 0 10px;
    margin: 10px;
    box-shadow: var(--shadow);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .section-title {
        font-size: 15px;
        font-weight: 400;
        color: var(--text-primary);
      }

      .header-actions {
        display: flex;
        gap: 15px;
        margin-right: 5px;
      }
    }
  }

  /* 数据概览 */
  .data-overview {
    background: white;
    border-radius: var(--card-radius);
    padding: 10px;
    margin: 10px;
    box-shadow: var(--shadow);

    .time-range {
      color: var(--text-secondary);
      font-size: 13px;
      text-align: center;
      margin-bottom: 16px;
    }

    .metric-cards {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;

      .metric-card {
        padding: 15px 10px;
        border-radius: 8px;
        text-align: center;

        &.income {
          background: linear-gradient(
            135deg,
            var(--primary-color) 0%,
            #6b8cff 100%
          );
          color: white;
        }

        &.secondary {
          background: linear-gradient(135deg, #ffa26b 0%, #ff7b42 100%);
          color: white;
        }

        .card-content {
          text-align: center;

          .card-icon {
            font-size: 28px;
            margin-bottom: 8px;
          }

          .metric-value {
            font-size: 20px;
            font-weight: 600;
            margin: 8px 0;
            white-space: nowrap;

            .currency {
              font-size: 0.8em;
            }
          }

          .metric-label {
            font-size: 14px;
            opacity: 0.9;
          }
        }
      }
    }
  }

  /* 订单列表 */
  .order-list-section {
    background: white;
    border-radius: var(--card-radius);
    padding: 10px 15px;
    margin: 10px;
    // margin-bottom: 30px;
    box-shadow: var(--shadow);

    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      margin-bottom: 16px;

      .total-records {
        font-size: 18px;
        color: var(--text-secondary);

        .highlight {
          color: var(--primary-color);
          font-weight: 600;
          font-size: 22px;
        }
      }

      .export-btn {
        padding: 5px;
      }
    }

    .order-item {
      position: relative;
      margin-bottom: 20px;
      border-radius: 8px;
      // overflow: hidden;
      background: #fff;
      transition: transform 0.2s;

      &:active {
        transform: translateY(2px);
      }

      .order-status-badge {
        position: absolute;
        top: -5px;
        right: -1.5px;
        padding: 4px 8px;
        border-radius: 0 8px 0 8px;
        font-size: 12px;
        color: white;
        z-index: 1;

        &.success {
          background: var(--secondary-color);
        }

        &.error {
          background: #ff4444;
        }

        &.refunding {
          background: #ff976a;
        }

        &.refunded {
          background: #969799;
        }
      }

      :deep(.van-card) {
        padding: 30px 10px;
        border-radius: 15px;
        box-shadow: 3px 3px 12px 5px rgba(0, 0, 0, 0.08);

        &__title {
          font-size: 15px;
          font-weight: 500;
          margin-bottom: 8px;
        }

        .order-meta {
          display: flex;
          flex-wrap: wrap;
          gap: 12px;
          font-size: 13px;
          color: var(--text-secondary);

          .meta-item {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }

        .van-card__thumb {
          margin-top: 10px;
          width: 80px;
          height: 80px;
        }

        .van-image__img {
          object-fit: contain !important;
        }

        .price-display {
          display: flex;
          align-items: baseline;
          gap: 4px;
          margin-top: 5px;

          .currency {
            color: #4dc193;
            font-size: 16px;
          }

          .amount {
            font-weight: 600;
            color: #4dc193;
            font-size: 15px;
          }

          .quantity {
            margin-left: auto;
            color: var(--text-secondary);
          }
        }

        .commission-display {
          display: flex;
          align-items: baseline;
          gap: 4px;

          .label {
            color: #e59a6d;
            font-size: 11px;
          }

          .value {
            color: #e59a6d;
            font-size: 12px;
          }
        }
      }
    }
  }
}

.orderPopBox {
  background-color: rgba(255, 255, 255, 1);
  height: auto;
  padding: 10px 10px;

  .popTopBox {
    height: 70px;

    .popTopTxtBox {
      .business {
        overflow-wrap: break-word;
        color: rgba(64, 77, 116, 1);
        font-size: 15px;
        font-family: PingFangSC-Medium;
        text-align: center;
        white-space: nowrap;
        line-height: 15px;
        display: block;
      }

      .incomePrice {
        overflow-wrap: break-word;
        color: rgba(223, 94, 76, 1);
        font-size: 20px;
        font-family: PingFangSC-Semibold;
        text-align: center;
        white-space: nowrap;
        line-height: 20px;
        display: block;
        margin-top: 8px;
      }
    }
  }

  .line {
    background-color: rgba(215, 215, 226, 1);
    height: 1px;
    margin: 10px 0;
  }

  .orderDetailBox {
    margin-top: 10px;
    padding: 0 15px;

    .title {
      width: 100px;
      overflow-wrap: break-word;
      color: rgba(135, 135, 166, 1);
      font-size: 13px;
      text-align: left;
      white-space: nowrap;
      line-height: 16px;
      display: block;
    }

    .content {
      width: 200px;
      color: rgba(64, 77, 116, 1);
      font-size: 13px;
      text-align: right;
      line-height: 16px;
    }
  }

  .van-field__label {
    width: 100px;
    color: rgba(135, 135, 166, 1);
    font-size: 13px;
    text-align: left;
  }

  .van-field__control {
    font-size: 13px;
  }

  .van-cell {
    padding: 0 15px;
    margin-top: 8px;
  }
}

.btnFooter {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .checkAllBtn {
    width: 40%;
    padding-left: 15px;
    padding-top: 5px;
    height: 30px;
  }

  .totalRefund {
    color: #df5e4c;
    font-size: 18px;
    font-family: PingFangSC-Semibold;
  }
}

.refundBox {
  display: block;
  justify-content: flex-end;
  /* 水平方向上右对齐 */
  align-items: center;
  /* 垂直方向上居中对齐 */
  flex-direction: column;
  /* 垂直方向上排列子元素 */

  .van-card {
    background-color: #ffff;
    width: 100%;
    padding: 0 5px;
  }

  .van-card__thumb {
    margin-top: 10px;
    width: 60px;
    height: 60px;
  }

  .van-image__img {
    object-fit: contain !important;
  }

  .van-card__title {
    width: 100px;
  }

  .van-card__footer {
    position: absolute;
    top: 25px;
    right: 10px;
    overflow-wrap: break-word;
    font-size: 13px;
    white-space: nowrap;
    line-height: 14px;
    display: block;
  }

  .card01 {
    display: flex;
    margin: 0 15px;
    width: 90%;
    height: auto;
  }

  .van-card__content {
    height: 50px;
  }
}

.record-dialog {
  .record-list {
    max-width: 600px;

    .list-header {
      display: flex;
      padding: 12px;

      .header-item {
        flex: 1;
        font-weight: 500;
        color: #333;
      }
    }

    .scroll-wrapper {
      max-height: 60vh;
      overflow-y: auto;

      .list-item {
        display: flex;
        align-items: center;
        padding: 12px;

        .item-cell {
          flex: 1;

          &.time {
            font-size: 13px;
            color: #666;
          }
        }
      }

      .empty-tip {
        padding: 20px;
        text-align: center;
        color: #999;

        .van-icon {
          display: block;
          margin: 0 auto 8px;
          font-size: 24px;
        }
      }
    }
  }
}

.complaint-dialog {
  :deep(.van-dialog__header) {
    padding: 20px 20px 10px;
    font-size: 18px;
    font-weight: 600;
    // color: --;
  }

  :deep(.van-dialog__content) {
    padding: 0;
  }
}

.dialog-content {
  padding: 0 20px 20px;
}

.input-group {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 25px;
  }
}

.input-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: var(--text-primary);
  font-weight: 500;
}

.input-field {
  background-color: #f9fbfe;
  border-radius: 8px;
  padding: 10px 15px;

  :deep(.van-field__control) {
    font-size: 14px;
    color: var(--text-secondary);
  }
}

@media (max-width: 480px) {
  .dialog-content {
    padding: 0 15px 15px;
  }

  .input-group {
    margin-bottom: 15px;
  }
}
</style>
