<template>
  <uv-navbar autoBack :title="title" placeholder />
  <form class="form-box">
    <view class="form-item" v-if="formData.name">
      <view class="item-label">
        <text class="label-text">模式名称：</text>
      </view>
      <view class="item-value">{{ formData.name }}</view>
    </view>

    <view class="form-item">
      <view class="item-label">
        <text class="label-required">*</text>
        <text class="label-text">模式类型：</text>
      </view>
      <view class="item-value">
        <view class="select-value" @click="handleSelectMode(0, 'sharedMode')">
          <text
            :class="[
              'select-icon',
              formData.sharedMode == 0 ? 'active-select-icon' : '',
            ]"
          ></text>
          <text class="select-text">排队模式</text>
        </view>

        <view class="select-value" @click="handleSelectMode(1, 'sharedMode')">
          <text
            :class="[
              'select-icon',
              formData.sharedMode == 1 ? 'active-select-icon' : '',
            ]"
          ></text>
          <text class="select-text">均摊模式</text>
        </view>
      </view>
    </view>

    <view class="form-item" v-if="formData.sharedMode == 1">
      <view class="item-label">
        <text class="label-required">*</text>
        <text class="label-text">均摊到账时间：</text>
      </view>
      <view class="item-value">
        <view
          class="select-value"
          @click="handleSelectMode(false, 'immediateArrival')"
        >
          <text
            :class="[
              'select-icon',
              !formData.immediateArrival ? 'active-select-icon' : '',
            ]"
          ></text>
          <text class="select-text">定时均摊</text>
        </view>

        <view
          class="select-value"
          @click="handleSelectMode(true, 'immediateArrival')"
        >
          <text
            :class="[
              'select-icon',
              formData.immediateArrival ? 'active-select-icon' : '',
            ]"
          ></text>
          <text class="select-text">立即均摊</text>
        </view>
      </view>
    </view>

    <view
      class="form-item"
      v-if="formData.sharedMode == 1 && !formData.immediateArrival"
    >
      <view class="item-label">
        <text class="label-required">*</text>
        <text class="label-text">请选择时间：</text>
      </view>
      <picker
        @change="bindPickerChange"
        :value="formData.settlementHour ? formData.settlementHour * 1 - 1 : 0"
        :range="hourArray"
        range-key="text"
      >
        <view class="item-value">
          <text v-if="formData.settlementHour" style="color: #000">{{
            formData.settlementHour + ":00"
          }}</text>
          <text v-else> 请选择时间 </text>
        </view>
      </picker>
    </view>

    <view class="form-item">
      <view class="item-label">
        <text class="label-required">*</text>
        <text class="label-text">商家让利：</text>
      </view>
      <view class="item-value value-bottom">
        <input
          v-model="formData.subsidyRatio"
          class="value-input"
          type="number"
          placeholder="请输入，最低5，最高90"
          placeholder-class="value-input-placeholder"
          @blur="handleBlur($event, 5, 90, 'subsidyRatio')"
        />
        <text class="value-percent">%</text>
      </view>
    </view>

    <template v-if="formData.sharedMode == 1">
      <view class="form-item">
        <view class="item-label">
          <text class="label-required">*</text>
          <text class="label-text">队首补贴占比：</text>
        </view>
        <view class="item-value value-bottom">
          <input
            v-model="formData.firstSubsidyRatio"
            class="value-input"
            type="number"
            placeholder="请输入，最低1，最高99"
            placeholder-class="value-input-placeholder"
            @blur="handleBlur($event, 1, 99, 'firstSubsidyRatio')"
          />
          <text class="value-percent">%</text>
        </view>
      </view>

      <view class="form-item">
        <view class="item-label">
          <text class="label-required">*</text>
          <text class="label-text">均摊补贴占比：</text>
        </view>
        <view class="item-value value-bottom">
          <text class="value-percent">
            {{
              formData.firstSubsidyRatio != null
                ? 100 - formData.firstSubsidyRatio
                : 0
            }}%</text
          >
        </view>
      </view>
    </template>

    <view class="form-item">
      <view class="item-label">
        <text class="label-required">*</text>
        <text class="label-text">消费者最高补贴（占订单金额比）：</text>
      </view>
      <view class="item-value value-bottom">
        <input
          v-model="formData.amountSubsidyRatio"
          class="value-input"
          type="number"
          placeholder="区间0~100"
          placeholder-class="value-input-placeholder"
          @blur="handleBlur($event, 0, 100, 'amountSubsidyRatio')"
        />
        <text class="value-percent">%</text>
      </view>
    </view>
    <view class="form-item">
      <view class="item-label">
        <text class="label-required">*</text>
        <text class="label-text">消费者积分补贴（占订单金额比）：</text>
      </view>
      <view class="item-value value-bottom">
        <input
          v-model="formData.pointSubsidyRatio"
          class="value-input"
          type="number"
          placeholder="区间0~100"
          placeholder-class="value-input-placeholder"
          @blur="handleBlur($event, 0, 100, 'pointSubsidyRatio')"
        />
        <text class="value-percent">%</text>
      </view>
    </view>
    <view class="form-hint"
      >注意：补贴金额+补贴积分占比合计最低要大于等于10%。</view
    >
  </form>

  <view class="footer-box">
    <view class="footer-but" @click.stop="handleSave"> 确定 </view>
  </view>
  <view class="footer-placeholder" />
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
  getSubsidyModeInfoApi,
  addSubsidyModeApi,
  editSubsidyModeApi,
} from "@/api/ShopContent";
const eventChannel = ref(null);
onMounted(() => {
  const instance = getCurrentInstance().proxy;
  eventChannel.value = instance.getOpenerEventChannel();
});
const formData = reactive({
  sharedMode: 0,
  immediateArrival: false,
  amountSubsidyRatio: 100
});
const title = ref("新增模式");
const hourArray = computed(() => {
  let list = [];
  for (let index = 1; index < 24; index++) {
    const element = index;
    list.push({
      value: element,
      text: element + ":00",
    });
  }
  return list;
});

// 模式切换
const handleSelectMode = (mode, type) => {
  formData[type] = mode;
};

const bindPickerChange = (e) => {
  //   console.log("picker发送选择改变，携带值为", e.detail.value);
  formData.settlementHour = e.detail.value * 1 + 1;
};

const handleBlur = (e, min, max, field) => {
  //   console.log(e.detail.value);
  //   formData[field] = e.detail.value * 1;
  if (formData[field] < min) {
    formData[field] = min;
  }
  if (formData[field] > max) {
    formData[field] = max;
  }
};

const handleSave = () => {
  //   console.log("保存", formData);
  if (formData.sharedMode == null) {
    uni.$uv.toast("请选择模式类型");
    return;
  }
  if (
    !formData.settlementHour &&
    formData.sharedMode == 1 &&
    !formData.immediateArrival
  ) {
    uni.$uv.toast("请选择均摊到账时间");
    return;
  }
  if (!formData.subsidyRatio) {
    uni.$uv.toast("请输入商家让利");
    return;
  }
  if (!formData.firstSubsidyRatio && formData.sharedMode == 1) {
    uni.$uv.toast("请输入队首补贴占比");
    return;
  }
  if (!formData.amountSubsidyRatio) {
    uni.$uv.toast("请输入消费者最高补贴（占订单金额比）");
    return;
  }
  if (!formData.pointSubsidyRatio) {
    uni.$uv.toast("请输入消费者积分补贴（占订单金额比）");
    return;
  }
  if (formData.amountSubsidyRatio + formData.pointSubsidyRatio < 10) {
    uni.$uv.toast("补贴金额+补贴积分占比合计最低要大于等于10%");
    return;
  }

  let url = formData.modeId ? editSubsidyModeApi : addSubsidyModeApi;
  uni.showLoading({
    title: "加载中...",
    mask: true,
  });
  url({
    ...formData,
    settlementHour: formData.settlementHour ? formData.settlementHour : 0,
    firstSubsidyRatio: formData.firstSubsidyRatio
      ? formData.firstSubsidyRatio
      : 0,
  }).then((res) => {
    uni.hideLoading();
    if (res.code == 200) {
      uni.$uv.toast(formData.modeId ? "修改成功" : "新增成功");
      setTimeout(() => {
        eventChannel.value.emit("updateData");
        uni.navigateBack();
      }, 500);
    }
  });
};

const getSubsidyModeInfo = (modeId) => {
  uni.showLoading({
    title: "加载中...",
    mask: true,
  });
  getSubsidyModeInfoApi(modeId)
    .then((res) => {
      uni.hideLoading();
      if (res.code == 200 && res.data) {
        Object.assign(formData, {
          ...res.data,
          subsidyRatio: res.data.subsidyRatio * 1,
          firstSubsidyRatio: res.data.firstSubsidyRatio * 1,
          amountSubsidyRatio: res.data.amountSubsidyRatio * 1,
          pointSubsidyRatio: res.data.pointSubsidyRatio * 1,
        });
      }
    })
    .catch((err) => {
      uni.hideLoading();
    });
};

onLoad((options) => {
  //   console.log(options);
  if (options.index) {
    formData.sortOrder = options.index;
  }
  if (options.modeId) {
    title.value = "修改模式";
    getSubsidyModeInfo(options.modeId);
  }
});
</script>

<style lang="scss" scoped>
.form-box {
  width: 100%;
  box-sizing: border-box;
}

.form-item {
  padding: 0 30rpx;
  box-sizing: border-box;

  .item-label {
    padding-top: 15rpx;
    width: 100%;
    display: flex;
    align-items: center;

    .label-required {
      font-size: 28rpx;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #ff0000;
    }

    .label-text {
      font-size: 28rpx;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #1a1a1a;
      line-height: 36rpx;
    }
  }

  .item-value {
    width: 100%;
    min-height: 70rpx;
    font-size: 28rpx;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    color: #808080;
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .select-value {
      display: flex;
      align-items: center;

      & + .select-value {
        padding-left: 40rpx;
      }

      .select-icon {
        width: 34rpx;
        height: 34rpx;
        background: #ffffff;
        border: 2rpx solid #b3b3b3;
        border-radius: 50%;
      }

      .active-select-icon {
        position: relative;
        border-color: #3775f6;

        &:before {
          content: "";
          position: absolute;
          left: 50%;
          top: 50%;
          width: 17rpx;
          height: 17rpx;
          background: #3775f6;
          border-radius: 50%;
          transform: translate(-50%, -50%);
        }
      }

      .select-text {
        font-size: 28rpx;
        font-family: PingFang SC, PingFang SC-Regular;
        font-weight: 400;
        color: #808080;
        padding-left: 10rpx;
      }
    }

    .value-input {
      height: 70rpx;
      flex: 1 0;
      font-size: 28rpx;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #000;
    }

    .value-input-placeholder {
      color: #cccccc;
      font-size: 28rpx;
    }

    .value-percent {
      font-size: 28rpx;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      text-align: right;
      color: #1a1a1a;
    }
  }

  .value-bottom {
    border-bottom: 1rpx solid #f0f0f0;
  }
}

.form-hint {
  box-sizing: border-box;
  width: 100%;
  padding: 30rpx;
  font-size: 24rpx;
  font-family: PingFang SC, PingFang SC-Regular;
  font-weight: 400;
  text-align: left;
  color: #ff0000;
  line-height: 36rpx;
}

.footer-placeholder,
.footer-box {
  width: 100%;
  height: 147rpx;
}

.footer-box {
  padding: 30rpx 60rpx 0;
  box-sizing: border-box;
  position: fixed;
  left: 0;
  bottom: 0;
  right: 0;

  .footer-but {
    width: 100%;
    height: 90rpx;
    background: #eb5153;
    border-radius: 45rpx;
    text-align: center;
    line-height: 90rpx;
    font-size: 32rpx;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    color: #ffffff;
  }
}
</style>
