<template>
  <Water></Water>
  <view class="history-page">
    <view class="header-section">
      <view class="header-title">历史记录</view>
      <view class="filter-tabs">
        <view class="tab-item" v-for="(tab, index) in timeFilters" :key="index"
          :class="{ active: currentFilter === tab.value }" @click="switchFilter(tab.value)">
          {{ tab.label }}
        </view>
      </view>
    </view>

    <scroll-view class="list-scroll" scroll-y="true" refresher-enabled :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh">
      <view class="list-container">
        <view class="date-group" v-for="groupItem in groupedRows" :key="groupItem.date">
          <view class="date-group-card">
            <view class="group-left">
              <!-- <text class="calendar-icon">📅</text> -->
              <text class="date-label">{{ groupItem.date }}</text>
            </view>
            <button class="group-export-btn" @click.stop="handleExportByDate(groupItem.date)">
              导出
            </button>
          </view>

          <view class="card-item" v-for="(item, index) in groupItem.list" :key="index" @click="toDetail(item)">
            <view class="card-header">
              <view class="header-left">
                <text class="index-num">{{ index + 1 }}</text>
                <text class="company-name">{{ item.customerName }}</text>
                <text class="level-tag" :class="getLevelClass(item.customerLevel)">
                  {{ item.customerLevel }}
                </text>
              </view>
              <view class="header-right">
                <text class="alert-count" v-if="item.totalWarningAmount > 0">{{ item.totalWarningAmount }}次预警</text>
              </view>
            </view>

            <view class="card-body">
              <view class="info-grid">
                <view class="info-item">
                  <text class="label">省份</text>
                  <text class="value">{{ item.customerProvinceName }}</text>
                </view>
                <view class="info-item">
                  <text class="label">性质</text>
                  <text class="value">{{ item.responsibleManager }}</text>
                </view>
                <view class="info-item">
                  <text class="label">责任人</text>
                  <text class="value">{{ item.customerCategory }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view v-if="loading" class="loading-more">
          <image class="loading-icon" src="../../../../static/images/loading.png" />
          <text class="loading-text">加载中...</text>
        </view>

        <view v-if="!loading && rows.length === 0" class="empty-data">
          <EmptyView text="暂无历史记录" />
        </view>
      </view>
    </scroll-view>

    <!-- 蒙层 -->
    <view class="report-export-create-modal-mask" v-if="emailModalOpen" @click="closeEmailModal"
      @touchmove.stop.prevent></view>

    <!-- 邮箱导出弹窗 -->
    <view class="report-export-create-modal report-export-create-email-modal"
      :class="{ 'report-export-create-modal--open': emailModalOpen }" v-if="emailModalOpen">
      <view class="report-export-create-modal-title">
        <text>发送至邮箱</text>
        <view class="report-export-create-modal-close" @click.stop="closeEmailModal">×</view>
      </view>
      <view class="report-export-create-modal-body">
        <view class="export-date-tip">导出日期：{{ currentExportDate }}</view>
        <up-input v-model="emailForm.email" border="none" :customStyle="{
          backgroundColor: '#ebf3fb',
          height: '80rpx',
          paddingLeft: '20rpx',
        }" placeholder="请填写邮箱" @input="emailError = false">
          <template #suffix>
            <view style="margin-right: 20rpx; color: #666">@999.com.cn</view>
          </template>
        </up-input>
        <text v-if="emailError" class="report-export-error-text">请输入邮箱</text>
      </view>
      <view class="report-export-create-modal-footer">
        <view class="report-export-create-modal-btn cancel-btn" @click.stop="closeEmailModal">取消</view>
        <view class="report-export-create-modal-btn confirm-btn" @click.stop="handleSendEmail">发送</view>
      </view>
    </view>
  </view>
</template>

<script>
import EmptyView from "../../../../wigets/empty.vue";
import { formatDate } from "../../../../utils/utils.js";
import request from "../../../../request/index.js";
import Water from "@/components/water/water.vue";


export default {
  components: {
    EmptyView,
    Water
  },
  data() {
    return {
      isRefreshing: false,
      loading: false,
      rows: [],
      currentFilter: "all",
      timeFilters: [
        { label: "全部", value: "all" },
        { label: "近7天", value: "7" },
        { label: "近15天", value: "15" },
        { label: "近30天", value: "30" },
      ],
      emailModalOpen: false,
      emailForm: {
        email: "",
      },
      emailError: false,
      currentExportDate: "",
    };
  },
  computed: {
    groupedRows() {
      const groups = {};
      this.rows.forEach((item) => {
        // 假设接口返回的时间字段为 updatedTime
        const fullTime = item.updatedTime || "";
        const date = fullTime.split(" ")[0] || fullTime.split("T")[0] || "未知日期";
        if (!groups[date]) {
          groups[date] = [];
        }
        groups[date].push(item);
      });
      // 按日期倒序排列
      return Object.keys(groups)
        .sort((a, b) => new Date(b.replace(/-/g, "/")) - new Date(a.replace(/-/g, "/")))
        .map((date) => ({
          date,
          list: groups[date],
        }));
    },
  },
  created() {
    this.resetFetch();
  },
  methods: {
    formatDate,

    getLevelClass(level) {
      if (level === "VIP") return "tag-vip";
      if (level === "二级") return "tag-l2";
      if (level === "三级") return "tag-l3";
      return "tag-default";
    },

    switchFilter(value) {
      if (this.currentFilter === value) return;
      this.currentFilter = value;
      this.resetFetch();
    },

    fetchList() {
      if (this.loading) return;
      this.loading = true;


      let url = '/report/ganmaoling/list?days=-1';
      if (this.currentFilter !== "all") {
        url = `/report/ganmaoling/list?days=${this.currentFilter}`
      }

      request(url, {}, "get").then((res) => {
        if (res.code == 200) {
          this.rows = res.data || [];
        }
        this.loading = false;
        this.isRefreshing = false;
      });
    },

    async onRefresh() {
      this.isRefreshing = true;
      this.fetchList();
    },

    resetFetch() {
      this.rows = [];
      this.fetchList();
    },

    toDetail(item) {
      uni.navigateTo({
        url: `/traceCodePackages/traceabilityReport/pages/ganmaoling/detail/index?name=${encodeURIComponent(item.customerName)}&updatedTime=${item.updatedTime || ""}`,
      });
    },
    handleExportByDate(date) {
      this.currentExportDate = date;
      this.emailModalOpen = true;
      this.emailError = false;
    },

    closeEmailModal() {
      this.emailModalOpen = false;
    },

    handleSendEmail() {
      if (!this.emailForm.email) {
        this.emailError = true;
        return;
      }
      uni.showLoading({ title: "发送中..." });

      // 根据实际接口文档，如果支持按日期导出，则传日期
      request(
        `/report/ganmaoling/sendemail`,
        {
          updatedTime: this.currentExportDate,
          emailAddress: '635509855@qq.com',//this.emailForm.email + "@999.com.cn",
          path: "traceabilityReport/pages/ganmaoling/history/index.vue",
        },
        "post",
      ).then((res) => {
        uni.hideLoading();
        if (res.code == 200) {
          uni.showToast({
            title: "发送成功",
            icon: "success",
          });
          this.closeEmailModal();
        } else {
          uni.showToast({
            title: res.msg || "发送失败",
            icon: "none",
          });
        }
      });
    },
  },
};
</script>

<style scoped>
.level-tag {
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  white-space: nowrap;
  line-height: 1.2;
  margin-left: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-right {
  flex-shrink: 0;
}

.header-left {
  flex: 1;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-right: 20rpx;
  gap: 12rpx;
}

.index-num {
  font-size: 24rpx;
  color: #999;
  font-family: monospace;
}

.company-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #096dd9;
  line-height: 1.4;
  text-decoration: underline;
}

.tag-vip {
  background: linear-gradient(135deg, #e6f7ff, #bae7ff);
  color: #096dd9;
}

.tag-l2 {
  background: linear-gradient(135deg, #f6ffed, #d9f7be);
  color: #389e0d;
}

.tag-l3 {
  background: linear-gradient(135deg, #fff7e6, #ffe7ba);
  color: #d46b08;
}

.history-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f7fa;
}

.header-section {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  padding: 30rpx 30rpx 60rpx;
  color: #fff;
  border-bottom-left-radius: 40rpx;
  border-bottom-right-radius: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(24, 144, 255, 0.2);
  z-index: 10;
  position: relative;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.filter-tabs {
  display: flex;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 16rpx;
  padding: 8rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 26rpx;
  padding: 12rpx 0;
  border-radius: 12rpx;
  color: rgba(255, 255, 255, 0.8);
  transition: all 0.3s;
}

.tab-item.active {
  background: #fff;
  color: #1890ff;
  font-weight: 600;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.list-scroll {
  flex: 1;
  height: 0;
  margin-top: -40rpx;
  z-index: 11;
  padding: 0 24rpx;
  box-sizing: border-box;
}

.list-container {
  padding-top: 50rpx;
  padding-bottom: 40rpx;
}

.date-group {
  margin-bottom: 40rpx;
}

.date-group-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  padding: 20rpx 30rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
  border-left: 8rpx solid #1890ff;
}

.group-left {
  display: flex;
  align-items: center;
}

.calendar-icon {
  font-size: 32rpx;
  margin-right: 16rpx;
}

.date-label {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
}

.group-export-btn {
  margin: 0;
  padding: 0 24rpx;
  height: 52rpx;
  line-height: 50rpx;
  font-size: 24rpx;
  color: #1890ff;
  background: #fff;
  border: 2rpx solid #1890ff;
  border-radius: 26rpx;
  font-weight: 500;
}

.group-export-btn::after {
  border: none;
}

.group-export-btn:active {
  opacity: 0.7;
  transform: scale(0.95);
}

.card-item {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.date-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.alert-count {
  font-size: 22rpx;
  color: #ff4d4f;
  background: rgba(255, 77, 79, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.card-body {
  font-size: 26rpx;
}

.row {
  display: flex;
  margin-bottom: 16rpx;
}

.info-grid {
  display: flex;
  justify-content: space-between;
}

.info-item {
  display: flex;
  align-items: center;
  width: 48%;
}

.label {
  color: #999;
  margin-right: 12rpx;
}

.value {
  color: #666;
  font-weight: 500;
}

.loading-more,
.no-more,
.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
  color: #999;
  font-size: 24rpx;
}

.loading-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 12rpx;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

/* 弹窗样式 */
.report-export-create-modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 999;
  backdrop-filter: blur(2px);
}

.report-export-create-modal {
  position: fixed;
  z-index: 1000;
  background: #fff;
  transition: all 0.3s ease;
}

.report-export-create-email-modal {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 620rpx;
  border-radius: 24rpx;
  opacity: 0;
  visibility: hidden;
  overflow: hidden;
}

.report-export-create-email-modal.report-export-create-modal--open {
  opacity: 1;
  visibility: visible;
}

.report-export-create-modal-title {
  padding: 36rpx 32rpx;
  font-size: 36rpx;
  color: #333;
  text-align: center;
  font-weight: 600;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
}

.report-export-create-modal-close {
  position: absolute;
  right: 32rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 44rpx;
  color: #999;
  line-height: 1;
  padding: 10rpx;
}

.report-export-create-modal-body {
  padding: 40rpx 40rpx 32rpx;
}

.export-date-tip {
  font-size: 26rpx;
  color: #1890ff;
  margin-bottom: 32rpx;
  background: #e6f7ff;
  padding: 20rpx 24rpx;
  border-radius: 12rpx;
  border-left: 6rpx solid #1890ff;
  font-weight: 500;
}

.report-export-error-text {
  font-size: 24rpx;
  color: #ff4d4f;
  margin-top: 12rpx;
  display: block;
}

.report-export-create-modal-footer {
  padding: 0 40rpx 48rpx;
  display: flex;
  justify-content: space-between;
  gap: 24rpx;
}

.report-export-create-modal-btn {
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
  text-align: center;
  font-size: 30rpx;
  font-weight: 600;
  flex: 1;
  margin: 0;
}

.cancel-btn {
  background: #f5f7fa;
  color: #666;
  border: 1rpx solid #e4e7ed;
}

.confirm-btn {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  color: #fff;
  box-shadow: 0 6rpx 16rpx rgba(24, 144, 255, 0.3);
}
</style>
