<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)">
              导出
            </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="company-name">{{ item.queryCustomer }}</text>
              </view>
              <view class="header-right">
                <text class="status-tag">黑名单</text>
              </view>
            </view>

            <view class="card-body">
              <view class="code-row">
                <text class="label">信用代码：</text>
                <text class="value code-text">{{ item.socialCreditCode }}</text>
              </view>
              <view class="info-grid">
                <view class="info-item">
                  <text class="label">省份</text>
                  <text class="value">{{ item.province }}</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" disabled>
          <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) => {
        const date = item.billTime || "未知日期";
        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();
    const userEmail = uni.getStorageSync('traceCode_useremail')
    this.emailForm.email = userEmail
  },
  methods: {
    formatDate,

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

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

      const today = new Date();
      let fromDateStr = "";
      const toDateStr = formatDate(today, "YYYY-MM-DD");

      if (this.currentFilter === "all") {
        // 全部：最近2个月
        const twoMonthsAgo = new Date();
        twoMonthsAgo.setMonth(today.getMonth() - 2);
        fromDateStr = formatDate(twoMonthsAgo, "YYYY-MM-DD");
      } else {
        const days = parseInt(this.currentFilter);
        const pastDate = new Date();
        pastDate.setDate(today.getDate() - days);
        fromDateStr = formatDate(pastDate, "YYYY-MM-DD");
      }

      request("/blacklist-report/get-export-company-data", {
        fromDate: fromDateStr,//'2024-01-01',
        toDate: toDateStr,//'2026-01-01',
        path: "traceabilityReport/pages/blacklist/history/index.vue",
      }).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/blacklist/detail/index?id=${item.socialCreditCode}&dateStr=${item.billTime}&name=${encodeURIComponent(item.queryCustomer)}`,
      });
    },

    handleExportByDate(data) {
      this.currentExportDate = data.date;
      this.emailModalOpen = true;
      this.emailError = false;
      this.taskId = data.list[0]?.taskId || ''
    },

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

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

      request("/report/sendemail", {
        taskId: this.taskId,
        emailAddress: this.emailForm.email + "@999.com.cn",
        path: "traceabilityReport/pages/blacklist/history/index.vue",
      }).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>
.history-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f7fa;
}

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

.header-section {
  background: linear-gradient(135deg, #2b32b2 0%, #1488cc 100%);
  padding: 30rpx 30rpx 60rpx;
  color: #fff;
  border-bottom-left-radius: 40rpx;
  border-bottom-right-radius: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(20, 136, 204, 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: #2b32b2;
  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: 65rpx;
  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 #1488cc;
}

.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: #1488cc;
  background: #fff;
  border: 2rpx solid #1488cc;
  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;
}

.status-tag {
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  background: #fff1f0;
  color: #f5222d;
  font-weight: 500;
}

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

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

.code-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.code-text {
  font-family: monospace;
  color: #333 !important;
  font-weight: 600 !important;
}

.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: #1488cc;
  margin-bottom: 32rpx;
  background: #ebf3fb;
  padding: 20rpx 24rpx;
  border-radius: 12rpx;
  border-left: 6rpx solid #1488cc;
  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>
