<template>
  <div class="diy-flower-device-page">
    <!-- 自定义头部 -->
    <s-header
      :name="$t('device.diyFlower')"
      :noback="false"
      class="device-header"
    />

    <!-- 设备信息区域 -->
    <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="control-card">
      <div class="control-status">
        <span class="status-text">
          {{
            checked ? $t("DIYFlower.openStatus") : $t("DIYFlower.closeStatus")
          }}
        </span>
        <van-switch
          :model-value="checked"
          @update:model-value="updateStatus"
          size="24"
          inactive-color="#d1d5db"
        />
      </div>
    </div>

    <!-- 配置选项 - 只在设备开启时显示 -->
    <div v-if="checked">
      <!-- 形状选择 -->
      <div class="config-section">
        <div class="section-header">
          <div class="section-title">
            <van-icon name="apps-o" class="section-icon" />
            {{ $t("DIYFlower.shape") }}
          </div>
        </div>

        <div class="options-container">
          <div class="options-grid">
            <div
              v-for="(item, index) in shapeData"
              @click="clickShape(index)"
              :key="index"
              class="option-item"
              :class="{ 'option-selected': shapeStates[index] }"
            >
              <div class="option-image-wrapper">
                <van-image
                  width="70"
                  height="70"
                  fit="contain"
                  :src="showSugerPhoto(item)"
                  :alt="item.name"
                  class="option-image"
                >
                  <template v-slot:loading>
                    <van-loading type="spinner" size="20" />
                  </template>
                </van-image>
              </div>
              <div class="option-name">{{ item.name }}</div>
              <van-checkbox
                v-model="shapeStates[index]"
                @click="clickShape(index)"
                shape="square"
                class="option-checkbox"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 糖分选择 -->
      <div class="config-section">
        <div class="section-header">
          <div class="section-title">
            <van-icon name="gem-o" class="section-icon" />
            {{ $t("DIYFlower.sugar") }}
          </div>
        </div>

        <div class="options-container">
          <div class="options-grid">
            <div
              v-for="(item, index) in sugarData"
              @click="clickSugar(index)"
              :key="index"
              class="option-item"
              :class="{ 'option-selected': sugarStates[index] }"
            >
              <div class="option-image-wrapper">
                <van-image
                  width="70"
                  height="70"
                  fit="contain"
                  :src="showSugerPhoto(item)"
                  :alt="item.name"
                  class="option-image"
                >
                  <template v-slot:loading>
                    <van-loading type="spinner" size="20" />
                  </template>
                </van-image>
              </div>
              <div class="option-name">{{ item.name }}</div>
              <van-checkbox
                v-model="sugarStates[index]"
                @click="clickSugar(index)"
                shape="square"
                class="option-checkbox"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <van-button
          round
          block
          class="update-button"
          type="primary"
          @click="updateShowGoods()"
        >
          <span>{{ $t("device.submitAndPushDeviceUpdates") }}</span>
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
// 导入接口
import {
  selectDIYFlowers,
  updateDIYFlowerStatus,
  updateDIYProductShow,
} 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 { showDialog, showConfirmDialog, showFailToast, showToast } from "vant";
import { useI18n } from "vue-i18n";
export default {
  components: {
    sHeader,
  },
  setup() {
    // 引入语言
    const { t } = useI18n();
    // 路由
    const route = useRoute();
    const router = useRouter();
    // 商品数据
    const shapeData = ref([]);
    const sugarData = ref([]);

    const switchStates = ref([]);
    const shapeStates = ref([]);
    const sugarStates = ref([]);

    // 设备名称
    const equipmentName = route.query.name;
    const checked = ref(false);
    // 刚进页面
    onMounted(() => {
      // 加载样式
      const id = route.query.deviceId || "";
      const diyFlowerStatus = route.query.diyFlowerStatus || "";

      cofficentForm.equipmentId = id;
      if (diyFlowerStatus == "1") {
        checked.value = true;
        getList();
      }
      console.log("check", checked.value);
    });
    const showSugerPhoto = (row) => {
      let imgId = row.no;
      if (imgId) {
        return require(`../../../assets/device/diyFlowers/${imgId}.png`);
      }
      return imgId;
    };
    // 获取商品列表
    const getList = () => {
      const flower = route.query.flower || "";
      selectDIYFlowers({
        equipmentId: cofficentForm.equipmentId,
      }).then((res) => {
        console.log("res", res);
        const { data } = res.data;
        if (data) {
          if (data.length > 0) {
            // 是否修改状态
            data.forEach((item) => {
              flowerNumber(item, flower);
              if (item.no.includes("T")) {
                sugarData.value.push(item);
                if (item.showType == null || item.showType == "0") {
                  sugarStates.value.push(false);
                } else {
                  sugarStates.value.push(true);
                }
              }
            });
          }
        }
      });
    };
    // 修改的价格
    const cofficentForm = reactive({
      equipmentId: "",
    });

    // 判断花型数目
    const flowerNumber = (item, number) => {
      var shape = null;
      if (number == "18") {
        shape = ["S01", "S02", "S03"];
      } else if (number == "22") {
        shape = ["S01", "S02", "S03", "S04"];
      } else if (number == "26") {
        shape = ["S01", "S02", "S03", "S04", "S05"];
      } else if (number == "30") {
        shape = ["S01", "S02", "S03", "S04", "S05", "S06"];
      } else {
        shape = ["S01", "S02", "S03", "S04", "S05", "S06", "S07", "S08", "S09"];
      }
      if (shape.includes(item.no)) {
        shapeData.value.push(item);
        if (item.showType == null || item.showType == "0") {
          shapeStates.value.push(false);
        } else {
          shapeStates.value.push(true);
        }
      }
    };

    const clickShape = (index) => {
      shapeStates.value[index] = !shapeStates.value[index];
      if (shapeStates.value[index]) {
        shapeData.value[index].showType = 1;
      } else {
        shapeData.value[index].showType = 0;
      }
    };

    const clickSugar = (index) => {
      sugarStates.value[index] = !sugarStates.value[index];
      if (sugarStates.value[index]) {
        sugarData.value[index].showType = 1;
      } else {
        sugarData.value[index].showType = 0;
      }
    };

    // 更改状态
    const shapeChange = (index) => {
      if (shapeStates.value[index]) {
        shapeData.value[index].showType = 1;
      } else {
        shapeData.value[index].showType = 0;
      }
      console.log("形状", shapeData.value[index]);
    };
    const sugarChange = (index) => {
      console.log("index", sugarStates.value[index]);
      if (sugarStates.value[index]) {
        sugarData.value[index].showType = 1;
      } else {
        sugarData.value[index].showType = 0;
      }
      console.log("糖", sugarData.value[index]);
    };

    const updateStatus = (newValue) => {
      const params = {
        equipmentId: cofficentForm.equipmentId,
        DIYFlowerStatus: newValue ? "1" : "0",
      };
      showConfirmDialog({
        title: t("DIYFlower.tips"),
        message: t("DIYFlower.content"),
      })
        .then(async () => {
          const { data } = await updateDIYFlowerStatus(params);
          if (data.code) {
            showToast(t("DIYFlower.successfully"));
            setTimeout(() => {
              router.go(-1);
            }, 1500);
          } else {
            showFailToast(data.message);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    };

    // 点击提交
    const updateShowGoods = () => {
      showConfirmDialog({
        title: t("device.openRemind"),
        message: t("device.editCheck"),
      })
        .then(() => {
          var products = shapeData.value.concat(sugarData.value);
          var list = JSON.stringify(products);
          console.log(list);

          updateDIYProductShow({
            productList: list,
          })
            .then((res) => {
              console.log(res.data.message);
              showDialog({
                message: t("DIYFlower.successfully"),
              }).then(() => {
                //返回上一页
                router.go(-1);
              });
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch((error) => {
          console.log(error);
        });
    };
    const activeNames = ref(["1", "2"]);

    return {
      cofficentForm,
      shapeData,
      sugarData,
      equipmentName,
      updateShowGoods,
      switchStates,
      shapeStates,
      sugarStates,
      shapeChange,
      sugarChange,
      checked,
      showSugerPhoto,
      activeNames,
      updateStatus,
      clickShape,
      clickSugar,
    };
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4d6add;
@card-bg: #ffffff;
@border-color: #e2e8f0;
@text-dark: #1e293b;
@text-light: #64748b;

.diy-flower-device-page {
  min-height: 100vh;
  background-color: #f8fafc;
  padding-bottom: 60px;
}

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

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

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

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

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

.control-card {
  background-color: @card-bg;
  border-radius: 16px;
  margin: 20px 16px;
  padding: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.03);

  .control-status {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .status-text {
      font-size: 15px;
      font-weight: 500;
      color: @text-dark;
    }
  }
}

.config-section {
  background-color: @card-bg;
  border-radius: 16px;
  margin: 16px;
  padding: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.03);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px dashed @border-color;

    .section-title {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      color: @text-dark;

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

  .options-container {
    margin-top: 10px;
  }

  .options-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;

    .option-item {
      position: relative;
      padding: 12px;
      border-radius: 12px;
      background-color: #f8fafc;
      border: 1px solid @border-color;
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
      }

      &.option-selected {
        border-color: @primary-color;
        background-color: #ede9fe;
      }

      .option-image-wrapper {
        position: relative;
        background: white;
        border-radius: 10px;
        padding: 8px;
        text-align: center;
        margin-bottom: 8px;
        transition: all 0.3s ease;
        height: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .option-name {
        font-size: 13px;
        text-align: center;
        color: @text-dark;
        font-weight: 500;
        margin-top: 6px;
        min-height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .option-checkbox {
        position: absolute;
        top: 8px;
        right: 8px;
        z-index: 2;
      }
    }
  }
}

.action-buttons {
  padding: 16px;

  .update-button {
    height: 50px;
    background: linear-gradient(to right, #4d6add, #98a7e0);
    border: none;
    font-size: 16px;
    font-weight: 600;
    box-shadow: 0 4px 10px rgba(124, 58, 237, 0.3);

    .button-loading {
      margin-right: 8px;
    }
  }
}

@media (max-width: 480px) {
  .device-info-card,
  .control-card,
  .config-section {
    margin: 12px;
  }

  .options-grid {
    gap: 12px !important;
  }

  .update-button {
    height: 46px !important;
    font-size: 15px !important;
  }

  .option-item {
    padding: 8px !important;
  }

  .option-image-wrapper {
    height: 80px !important;
  }
}
</style>
