<template>
  <div class="sugar-maker">
    <s-header :name="$t('device.remoteSugarMaking')" :noback="false" />

    <!-- 设备信息卡片 -->
    <div class="device-card">
      <div class="device-header">
        <div class="header-indicator"></div>
        <h3 class="device-name">
          {{ $t("device.equipmentName") }}：{{ deviceDetal?.name || "-" }}
        </h3>
      </div>
    </div>

    <!-- 主操作区 -->
    <div class="operation-card">
      <!-- 动态选择器 -->
      <div v-if="[null, '0', '1'].includes(machineType)" class="selector-card">
        <van-field
          v-model="fieldValue"
          is-link
          readonly
          :label="
            machineType === '1'
              ? $t('device.clickToSelectTaste')
              : $t('device.clickToSelectPattern')
          "
          :placeholder="
            machineType === '1'
              ? $t('device.pleaseSelectTaste')
              : $t('device.pleaseSelectAPattern')
          "
          @click="show = true"
          class="smart-field"
        />
        <van-popup v-model:show="show" round position="bottom">
          <van-cascader
            v-model="cascaderValue"
            :title="
              machineType === '1'
                ? $t('device.pleaseSelectTaste')
                : $t('device.pleaseSelectAPattern')
            "
            :options="options"
            @close="show = false"
            @finish="onFinish"
          >
            <template #option="{ option }">
              <div class="cascader-item">
                <van-image
                  :src="option.imgUrl"
                  width="55px"
                  height="55px"
                  class="option-image"
                >
                  <template v-if="!option.imgUrl" #error>
                    <van-icon name="photo" size="24" />
                  </template>
                </van-image>
                <div class="option-label">{{ option.text }}</div>
              </div>
            </template>
          </van-cascader>
        </van-popup>
      </div>

      <!-- 复合材料选择（类型2） -->
      <div v-if="machineType === '2'" class="material-selector">
        <van-collapse v-model="activeNames">
          <!-- 果酱选择 -->
          <van-collapse-item
            :title="$t('device.jam')"
            name="1"
            class="material-section"
          >
            <div class="grid-container">
              <div
                v-for="(item, index) in jamData"
                :key="`jam-${index}`"
                class="material-item"
              >
                <van-image
                  :src="showPopPhoto(item)"
                  width="50"
                  height="50"
                  fit="contain"
                />
                <span class="material-name">{{ item.name }}</span>
                <van-checkbox
                  v-model="item.checked"
                  shape="square"
                  class="material-checkbox"
                />
              </div>
            </div>
          </van-collapse-item>

          <!-- 坚果选择 -->
          <van-collapse-item
            :title="$t('device.nuts​')"
            name="2"
            class="material-section"
          >
            <div class="grid-container">
              <div
                v-for="(item, index) in crushData"
                :key="`nut-${index}`"
                class="material-item"
              >
                <van-image
                  :src="showPopPhoto(item)"
                  width="50"
                  height="50"
                  fit="contain"
                />
                <span class="material-name">{{ item.name }}</span>
                <van-checkbox
                  v-model="item.checked"
                  shape="square"
                  class="material-checkbox"
                />
              </div>
            </div>
          </van-collapse-item>
        </van-collapse>
      </div>

      <!-- 公共操作区 -->
      <div class="action-area">
        <div class="quick-link" @click="pushToDaySugarList">
          {{
            $t(
              machineType === "2"
                ? "device.todaysMakeList"
                : "device.todaysSugarList"
            )
          }}
          <van-icon name="arrow" />
        </div>

        <van-button
          round
          :type="doSugartData ? 'success' : 'primary'"
          class="submit-btn"
          :disabled="doSugartType"
          @click="doSugartData ? checkData() : submitDoSugar()"
        >
          <van-icon :name="doSugartData ? 'eye' : 'play-circle'" />
          {{
            $t(doSugartData ? "device.viewResults" : "device.submitToMakeSugar")
          }}
        </van-button>
      </div>
    </div>
  </div>
</template>
<script>
import { onMounted, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import { useRoute, useRouter } from "vue-router";
import {
  getDeviceDetal,
  selectProducts,
  remoteProduction,
  selectSugarStatus,
} from "@/service/device";
import {
  showConfirmDialog,
  showFailToast,
  showSuccessToast,
  showToast,
} from "vant";
import { useI18n } from "vue-i18n";
import { styleUrl } from "../../common/js/utils";

export default {
  setup() {
    const { t } = useI18n();
    const route = useRoute();
    const router = useRouter();
    const deviceId = route.query.deviceId;
    const machineType = route.query.machineType;
    const deviceDetal = ref(null);
    const show = ref(false);
    const fieldValue = ref("");
    const cascaderValue = ref("");
    const options = ref([]);
    const activeNames = ref(["1", "2"]);
    const productNo = ref("");

    // 果酱数据
    const iceName = ref();
    const jamData = ref([]);
    const crushData = ref([]);

    // 商品图片
    const showPopPhoto = (row) => {
      let imgId = row.no;
      if (imgId) {
        return require(`../../assets/order/spunSugar/goods/${imgId}.png`);
      }
      return imgId;
    };
    const onFinish = ({ selectedOptions }) => {
      console.log("onFinish", selectedOptions);
      show.value = false;
      fieldValue.value = selectedOptions[0].text;
      productNo.value = selectedOptions[0].value;
    };
    const doSugartData = ref(null);
    const doSugartType = ref(false);

    // 初始化页面获取列表
    onMounted(async () => {
      styleUrl("doSugar");
      getDeviceDetalFun();
    });

    const showSugarPhoto = (no) => {
      return require(`../../assets/order/spunSugar/goods/${no}.png`);
    };

    // 获取设备列表数据
    const getDeviceDetalFun = async () => {
      const { data } = await getDeviceDetal({ id: deviceId });
      if (data.code === "00000") {
        deviceDetal.value = data.data;
        getProduct();
      } else {
        showFailToast(data.message);
      }
    };
    // 获取花形下拉列表
    const getProduct = async () => {
      const { data } = await selectProducts({ equipmentId: deviceId });
      if (data.code) {
        if (machineType != "2") {
          options.value = data.data.map((item) => {
            return {
              text: item.productName,
              value: item.no,
              imgUrl: showSugarPhoto(item.no),
            };
          });
          console.log(options.value);
        } else {
          data.data.forEach((item) => {
            if (item.no.includes("J01")) {
              // 果酱1
              jamData.value.push({
                name: item.productName,
                no: item.no,
                value: 1,
                checked: false,
              });
            } else if (item.no.includes("J02")) {
              // 果酱2
              jamData.value.push({
                name: item.productName,
                no: item.no,
                value: 2,
                checked: false,
              });
            } else if (item.no.includes("J03")) {
              // 果酱3
              jamData.value.push({
                name: item.productName,
                no: item.no,
                value: 3,
                checked: false,
              });
            } else if (item.no.includes("C01")) {
              // 果碎1
              crushData.value.push({
                name: item.productName,
                no: item.no,
                value: 1,
                checked: false,
              });
            } else if (item.no.includes("C02")) {
              // 果碎2
              crushData.value.push({
                name: item.productName,
                no: item.no,
                value: 2,
                checked: false,
              });
            } else if (item.no.includes("I01")) {
              // 雪糕
              iceName.value = item.productName;
            }
          });
        }
      } else {
        showFailToast(data.message);
      }
    };
    const submitDoSugar = async () => {
      const makeCodes = ref([1, 0, 0]);
      doSugartData.value = null;
      doSugartType.value = true;

      if (machineType == "2") {
        fieldValue.value = "";
        let jamCount = 0;
        let crushCount = 0;
        // 如果是冰淇淋机器
        jamData.value.forEach((item) => {
          if (item.checked) {
            fieldValue.value += item.name + ",";
            makeCodes.value[1] += item.value;
            jamCount++;
          }
        });
        crushData.value.forEach((item) => {
          if (item.checked) {
            fieldValue.value += item.name + ",";
            makeCodes.value[2] += item.value;
            crushCount++;
          }
        });
        if (jamCount > 1) {
          makeCodes.value[1] += 1;
        }
        if (crushCount > 1) {
          makeCodes.value[2] += 1;
        }
        if (fieldValue.value === "") {
          fieldValue.value = iceName.value;
        } else {
          fieldValue.value = fieldValue.value.substring(
            0,
            fieldValue.value.length - 1
          );
          fieldValue.value = iceName.value + "(" + fieldValue.value + ")";
        }
      }
      if (fieldValue.value === "") {
        showFailToast(t("device.pleaseSelectAPattern"));
        return;
      }
      showConfirmDialog({
        title: t("user.tips"),
        message: t("device.confirmMake") + fieldValue.value + "?",
      })
        .then(async () => {
          const { data } = await remoteProduction({
            equipmentId: deviceId,
            productName: fieldValue.value,
            makeCodes: makeCodes.value.join(","),
            productNo: productNo.value,
          });
          if (data.code == "00000") {
            doSugartData.value = data.data;
            setTimeout(() => {
              doSugartType.value = false;
            }, 5000);
          } else {
            showFailToast(data.message);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    };
    const checkData = async () => {
      const { data } = await selectSugarStatus({ no: doSugartData.value.no });
      if (data.code) {
        if (data.data == "1") {
          showToast(t("device.receiveInstruction"));
        } else {
          showSuccessToast(data.message);
        }
        doSugartData.value = null;
        doSugartType.value = true;
      } else {
        if (data.data == "0") {
          showToast(t("device.notUploadData"));
        } else if (data.data == "2") {
          showToast(t("device.machineException"));
        } else if (data.data == "3") {
          showToast(t("device.netException"));
        } else {
          showToast(data.message);
        }
      }
    };

    const pushToDaySugarList = async () => {
      router.push({
        path: "toDaySugarList",
        query: { deviceId: deviceId, clientId: deviceDetal.value.clientId },
      });
    };

    return {
      deviceDetal,
      show,
      fieldValue,
      cascaderValue,
      options,
      onFinish,
      submitDoSugar,
      doSugartData,
      doSugartType,
      checkData,
      pushToDaySugarList,
      showSugarPhoto,
      machineType,
      activeNames,
      jamData,
      crushData,
      showPopPhoto,
    };
  },
  components: { sHeader },
};
</script>
<style lang="less" scoped>
@primary-color: #4d6add;
@card-bg: #ffffff;
@text-primary: #2d3436;
@border-color: #e4e7ec;

.sugar-maker {
  background: #f8fafb;
  min-height: 100vh;
}

.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;

    .header-indicator {
      width: 3px;
      height: 20px;
      background: @primary-color;
      margin-right: 12px;
      border-radius: 2px;
    }

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

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

  .selector-card {
    margin-bottom: 24px;

    .smart-field {
      :deep(.van-field__label) {
        color: @primary-color;
        font-weight: 500;
      }
    }

    .cascader-item {
      padding: 5px;
      display: flex;
      align-items: center;

      .option-image {
        border-radius: 8px;
        margin-right: 15px;
      }

      .option-label {
        font-size: 14px;
        color: @text-primary;
      }
    }
  }

  .material-selector {
    .material-section {
      :deep(.van-collapse-item__title) {
        font-weight: bold;
        color: #404d74;
      }
    }

    .grid-container {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;
    }

    .material-item {
      display: flex;
      align-items: center;
      padding: 8px;
      background: #f8fafb;
      border-radius: 8px;

      .material-name {
        flex: 1;
        margin: 0 12px;
        font-size: 13px;
        .ellipsis();
      }

      .material-checkbox {
        :deep(.van-checkbox__icon) {
          border-color: @primary-color;

          &.van-checkbox__icon--checked {
            background: @primary-color;
          }
        }
      }
    }
  }

  .action-area {
    margin-top: 24px;

    .quick-link {
      color: @primary-color;
      font-size: 13px;
      text-align: right;
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .van-icon {
        margin-left: 4px;
      }
    }

    .submit-btn {
      width: 100%;
      height: 48px;
      font-size: 16px;

      .van-icon {
        margin-right: 8px;
      }
    }
  }
}

.ellipsis() {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

@media (max-width: 480px) {
  .material-item {
    padding: 6px !important;

    .material-name {
      font-size: 12px !important;
    }
  }
}

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