<template>
  <div class="advert-form-page">
    <!-- 头部导航 -->
    <s-header :name="pageTitle" :noback="false" />

    <!-- 表单内容 -->
    <div class="form-container">
      <van-form @submit="updateAdFun" class="advert-form">
        <!-- 基本信息部分 -->
        <div class="form-section">
          <div class="section-title">{{ $t("advertManage.basicInfo") }}</div>
          <van-field
            required
            v-model="adInfo.name"
            name="name"
            :label="`${$t('advertManage.advertisingNameLabel')}`"
            :placeholder="$t('advertManage.advertisingNamePlaceholder')"
            :rules="[
              {
                required: true,
                message: $t('advertManage.advertisingNamePlaceholder'),
              },
            ]"
          />

          <van-field
            v-model="adInfo.adminId"
            name="adminId"
            :label="`${$t('advertManage.affiliatedMerchantsLabel')}`"
            :placeholder="$t('advertManage.affiliatedMerchantsPlaceholder')"
          />

          <van-field
            v-model="adInfo.orders"
            name="orders"
            type="number"
            :label="`${$t('advertManage.advertisingOrderLabel')}`"
            :placeholder="$t('advertManage.advertisingOrderPlaceholder')"
          />

          <van-field
            required
            readonly
            v-model="adInfo.equipmentType"
            name="equipmentType"
            :label="`${$t('advertManage.machineType')}`"
            :placeholder="$t('advertManage.machineTypePlace')"
            :rules="[
              { required: true, message: $t('advertManage.machineTypePlace') },
            ]"
            @click="busiInpClk"
          >
            <template #right-icon>
              <van-icon name="arrow-down" />
            </template>
          </van-field>
        </div>

        <!-- 播放设置部分 -->
        <div class="form-section">
          <div class="section-title">{{ $t("advertManage.playSettings") }}</div>
          <van-field
            v-model="adInfo.duration"
            name="duration"
            type="number"
            :label="`${$t('advertManage.advertisingDurationLabel')}`"
            :placeholder="$t('advertManage.advertisingDurationPlaceholder')"
          />

          <van-field
            v-model="adInfo.plays"
            name="plays"
            type="number"
            :label="`${$t('advertManage.playbackTimesLabel')}`"
            :placeholder="$t('advertManage.playbackTimesPlaceholder')"
          />

          <div class="radio-group">
            <div class="group-label">
              {{ $t("advertManage.playTimeStatus") }}
            </div>
            <van-radio-group v-model="adInfo.playTimeStatus">
              <van-radio name="0">{{ $t("advertManage.acquiesce") }}</van-radio>
              <van-radio name="1">{{ $t("advertManage.standby") }}</van-radio>
              <van-radio name="2">{{ $t("advertManage.work") }}</van-radio>
            </van-radio-group>
          </div>
        </div>

        <!-- 广告设置部分 -->
        <div class="form-section">
          <div class="section-title">{{ $t("advertManage.adSettings") }}</div>

          <div class="radio-group">
            <div class="group-label">
              {{ $t("advertManage.advertisingPosition") }}
            </div>
            <van-radio-group v-model="adInfo.screenType">
              <van-radio name="0">{{ $t("advertManage.screenA") }}</van-radio>
              <van-radio name="1">{{ $t("advertManage.screenB") }}</van-radio>
            </van-radio-group>
          </div>

          <div class="radio-group">
            <div class="group-label">
              {{ $t("advertManage.locationType") }}
            </div>
            <van-radio-group v-model="adInfo.locationType">
              <van-radio name="0">{{
                $t("advertManage.advertising")
              }}</van-radio>
              <van-radio name="1">{{
                $t("advertManage.externalAdvertising")
              }}</van-radio>
            </van-radio-group>
          </div>

          <div class="radio-group">
            <div class="group-label">
              {{ $t("advertManage.defaultDownload") }}
            </div>
            <van-radio-group v-model="adInfo.type">
              <van-radio name="0">{{
                $t("advertManage.defaultDownload")
              }}</van-radio>
              <van-radio name="1">{{
                $t("advertManage.doNotDownloadByDefault")
              }}</van-radio>
            </van-radio-group>
          </div>

          <div class="radio-group">
            <div class="group-label">
              {{ $t("advertManage.advertisingType") }}
            </div>
            <van-radio-group v-model="adInfo.adType">
              <van-radio name="0">{{ $t("advertManage.picture") }}</van-radio>
              <van-radio name="1">{{ $t("advertManage.video") }}</van-radio>
            </van-radio-group>
          </div>
        </div>

        <!-- 媒体内容部分 -->
        <div class="form-section">
          <div class="section-title">{{ $t("advertManage.mediaContent") }}</div>

          <!-- 图片广告内容 -->
          <div v-if="adInfo.adType === '0'" class="media-content">
            <van-field
              required
              v-model="adInfo.url"
              name="url"
              :label="`${$t('advertManage.pictureAddressLabel')}`"
              :placeholder="$t('advertManage.pictureAddressPlaceholder')"
              :rules="[
                {
                  required: true,
                  message: $t('advertManage.pictureAddressPlaceholder'),
                },
              ]"
            />

            <div class="preview-area" v-if="adInfo.url">
              <div class="preview-label">预览</div>
              <img :src="adInfo.url" class="image-preview" alt="广告图片预览" />
            </div>
          </div>

          <!-- 视频广告内容 -->
          <div v-if="adInfo.adType === '1'" class="media-content">
            <van-field
              v-model="adInfo.mediaPreview"
              name="mediaPreview"
              :label="`${$t('advertManage.thumbnailAddressLabel')}`"
              :placeholder="$t('advertManage.thumbnailAddressPlaceholder')"
            />

            <van-field
              required
              v-model="adInfo.url"
              name="url"
              :label="`${$t('advertManage.videoLinkLabel')}`"
              :placeholder="$t('advertManage.videoLinkPlaceholder')"
              :rules="[
                {
                  required: true,
                  message: $t('advertManage.videoLinkPlaceholder'),
                },
              ]"
            />

            <div class="preview-area" v-if="adInfo.url">
              <div class="preview-label">预览</div>
              <video :src="adInfo.url" class="video-preview" controls></video>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-section">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            class="submit-button"
          >
            {{ $t("advertManage.submit") }}
          </van-button>
        </div>
      </van-form>
    </div>

    <!-- 机器类型选择弹窗 -->
    <van-popup v-model:show="busiPopShow" position="bottom" round>
      <van-picker
        v-model="busiDefaIdx"
        :title="$t('advertManage.machineTypePlace')"
        :columns="busiPopList"
        :columns-field-names="busiPopFieldName"
        @confirm="busiPopConfirm"
        @cancel="busiPopShow = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { onMounted, ref, reactive } from "vue";
import sHeader from "../../components/SimpleHeader";
import { addAdInfo, updateAdInfo } from "../../service/advertManage";
import { useRouter } from "vue-router";
import { showFailToast, showSuccessToast } from "vant";
import { useI18n } from "vue-i18n";
import { styleUrl } from "../../common/js/utils";

export default {
  components: { sHeader },
  setup() {
    // 点击机器类型
    const busiInpClk = () => {
      busiPopShow.value = true;
    };
    // 机器类型
    const busiPopShow = ref(false);
    const busiDefaIdx = ref(["280"]);
    const busiPopList = reactive([
      {
        name: "280",
        id: "280",
      },
      {
        name: "280en",
        id: "280en",
      },
      {
        name: "301",
        id: "301",
      },
      {
        name: "301en",
        id: "301en",
      },
      {
        name: "320",
        id: "320",
      },
      {
        name: "320en",
        id: "320en",
      },
      {
        name: "330",
        id: "330",
      },
      {
        name: "330en",
        id: "330en",
      },
      {
        name: "P10",
        id: "P10",
      },
      {
        name: "P10en",
        id: "P10en",
      },
      {
        name: "P20",
        id: "P20",
      },
      {
        name: "P20en",
        id: "P20en",
      },
      {
        name: "P30",
        id: "P30",
      },
      {
        name: "P30en",
        id: "P30en",
      },
      {
        name: "SI320",
        id: "SI320",
      },
      {
        name: "SI320en",
        id: "SI320en",
      },
      {
        name: "SBC320",
        id: "SBC320",
      },
      {
        name: "SBC320en",
        id: "SBC320en",
      },
      {
        name: "SBM10ch",
        id: "SBM10ch",
      },
      {
        name: "SBM10en",
        id: "SBM10en",
      },
      {
        name: "EF210ch",
        id: "EF210ch",
      },
      {
        name: "EF210en",
        id: "EF210en",
      },
    ]);
    const busiPopFieldName = reactive({
      text: "name",
      value: "id",
    });
    // 点击机器类型的弹窗确定
    const busiPopConfirm = ({ selectedOptions }) => {
      adInfo.value.equipmentType = selectedOptions[0].id;
      busiPopShow.value = false;
    };
    const { t } = useI18n();
    const router = useRouter();
    const adInfo = ref({
      adminId: "",
      username: null,
      name: "",
      orders: "",
      duration: "",
      plays: "",
      status: "推送中",
      screenType: "0",
      locationType: "0",
      type: "0",
      adType: "0",
      url: "",
      mediaPreview: "",
      equipmentType: "",
      playTimeStatus: "0",
    });
    const pageTitle = ref("");
    onMounted(async () => {
      // 加载样式
      styleUrl("advertManage");
      let adverInfo = localStorage.getItem("adverInfo");
      if (adverInfo) {
        pageTitle.value = t("advertManage.modifyAdvertisement");
        adverInfo = JSON.parse(adverInfo);
        adInfo.value.id = adverInfo.id;
        adInfo.value.adminId = adverInfo.adminId;
        adInfo.value.username = adverInfo.username;
        adInfo.value.name = adverInfo.name;
        adInfo.value.orders = adverInfo.orders;
        adInfo.value.duration = adverInfo.duration;
        adInfo.value.plays = adverInfo.plays;
        adInfo.value.screenType =
          typeof adverInfo.screenType === "object"
            ? "0"
            : adverInfo.screenType.toString();
        adInfo.value.locationType =
          typeof adverInfo.locationType === "object"
            ? "0"
            : adverInfo.locationType.toString();
        adInfo.value.type =
          typeof adverInfo.type === "object" ? "0" : adverInfo.type.toString();
        adInfo.value.adType =
          typeof adverInfo.adType === "object"
            ? "0"
            : adverInfo.adType.toString();
        adInfo.value.url = adverInfo.url;
        adInfo.value.mediaPreview = adverInfo.mediaPreview;
        adInfo.value.equipmentType = adverInfo.equipmentType;
        // 找到机器类型的下标
        // busiPopList.forEach((item, index) => {
        //   console.log(item, index);
        //   console.log(adverInfo.equipmentType);

        //   if (item.id == adverInfo.equipmentType) {
        //     busiDefaIdx.value = index;
        //   }
        // });
        busiDefaIdx.value = [adverInfo.equipmentType];
        // console.log(adInfo.value);
      } else {
        pageTitle.value = t("advertManage.addAds");
      }
    });

    const updateAdFun = async () => {
      if (pageTitle.value === t("advertManage.modifyAdvertisement")) {
        const params = Object.assign({}, adInfo.value);
        const { data } = await updateAdInfo(params);
        if (data.code === "00000") {
          showSuccessToast(
            t("advertManage.successfullyModifiedTheAdvertisement")
          );
          router.push({ path: "advertManage" });
        } else {
          showFailToast(data.message);
        }
        console.log("updateAdFun", data);
      } else {
        const params = Object.assign({}, adInfo.value);
        const { data } = await addAdInfo(params);
        if (data.code === "00000") {
          showSuccessToast(t("advertManage.advertisementAddedSuccessfully"));
          router.push({ path: "advertManage" });
        } else {
          showFailToast(data.message);
        }
      }
    };
    return {
      pageTitle,
      adInfo,
      updateAdFun,
      busiPopShow,
      busiDefaIdx,
      busiPopList,
      busiPopFieldName,
      busiPopConfirm,
      busiInpClk,
    };
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4d6add;

.advert-form-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.form-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.advert-form {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.form-section {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-left: 8px;
  position: relative;

  &::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 3px;
    height: 16px;
    background-color: @primary-color;
    border-radius: 2px;
  }
}

.radio-group {
  margin: 10px;

  .group-label {
    font-size: 13px;
    color: #404d74;
    margin-bottom: 8px;
  }

  .van-radio-group {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .van-radio {
    background-color: #f5f7fa;
    border-radius: 16px;
    padding: 6px 16px;
    margin-right: 8px;

    :deep(.van-radio__label) {
      font-size: 13px;
    }
  }
}

.media-content {
  .preview-area {
    margin-top: 16px;

    .preview-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
    }

    .image-preview {
      width: 100%;
      max-height: 200px;
      object-fit: contain;
      border-radius: 8px;
      border: 1px solid #eee;
    }

    .video-preview {
      width: 100%;
      height: 180px;
      border-radius: 8px;
      background-color: #000;
    }
  }
}

.submit-section {
  margin-top: 24px;

  .submit-button {
    height: 44px;
    font-size: 16px;
    font-weight: 500;
  }
}

@media (max-width: 480px) {
  .form-container {
    padding: 12px;
  }

  .advert-form {
    padding: 12px;
  }

  .section-title {
    font-size: 15px;
  }

  .radio-group {
    .van-radio-group {
      gap: 5px;
    }

    .van-radio {
      padding: 6px 12px;
      margin-right: 6px;
    }
  }
}
</style>
