<template>
  <div class="goods-management">
    <!-- 头部优化 -->
    <s-header
      :name="$t('device.showGoodsPage.title')"
      :noback="false"
      class="management-header"
    />
    <div class="content-container">
      <!-- 设备信息卡片 -->
      <div class="device-card">
        <div class="device-info">
          <h3 class="device-name">
            <van-icon name="desktop-o" class="icon" />
            <span class="highlight">{{ equipmentName }}</span>
          </h3>
          <div class="goods-count">
            {{ $t("device.modifyPricePage.total") }}
            <van-tag type="primary">{{ tableData.length }}</van-tag>
            {{ $t("device.modifyPricePage.goods") }}
          </div>
        </div>
      </div>

      <!-- 商品网格布局 -->
      <div class="goods-grid">
        <div v-for="(item, index) in tableData" :key="index" class="goods-card">
          <div class="card-header" v-if="item.no != 'I01'">
            <van-image
              class="goods-thumb"
              fit="cover"
              :src="showSugerPhoto(item)"
            />
            <div class="goods-info">
              <h4 class="goods-title van-ellipsis">{{ item.productName }}</h4>
              <van-switch
                v-model="switchStates[index]"
                size="24px"
                active-color="var(--primary-color)"
                inactive-color="#dcdee0"
                @change="handleChange(index)"
              />
            </div>
          </div>
          <van-divider class="card-divider" />
        </div>
      </div>
      <!-- 粘性底栏提交按钮 -->
      <div class="action-footer">
        <van-button
          round
          block
          type="primary"
          class="submit-btn"
          @click="updateShowGoods"
        >
          <van-icon name="passed" class="btn-icon" />
          {{ $t("device.submitAndPushDeviceUpdates") }}
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
// 导入接口
import {
  selectProducts,
  updateProductsShow,
  newUpdateProductsShow,
} from "@/service/device/index";
import sHeader from "@/components/SimpleHeader";
import { ref, reactive } from "@vue/reactivity";
import { onMounted } from "@vue/runtime-core";
import { useRoute, useRouter } from "vue-router";
import { showFailToast, showDialog, showConfirmDialog } from "vant";
import { useI18n } from "vue-i18n";
export default {
  components: {
    sHeader,
  },
  setup() {
    // 引入语言
    const { t } = useI18n();
    // 商品图片路径处理
    const showSugerPhoto = (row) => {
      let imgId = row.no;
      if (imgId) {
        return require(`../../../assets/order/spunSugar/goods/${imgId}.png`);
      }
      return imgId;
    };
    // 路由
    const route = useRoute();
    const router = useRouter();
    // 商品数据
    const tableData = ref([]);
    const switchStates = ref([]);
    // 设备名称
    const equipmentName = ref("");
    const machineType = ref(route.query.machineType || "");

    // 刚进页面
    onMounted(() => {
      const id = route.query.deviceId || "";
      const name = route.query.name || "";
      if (id) {
        cofficentForm.equipmentId = id;
        equipmentName.value = name;
        getList();
      }
    });
    // 获取商品列表
    const getList = () => {
      selectProducts({
        equipmentId: cofficentForm.equipmentId,
      }).then((res) => {
        console.log("res", res);
        const { data } = res.data;
        if (data) {
          if (data.length > 0) {
            // 是否修改状态
            data.forEach((item) => {
              if (item.no != "I01") {
                if (item.showType == null || item.showType == 0) {
                  switchStates.value.push(true);
                } else {
                  switchStates.value.push(false);
                }
              }
            });
          }
          data.forEach((item) => {
            if (item.no != "I01") {
              tableData.value.push(item);
            }
          });
        }
      });
    };
    // 修改的价格
    const cofficentForm = reactive({
      equipmentId: "",
    });

    // 更改状态
    const handleChange = (index) => {
      if (switchStates.value[index]) {
        tableData.value[index].showType = 0;
      } else {
        tableData.value[index].showType = 1;
      }
    };

    // 点击提交
    const updateShowGoods = () => {
      showConfirmDialog({
        title: t("device.openRemind"),
        message: t("device.editCheck"),
      }).then(() => {
        console.log(tableData.value);
        var products = tableData.value;
        var list = JSON.stringify(products);
        machineType.value === "2"
          ? newUpdateProductsShow({
              productList: list,
            })
          : updateProductsShow({
              productList: list,
            })
              .then((res) => {
                console.log(res.data.message);
                showDialog({
                  message: t("device.modificationSucceeded"),
                }).then(() => {
                  //返回上一页
                  router.go(-1);
                });
                setTimeout(() => {
                  getList();
                }, 1000);
              })
              .catch((error) => {
                console.log(error);
                showFailToast(t("device.unknownError"));
              });
      });
    };
    return {
      cofficentForm,
      tableData,
      showSugerPhoto,
      equipmentName,
      updateShowGoods,
      switchStates,
      handleChange,
    };
  },
};
</script>

<style lang="less" scoped>
.goods-management {
  --primary-color: #4d6add;
  --card-radius: 12px;
  --card-padding: 16px;
  --grid-gap: 12px;

  background: #f7f8fa;

  .content-container {
    background: #f7f8fa;
    height: calc(100% - 50px);
    overflow: auto;
    overflow-x: hidden;
  }
}

/* 设备信息卡片 */
.device-card {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  background: #fff;
  margin: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.device-info {
  flex: 1;
}

.device-name {
  display: flex;
  align-items: center;
  font-size: 16px;
  margin: 0 0 8px;
  color: #404d74;

  .icon {
      font-size: 18px;
      color: var(--primary-color);
      margin-right: 10px;
    }
}

.highlight {
  margin: 0;
  font-size: 15px;
  color: #404d74;
  font-weight: 550;

  // 长名称处理
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 70vw;
}

.goods-count {
  font-size: 14px;
  color: #888;
}

/* 商品网格布局 */
.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: var(--grid-gap);
  padding: 0 16px;
  margin-bottom: 20px;
}

.goods-card {
  background: #fff;
  border-radius: var(--card-radius);
  overflow: hidden;
  transition: transform 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.goods-card:hover {
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  padding: var(--card-padding);
}

.goods-thumb {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  margin-right: 12px;
}

.goods-info {
  flex: 1;
  min-width: 0;
}

.goods-title {
  font-size: 15px;
  margin: 0 0 12px;
  line-height: 1.4;
}

.card-divider {
  margin: 0;
  border-color: rgba(0, 0, 0, 0.05);
}

/* 提交按钮 */
.action-footer {
  position: sticky;
  bottom: 0;
  padding: 16px;
  background: linear-gradient(to top, #fff 70%, rgba(255, 255, 255, 0.8));
}

.submit-btn {
  height: 48px;
  font-size: 16px;
  font-weight: 500;
}

.btn-icon {
  margin-right: 3px;
  font-size: 12px;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .goods-grid {
    grid-template-columns: 1fr;
  }

  .device-card {
    margin: 15px;
    padding: 12px;
  }

  .goods-thumb {
    width: 60px;
    height: 60px;
  }

  .submit-btn {
    height: 44px;
    font-size: 15px;
  }
}

:deep(.van-image__img) {
  object-fit: contain !important;
}
</style>
