<template>
  <view class="page">
    <BackBar :title="formData.id ? '编辑奖励' : '添加奖励'" />
    <view class="award_form">
      <view class="form_item">
        <view class="form_item_label"> <text class="must">*</text>奖励名称 </view>
        <input
          v-model="formData.rewardName"
          class="phone_input"
          type="text"
          confirm-type="search"
          placeholder="请输入"
          placeholder-style="color:#A9AAB5;font-size:30rpx;"
          @blur="blurInput"
        />
        <view v-if="isEmpty.rewardName" class="error">请填写奖励名称</view>
        <view v-if="formData?.rewardName.length > 6" class="error"> 字数不能超过六位 </view>
      </view>
      <view class="form_item">
        <view class="form_item_label"> <text class="must">*</text>选择奖励 LOGO（1:1） </view>
        <view class="uplaod_problem">
          <view v-if="tempImageUrl.length > 0" class="all_img">
            <view v-for="(i, idx) in tempImageUrl" :key="idx" class="problem_img">
              <image :src="i" mode="" class="show_problem" @click="previewImg(idx)"></image>
              <image
                :src="`${OSS_URL}/iconfont/close_icon.png`"
                mode=""
                class="close_icon"
                @click="tempImageUrl = []"
              ></image>
            </view>
          </view>
          <image
            v-else
            :src="`${OSS_URL}/upload_icon.png`"
            class="upload_icon"
            mode=""
            @load="loadUploadIcon"
            @error="errorUploadIcon"
            @click="clickChooseLogo"
          ></image>
        </view>
        <view v-if="isEmpty.iconUrl" class="error">请上传奖励 LOGO</view>
      </view>

      <view class="form_item">
        <view class="form_item_label"> 奖励描述 </view>
        <view class="form_item_problem">
          <textarea
            v-model="formData.note"
            class="problem_input"
            :maxlength="maxlength"
            placeholder="请输入"
            placeholder-style="color:#A9AAB5;font-size:30rpx;"
            @input="handleInputNum"
          />
          <view class="input_num"
            ><text>{{ fontNum }}</text
            >/200</view
          >
        </view>
      </view>

      <view class="footer">
        <button class="btn-primary" @click="submit">
          {{ formData.id ? '保存' : '确定' }}
        </button>
      </view>
      <!-- 弹出框选项 -->
      <LogoPicker ref="logoPickerRef" @confirm="confirmPicker" />
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getRewardDetailApi, addRewardApi, updateRewardApi } from '@/api';
import { uploadFile } from '@/utils';
import LogoPicker from './LogoPicker.vue';
const OSS_URL = import.meta.env.VITE_OSS_HOST;
const logoPickerRef = ref();
const LOGOType = ref();

const maxlength = ref(-1);
// 内容是否为空
const isEmpty = ref({
  rewardName: false,
  iconUrl: false,
});
const fontNum = ref(0);

const tempImageUrl = ref([]); // 临时存储图片
const formData = ref({
  id: '',
  rewardName: '',
  iconUrl: '',
  note: '',
  rewardType: 1,
});

function blurInput(event) {
  let len = formData.value.rewardName.length;
  if (len > 6) {
    formData.value.rewardName = formData.value.rewardName.slice(0, 6);
  }
}

function handleInputNum(event) {
  let value = event.detail.value.replace(/\s+/g, '');
  setTimeout(() => {
    if (value.length >= 200) {
      maxlength.value = 200;
      value = value.substr(0, 200);
    } else {
      maxlength.value = -1;
      value = value.substr(0, value.length);
    }
    event.detail.value = value;
    formData.value.note = value;
    fontNum.value = formData.value.note.length;
  }, 0);
}
// 选择logo
function clickChooseLogo() {
  logoPickerRef.value.open();
}

// 上传图标加载完毕
function loadUploadIcon(e) {
  uni.hideLoading();
}

function errorUploadIcon() {
  uni.hideLoading();
}
// 选中奖励LOGO
function confirmPicker(val, type) {
  LOGOType.value = type;
  if (LOGOType.value === 1) {
    // 本地LOGO
    formData.value.iconUrl = val;
  }
  tempImageUrl.value[0] = val;
  isEmpty.value.iconUrl = false;
}
// 查看LOGO
function previewImg(idx) {
  uni.previewImage({
    current: idx,
    urls: tempImageUrl.value,
  });
}

// 提交
async function submit() {
  isEmpty.value = {
    rewardName: !formData.value.rewardName,
    iconUrl: tempImageUrl.value.length === 0,
  };
  if (isEmpty.value.rewardName || isEmpty.value.iconUrl) return;
  uni.showLoading({
    title: formData.value.id ? '编辑中...' : '添加中...',
  });
  if (LOGOType.value === 2) {
    // 本地相册上传
    const { filePath, id } = await uploadFile(tempImageUrl.value[0]);
    formData.value.iconUrl = filePath;
  }
  let res;
  if (formData.value.id) {
    res = await updateRewardApi(formData.value);
  } else {
    res = await addRewardApi(formData.value);
  }
  uni.hideLoading();
  if (res.code === 200) {
    uni.showToast({
      title: formData.value.id ? '编辑成功' : '添加成功',
      icon: 'none',
    });
    uni.navigateTo({
      url: '/pages/mine/awardManage/index',
    });
  }
}
onLoad(async options => {
  formData.value.id = options.id;
  if (formData.value.id) {
    const { data } = await getRewardDetailApi(formData.value.id);
    formData.value = data;
    tempImageUrl.value[0] = data.iconUrl;
    fontNum.value = data.note.length;
  }
  uni.setNavigationBarTitle({
    title: formData.value.id ? '编辑奖励' : '添加奖励',
  });
});
</script>

<style lang="scss" scoped>
.page {
}
.award_form {
  margin: 30rpx 30rpx 0;
  padding: 30rpx 30rpx 40rpx 30rpx;
  box-sizing: border-box;
  border-radius: 20rpx;
  color: #333;
  background-color: #fff;
  font-size: 30rpx;

  .form_item {
    margin-bottom: 32rpx;

    &_label {
      margin-bottom: 16rpx;
      font-weight: 500;
    }

    &_con {
      position: relative;
      padding: 24rpx 20rpx;
      box-sizing: border-box;
      height: 90rpx;
      background-color: #f9f9fb;
      border-radius: 16rpx;

      .more_down {
        position: absolute;
        right: 30rpx;
        width: 30rpx;
        height: 30rpx;
      }
    }

    &_problem {
      position: relative;

      .problem_input {
        padding: 30rpx 20rpx 56rpx 20rpx;
        box-sizing: border-box;
      }

      .input_num {
        position: absolute;
        bottom: 18rpx;
        right: 20rpx;
        font-size: 24rpx;
        color: #a9aab5;
      }
    }

    .must {
      color: red;
    }

    .image_tip {
      font-size: 26rpx;
      color: #999;
      white-space: nowrap;
    }

    .uplaod_problem {
      display: flex;
      white-space: nowrap;

      .all_img {
        display: flex;

        .problem_img {
          position: relative;
          margin-right: calc((100vw - 540rpx) / 4);
          width: 120rpx;
          height: 120rpx;

          .show_problem {
            width: 100%;
            height: 100%;
          }

          &:nth-child(4n) {
            margin-right: 0 !important;
          }

          .close_icon {
            position: absolute;
            top: -8rpx;
            right: -8rpx;
            width: 24rpx;
            height: 24rpx;
            background-color: #fff;
            border-radius: 50%;
          }
        }
      }

      .upload_icon {
        width: 122rpx;
        height: 122rpx;
      }
    }

    .problem_input {
      width: 100%;
      height: 274rpx;
      background-color: #f9f9fb;
      border-radius: 16rpx;
    }

    .phone_input {
      height: 90rpx;
      padding: 0 20rpx;
      box-sizing: border-box;
      background-color: #f9f9fb;
      border-radius: 16rpx;
    }

    .error {
      margin-top: 16rpx;
      font-size: 26rpx;
      color: #ff3d3d;
    }
  }

  .footer {
    position: absolute;
    display: flex;
    justify-content: center;
    flex-direction: row;
    bottom: 0;
    width: 100%;
    height: 172rpx;
    left: 0;
    box-sizing: border-box;
    background-color: #fff;
    border-top: 1rpx solid #eee;

    button::after {
      border: none;
    }

    .btn-primary {
      margin-top: 16rpx;
      box-sizing: border-box;
      width: 440rpx;
      height: 90rpx;
      background-color: #615dff;
      color: #ffffff;
      border-radius: 20rpx;
      font-size: 30rpx;
      line-height: 90rpx;
    }
  }
}
</style>
