<template>
  <!-- 做糖列表 -->
  <div class="sugar-page">
    <s-header :name="$t('device.todaysSugarList')" :noback="false"></s-header>

    <div class="content-container">
      <!-- 设备信息栏 -->
      <div class="device-header" v-if="deviceDetal">
        <van-icon name="box" class="device-icon" />
        <span class="device-name"
          >{{ $t("device.equipmentName") }}：{{ deviceDetal?.name || "" }}</span
        >
      </div>

      <!-- 统计卡片 -->
      <div class="stats-card">
        <div class="stats-content">
          <div class="stats-icon-box">
            <van-icon name="bar-chart-o" class="stats-icon" />
          </div>
          <div class="stats-text">
            <div class="stats-title">{{ $t("device.makeRecord.title") }}</div>
            <div class="stats-info">
              <span class="stats-number">{{ total }}</span>
              <span class="stats-unit">{{
                $t("device.makeRecord.total")
              }}</span>
            </div>
          </div>
          <!-- 右侧操作按钮 -->
          <div class="action-buttons">
            <van-icon
              name="filter-o"
              class="action-icon"
              @click="showFilter = true"
            />
            <van-icon
              name="down"
              class="action-icon"
              @click="showExport = true"
            />
          </div>
        </div>
      </div>
      <!-- 筛选弹窗 -->
      <van-popup
        v-model:show="showFilter"
        position="right"
        class="filter-popup"
      >
        <div class="popup-header">
          <h3>{{ $t("device.makeRecord.condition") }}</h3>
          <van-icon name="cross" @click="showFilter = false" />
        </div>

        <div class="filter-content">
          <!-- 设备编号输入 -->
          <div class="filter-item" v-if="deviceDetal == null">
            <label>{{ $t("device.equipmentCodeLabel") }}</label>
            <van-field
              v-model="searchParams.clientId"
              :placeholder="$t('device.equipmentCodePlaceholder')"
              clearable
            />
          </div>

          <!-- 制作状态单选 -->
          <div class="filter-item">
            <label>{{ $t("device.makeRecord.status") }}</label>
            <van-radio-group v-model="searchParams.status">
              <van-cell-group>
                <van-cell
                  v-for="status in statusOptions"
                  :key="status.value"
                  clickable
                  @click="searchParams.status = status.value"
                >
                  <template #title>
                    <span class="status-label">{{ status.label }}</span>
                  </template>
                  <template #right-icon>
                    <van-radio :name="status.value" />
                  </template>
                </van-cell>
              </van-cell-group>
            </van-radio-group>
          </div>

          <!-- 时间范围 -->
          <div class="filter-item">
            <label>{{ $t("device.makeRecord.time") }}</label>
            <div class="date-picker">
              <van-field
                v-model="searchParams.startTime"
                :placeholder="$t('device.makeRecord.startTime')"
                @click="showStartPicker = true"
              />
              <van-field
                v-model="searchParams.endTime"
                :placeholder="$t('device.makeRecord.endTime')"
                @click="showEndPicker = true"
              />
            </div>
          </div>
        </div>

        <!-- 底部操作 -->
        <div class="popup-footer">
          <van-button type="default" @click="handleReset">重置</van-button>
          <van-button type="primary" @click="handleConfirmFilter"
            >筛选</van-button
          >
        </div>
      </van-popup>

      <!-- 时间选择器 -->
      <van-popup v-model:show="showStartPicker" position="bottom">
        <van-date-picker
          :columns-type="columnsType"
          v-model="startDate"
          @confirm="handleStartConfirm"
          @cancel="showStartPicker = false"
        />
      </van-popup>
      <van-popup v-model:show="showEndPicker" position="bottom">
        <van-date-picker
          :columns-type="columnsType"
          v-model="endDate"
          @confirm="handleEndConfirm"
          @cancel="showEndPicker = false"
        />
      </van-popup>

      <!-- 导出弹窗 -->
      <van-dialog
        v-model:show="showExport"
        :title="$t('device.makeRecord.export')"
        :message="$t('device.makeRecord.exportTips')"
        show-cancel-button
        @confirm="handleExport"
      >
      </van-dialog>

      <!-- 做糖列表 -->
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :finished-text="$t('public.noMore')"
        @load="onLoad"
      >
        <van-cell
          v-for="(item, index) in list"
          :key="index"
          offset="200"
          class="sugar-item"
          @click="handleItemClick(item)"
        >
          <template #title>
            <div class="item-content">
              <!-- 商品信息 -->
              <div class="product-info">
                <h4 class="product-name">{{ item.productName }}</h4>

                <!-- 设备编号 -->
                <div class="device-info" v-if="deviceDetal == null">
                  <span class="device-label"
                    >{{ $t("device.equipmentCodeLabel") }}：</span
                  >
                  <van-tag plain type="primary" class="device-id">
                    {{ item.clientId.slice(-6) }}
                  </van-tag>
                </div>
                <div class="time-info">
                  <van-icon name="clock" class="time-icon" />
                  <span class="time-text">{{
                    showDateTime(item.createDate)
                  }}</span>
                </div>
              </div>

              <!-- 状态标识 -->
              <div class="status-box" :class="statusClass(item.status)">
                <van-icon :name="statusIcon(item.status)" class="status-icon" />
                <span>{{ statusText(item.status) }}</span>
              </div>
            </div>
          </template>
        </van-cell>
        <!-- 失败原因弹窗 -->
        <van-dialog
          v-model:show="showReasonDialog"
          :title="$t('device.makeRecord.reason')"
          confirm-button-text=""
        >
          <div class="reason-content">
            <van-icon name="warning" class="reason-icon" />
            <p>{{ selectedItem?.note || $t("device.unknownError") }}</p>
          </div>
        </van-dialog>
      </van-list>
    </div>
  </div>
</template>
<script>
import { onMounted, reactive, computed, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import {
  getDeviceDetal,
  selectMakeList,
  exportMakeList,
} from "@/service/device";
import { showFailToast } from "vant";
import { getLoginUser, $M_ExportFile } from "@/common/js/utils";
import { useRoute } from "vue-router";
import dateUtil from "../../utils/dateUtil";
import { useI18n } from "vue-i18n";

export default {
  setup() {
    const { t } = useI18n();
    const route = useRoute();
    const deviceId = route.query.deviceId;
    const clientId = route.query.clientId;
    const deviceDetal = ref(null);
    const loading = ref(false);
    const finished = ref(false);
    const user = getLoginUser();
    const list = ref([]);
    const total = ref(0);
    const showReasonDialog = ref(false);
    const selectedItem = ref(null);
    const showFilter = ref(false);
    const showExport = ref(false);

    // 时间选择
    const columnsType = ref(["year", "month", "day"]);
    const showStartPicker = ref(false);
    const showEndPicker = ref(false);
    const startDate = ref([
      new Date().getFullYear(),
      new Date().getMonth() + 1,
      new Date().getDate(),
    ]);
    const endDate = ref([
      new Date().getFullYear(),
      new Date().getMonth() + 1,
      new Date().getDate(),
    ]);
    const statusOptions = computed(() => [
      {
        value: "",
        label: t("device.makeRecord.all"),
      },
      {
        value: "0",
        label: t("device.makeRecord.waiting"),
      },
      {
        value: "1",
        label: t("device.makeRecord.success"),
      },
      {
        value: "2",
        label: t("device.makeRecord.warning"),
      },
    ]);
    // 页面列表查询参数
    const searchParams = reactive({
      adminId: user.type == 2 ? user.id : "", // 用户账户id
      status: "", // 制作状态 1：制作中 2：制作失败 0：未制作
      clientId: clientId,
      current: 0, // 页数
      size: 10, // 页大小
      startTime: "", // 开始时间
      endTime: "", // 结束时间
    });

    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      if (deviceId != null) {
        getDeviceDetalFun();
      }
    });

    // 获取设备数据
    const getDeviceDetalFun = async () => {
      const { data } = await getDeviceDetal({
        id: deviceId,
      });
      if (data.code === "00000") {
        deviceDetal.value = data.data;
      } else {
        showFailToast(data.message);
      }
    };

    // 获取做糖列表数据
    const selectSugarListFun = async () => {
      finished.value = false;
      const { data } = await selectMakeList(searchParams);
      if (data.code) {
        list.value = list.value.concat(data.data.records);
        total.value = data.data.total;
        if (list.value.length === data.data.total) {
          finished.value = true;
        }
        loading.value = false;
      } else {
        showFailToast(data.message);
      }
    };
    // 滚动加载
    const onLoad = () => {
      if (!finished.value) {
        searchParams.current = searchParams.current + 1;
        selectSugarListFun();
      }
    };
    const showDoList = (item) => {
      if (!item) {
        return "";
      }
      const currentDate = dateUtil.formateDate(
        new Date(item.modifyDate),
        "yyyy/MM/dd hh:mm:ss"
      );
      return (
        t("device.goods") +
        item.productName +
        t("device.doTime") +
        currentDate +
        t("device.byDeice") +
        item.clientId.slice(-6)
      );
    };

    const showDateTime = (date) => {
      if (!date) {
        return "";
      }
      const currentDate = new Date(
        dateUtil.formateDate(new Date(date), "yyyy/MM/dd hh:mm:ss")
      );
      return dateUtil.timeZoneDate(currentDate);
    };

    const statusClass = (status) => {
      return {
        success: status === "1",
        processing: status === "0",
        failed: status === "2",
      };
    };

    const statusText = (status) => {
      switch (status) {
        case "1":
          return t("device.makeRecord.success");
        case "2":
          return t("device.makeRecord.warning");
        default:
          return t("device.makeRecord.waiting");
      }
    };

    const statusIcon = (status) => {
      switch (status) {
        case "1":
          return "checked";
        case "2":
          return "warning";
        default:
          return "clock";
      }
    };

    // 时间选择
    const handleStartConfirm = ({ selectedValues }) => {
      console.log(selectedValues.join("/"));
      searchParams.startTime = selectedValues.join("/");
      showStartPicker.value = false;
    };

    // 时间选择
    const handleEndConfirm = ({ selectedValues }) => {
      console.log(selectedValues.join("/"));
      searchParams.endTime = selectedValues.join("/");
      showEndPicker.value = false;
    };

    // 制作失败原因
    const handleItemClick = (item) => {
      if (item.status === "2") {
        // 仅失败状态可点击
        selectedItem.value = item;
        showReasonDialog.value = true;
      }
    };

    // 重置
    const handleReset = () => {
      searchParams.status = "";
      searchParams.startTime = "";
      searchParams.endTime = "";
      searchParams.clientId = clientId;
    };

    // 确认
    const handleConfirmFilter = () => {
      showFilter.value = false;
      searchParams.current = 1;
      list.value = [];
      selectSugarListFun();
      console.log(finished.value);
    };

    // 导出
    const handleExport = async () => {
      const { headers, data } = await exportMakeList(
        Object.assign({}, searchParams)
      );
      $M_ExportFile(data, headers);
    };

    return {
      searchParams,
      list,
      deviceDetal,
      loading,
      finished,
      selectSugarListFun,
      showDoList,
      showDateTime,
      statusClass,
      statusText,
      statusIcon,
      total,
      onLoad,
      showReasonDialog,
      selectedItem,
      handleItemClick,
      showFilter,
      statusOptions,
      showExport,
      showStartPicker,
      showEndPicker,
      startDate,
      endDate,
      columnsType,
      handleReset,
      handleConfirmFilter,
      handleStartConfirm,
      handleEndConfirm,
      handleExport,
    };
  },
  components: {
    sHeader,
  },
};
</script>
<style lang="less" scoped>
@import "../../common/style/common";

.sugar-page {
  min-height: 100vh;

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

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

    .device-icon {
      font-size: 18px;
      color: #409eff;
      margin-right: 8px;
    }

    .device-name {
      font-size: 14px;
      color: #333;
    }
  }

  .stats-card {
    background: #ffffff;
    border-radius: 12px;
    padding: 18px;
    margin: 16px 0;
    position: relative;
    overflow: hidden;

    &::before {
      content: "";
      position: absolute;
      top: -20px;
      right: -20px;
      width: 80px;
      height: 80px;
      background: #f0f3ff;
      border-radius: 50%;
    }

    .stats-content {
      display: flex;
      align-items: center;
      position: relative;
      z-index: 1;
    }

    .stats-icon-box {
      width: 36px; // 容器尺寸缩小
      height: 36px; // 容器尺寸缩小
      background: linear-gradient(135deg, #2c87c8 0%, #6b8eff 100%);
      border-radius: 8px; // 圆角缩小
      margin-right: 12px; // 右边距缩小
      display: flex;
      align-items: center;
      justify-content: center;

      .stats-icon {
        font-size: 18px;
        color: white;
      }
    }

    .stats-text {
      .stats-title {
        color: #666;
        font-size: 12px;
        margin-bottom: 4px;
      }

      .stats-info {
        display: flex;
        align-items: baseline;

        .stats-number {
          color: #2c87c8;
          font-size: 22px;
          font-weight: 600;
          margin-right: 6px;
        }

        .stats-unit {
          color: #999;
          font-size: 12px;
        }
      }
    }

    .action-buttons {
      display: flex;
      gap: 16px; // 增大按钮间距
      margin-left: auto; // 确保右对齐

      .action-icon {
        font-size: 24px; // 增大图标尺寸
        color: #ffffff; // 白色图标
        padding: 8px; // 增大点击区域
        background: #2c87c8; // 主题色背景
        border-radius: 8px; // 圆角匹配整体风格
        box-shadow: 0 2px 6px rgba(78, 107, 221, 0.3); // 添加投影
        transition: all 0.2s ease;

        // 悬停效果
        &:active {
          transform: scale(0.95);
          background: #3b5ab3;
          box-shadow: 0 1px 3px rgba(78, 107, 221, 0.2);
        }
      }

      // 单独设置导出按钮颜色
      .van-icon-down {
        background: #66bb6a; // 绿色表示导出操作

        &:active {
          background: #4caf50;
        }
      }
    }
  }

  .sugar-item {
    margin-top: 12px;
    border-radius: 8px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    cursor: pointer;

    :deep(.van-cell__title) {
      overflow: visible;
    }

    .item-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
    }

    .product-info {
      position: relative;
      flex: 1;

      .product-name {
        margin: 0 0 8px 0;
        font-size: 15px;
        color: #333;
      }

      // 设备编号样式
      .device-info {
        margin: 6px 0;
        display: flex;
        align-items: center;

        .device-label {
          color: #888;
          font-size: 12px;
          margin-right: 4px;
        }

        .device-id {
          font-size: 12px;
          padding: 2px 6px;
          background: #f0f7ff;
        }
      }

      .time-info {
        display: flex;
        align-items: center;

        .time-icon {
          font-size: 14px;
          color: #999;
          margin-right: 4px;
        }

        .time-text {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .status-box {
      padding: 4px 10px;
      border-radius: 14px;
      font-size: 12px;
      display: flex;
      align-items: center;

      &.success {
        background: #e8f5e9;
        color: #4caf50;
      }

      &.processing {
        background: #ebf3ff;
        color: #2196f3;
      }

      &.failed {
        background: #fff0f0;
        cursor: pointer;
        color: #ff4444;
        transition: opacity 0.3s;

        &:active {
          opacity: 0.8;
        }
      }

      .status-icon {
        margin-right: 4px;
        font-size: 14px;
      }
    }

    &:active {
      background: #f8f9ff;
    }
  }

  .reason-content {
    padding: 16px;
    display: flex;
    align-items: flex-start;

    .reason-icon {
      color: #ff4444;
      font-size: 18px;
      margin-right: 12px;
      flex-shrink: 0;
    }

    p {
      margin: 0;
      color: #666;
      font-size: 14px;
      line-height: 1.6;
      white-space: pre-wrap;
    }
  }

  .filter-popup {
    width: 85%;
    height: 100%;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      border-bottom: 1px solid #eee;

      h3 {
        margin: 0;
        font-size: 18px;
      }

      .van-icon {
        font-size: 20px;
        color: #999;
      }
    }

    .filter-content {
      padding: 16px;

      .filter-item {
        margin-bottom: 20px;

        label {
          font-size: 14px;
          color: #606266;
          margin-bottom: 8px;
          display: block;
        }

        // 设备编号输入框样式
        .van-field {
          background: #f5f7fa;
          border-radius: 4px;
          padding: 10px 12px;

          &::placeholder {
            color: #c0c4cc;
          }
        }

        .van-radio-group {
          width: 100%;
        }

        .van-cell {
          // 选中状态样式
          &--selected {
            background-color: #f0f3ff;

            .status-label {
              color: #2c87c8;
            }
          }
        }

        .van-radio__icon--checked .van-icon {
          background-color: #2c87c8;
          border-color: #2c87c8;
        }

        .date-picker {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 8px;
        }
      }
    }

    .popup-footer {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      display: flex;
      gap: 12px;
      padding: 16px;
      background: #fff;
      border-top: 1px solid #eee;

      .van-button {
        flex: 1;
      }
    }
  }

  .export-content {
    padding: 16px;

    p {
      color: #666;
      margin: 0 0 12px 0;
    }
  }
}
</style>
