<template>
  <div class="coin-return">
    <s-header :name="$t('device.returnCoin')" :noback="false" />

    <div class="content-container">
      <!-- 设备信息卡片 -->
      <div class="device-card">
        <div class="device-header">
          <van-icon name="desktop-o" class="icon" />
          <h3 class="device-name">
            {{ equipmentName }}
          </h3>
        </div>
      </div>

      <!-- 退币操作卡片 -->
      <div class="operation-card">
        <div class="return-control">
          <div class="control-header">
            <van-icon name="wap-nav" class="control-icon" />
            <span class="control-title">{{
              $t("device.returnCoinPage.amount")
            }}</span>
          </div>

          <div class="stepper-container">
            <van-stepper
              v-model="amount"
              :max="50"
              integer
              class="custom-stepper"
            />
            <van-button
              type="primary"
              icon="refund"
              @click="applyReturnCoinClk"
              class="submit-btn"
            >
              {{ $t("device.returnCoinPage.returnCoinBtn") }}
            </van-button>
          </div>
        </div>
      </div>

      <!-- 记录列表卡片 -->
      <div class="record-card">
        <div class="card-header">
          <van-icon name="notes" class="header-icon" />
          <span class="header-title">{{
            $t("device.returnCoinPage.returnCoinRecord")
          }}</span>
        </div>

        <van-list
          v-model:loading="loading"
          :finished="finished"
          :finished-text="$t('public.noMore')"
          @load="onLoad"
        >
          <!-- 记录项 -->
          <div v-for="item in recordList" :key="item.id" class="record-item">
            <div class="info-row">
              <span class="label"
                >{{ $t("device.returnCoinPage.applyTime") }}：</span
              >
              <span class="value">{{ showTime(item.createDate) }}</span>
            </div>
            <div class="info-row">
              <span class="label"
                >{{ $t("device.returnCoinPage.amount") }}：</span
              >
              <span class="value">{{ item.amount }}</span>
            </div>
            <div class="info-row">
              <span class="label"
                >{{ $t("device.returnCoinPage.status") }}：</span
              >
              <van-tag :color="getStatusColor(item.status)" class="status-tag">
                {{ getStatusText(item.status) }}
              </van-tag>
            </div>
            <div v-if="item.status == 2" class="info-row">
              <span class="label"
                >{{ $t("device.returnCoinPage.reason") }}：</span
              >
              <span class="error-text">{{ item.reason }}</span>
            </div>
          </div>
        </van-list>
      </div>
    </div>
  </div>
</template>

<script>
// 导入接口
import { applyReturnCoin, returnCoinList } from "@/service/device/index";
import sHeader from "@/components/SimpleHeader";
import { ref } from "@vue/reactivity";
import { onMounted } from "@vue/runtime-core";
import { useRoute, useRouter } from "vue-router";
import { showConfirmDialog, showFailToast, showToast } from "vant";
import { useI18n } from "vue-i18n";
import { getLoginUser, styleUrl } from "../../../common/js/utils";
import dateUtil from "../../../utils/dateUtil";
import { reactive } from "vue";
export default {
  components: {
    sHeader,
  },
  setup() {
    // 引入语言
    const { t } = useI18n();
    // 路由
    const route = useRoute();
    const router = useRouter();
    const amount = ref(1);
    const user = getLoginUser();
    const equipmentId = ref("");
    const equipmentName = ref("");
    const clientId = ref(route.query.clientId);
    const activeNames = ref(["1"]);
    const recordList = ref([]);
    const loading = ref(false);
    const finished = ref(false);
    const total = ref(0);
    // 刚进页面
    onMounted(() => {
      // 加载样式
      styleUrl("showGoods");
      equipmentId.value = route.query.deviceId || "";
      const name = route.query.name || "";
      if (equipmentId) {
        equipmentName.value = name;
      }
    });

    // 页面列表查询参数
    const searchParams = reactive({
      status: "", // 制作状态 1：制作中 2：制作失败 0：未制作
      clientId: clientId.value,
      current: 0, // 页数
      size: 10, // 页大小
      startTime: "", // 开始时间
      endTime: "", // 结束时间
    });

    // 滚动加载
    const onLoad = () => {
      if (!finished.value) {
        searchParams.current = searchParams.current + 1;
        returnCoinListFun();
      }
    };

    // 获取退币记录列表数据
    const returnCoinListFun = async () => {
      finished.value = false;
      const { data } = await returnCoinList(searchParams);
      if (data.code) {
        recordList.value = recordList.value.concat(data.data.records);
        total.value = data.data.total;
        if (recordList.value.length === data.data.total) {
          finished.value = true;
        }
        loading.value = false;
      } else {
        showFailToast(data.message);
      }
    };

    // 格式化时间
    const showTime = (time) => {
      return dateUtil.timeZoneDate(
        new Date(dateUtil.formateDate(new Date(time), "yyyy/MM/dd hh:mm:ss"))
      );
    };

    // 退币申请
    const applyReturnCoinClk = () => {
      const params = {
        equipmentId: equipmentId.value,
        amount: amount.value,
        adminId: user.id,
      };
      showConfirmDialog({
        title: t("alramClean.tips"),
        message: t("device.returnCoinPage.tipsContent"),
      })
        .then(async () => {
          const { data } = await applyReturnCoin(params);
          console.log("data>>>", data);
          if (data.code) {
            showToast(t("alramClean.successfully"));
            setTimeout(() => {
              router.go(-1);
            }, 1500);
          } else {
            showFailToast(data.message);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    };

    const getStatusText = (status) => {
      return status === 1
        ? t("device.returnCoinPage.returnCoinSuccess")
        : status === 2
        ? t("device.returnCoinPage.returnCoinFailed")
        : t("device.returnCoinPage.waiting");
    };

    const getStatusColor = (status) => {
      return (
        {
          1: "#4dc294",
          2: "#ee0a24",
          0: "#ff976a",
        }[status] || "#969799"
      );
    };

    return {
      equipmentName,
      applyReturnCoinClk,
      amount,
      activeNames,
      recordList,
      showTime,
      loading,
      finished,
      onLoad,
      getStatusText,
      getStatusColor,
    };
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4d6add;
@card-bg: #ffffff;
@text-primary: #2d3436;
@border-color: #e4e7ec;

.content-container {
  background: #f5f6fa;
  // padding: 16px;
  height: calc(100% - 55px);
  overflow: auto;
  overflow-x: hidden;
}

.coin-return {
  background: #f8fafb;
  min-height: 100vh;
}

.device-card {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  background: #fff;
  margin: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .device-header {
    display: flex;
    align-items: center;

    .icon {
      font-size: 18px;
      color: #4d6add;
      margin-right: 10px;
    }

    .device-name {
      font-size: 15px;
      color: #404d74;
      margin: 0;
    }
  }
}

.operation-card {
  background: @card-bg;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 15px;
  margin: 10px;

  .return-control {
    .control-header {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      .control-icon {
        color: @primary-color;
        font-size: 20px;
        margin-right: 8px;
      }

      .control-title {
        font-size: 15px;
        color: @text-primary;
      }
    }

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

      .custom-stepper {
        :deep(.van-stepper__input) {
          width: 80px;
          background: #f8fafb;
          border-radius: 4px;
        }
      }

      .submit-btn {
        height: 36px;
        padding: 0 20px;
        box-shadow: 0 2px 6px rgba(77, 194, 148, 0.2);
      }
    }
  }
}

.record-card {
  background: @card-bg;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  padding: 16px;
  margin: 10px;

  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .header-icon {
      color: @primary-color;
      font-size: 18px;
      margin-right: 8px;
    }

    .header-title {
      font-size: 15px;
      color: @text-primary;
      font-weight: 500;
    }
  }

  .record-item {
    padding: 12px 0;
    border-bottom: 1px solid @border-color;

    &:last-child {
      border-bottom: none;
    }

    .info-row {
      display: flex;
      align-items: center;
      margin: 8px 0;
      font-size: 14px;

      .label {
        color: #666;
        min-width: 80px;
      }

      .value {
        color: @text-primary;
      }

      .status-tag {
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
      }

      .error-text {
        color: #ee0a24;
        flex: 1;
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 40px 0;

    .empty-icon {
      font-size: 48px;
      color: #c8c9cc;
      margin-bottom: 16px;
    }

    p {
      color: #969799;
      margin: 0;
    }
  }
}

@media (max-width: 480px) {
  .stepper-container {
    flex-direction: column;
    align-items: stretch !important;
    gap: 12px;

    .submit-btn {
      width: 100%;
    }
  }
}
</style>
