<template>
  <uv-navbar autoBack title="配置条件" placeholder bgColor="#fff" />
  <view class="switchover-box">
    <text class="switchover-title">当前模式</text>
    <view class="condition-value">{{ SubsidyMode.name || "--" }}</view>
  </view>
  <view class="switchover-box">
    <text class="switchover-title">启用模式自动切换</text>
    <uv-switch
      v-model="valueStatus"
      :size="SwitchSize"
      activeColor="#43B436"
      @change="ChangeSwitch"
    ></uv-switch>
  </view>
  <view class="placeholder" />
  <view class="condition-box">
    <view class="condition-item">
      <text class="condition-lable">当排队订单数到达：</text>
      <view class="condition-value">
        <input
          v-model="FormData.maxQueueCount"
          class="condition-input"
          type="number"
          placeholder="请输入排队人数"
          placeholder-class="condition-placeholder"
        />
      </view>
    </view>
    <view class="condition-item">
      <text class="condition-lable"></text>
      <view class="condition-value condition-text"
        >当排队订单数：{{ QueueCount }}</view
      >
    </view>
    <view class="condition-item">
      <text class="condition-lable"></text>
      <view class="condition-value condition-or">或</view>
    </view>
    <view class="condition-item">
      <text class="condition-lable">到达指定日期：</text>
      <view
        class="condition-value calendar-box"
        @click.stop="CalendarRef.open()"
      >
        <template v-if="FormData.autoConvertDate">
          <text class="condition-input">{{ FormData.autoConvertDate }}</text>
          <view @click.stop="FormData.autoConvertDate = ''">
            <uv-icon name="close-circle" color="#000" size="30rpx"></uv-icon>
          </view>
        </template>
        <template v-else>
          <text class="condition-input condition-placeholder"
            >请选择年月日</text
          >
          <text class="iconfont calendar-icon">&#xe651;</text>
        </template>
      </view>
    </view>
  </view>
  <view class="placeholder" />
  <view class="condition-box">
    <view class="condition-item" @click.stop="ModeClick">
      <text class="condition-lable">自动更换模式为：</text>
      <view class="condition-value calendar-box">
        <text class="condition-input" v-if="FormData.targetModeName">{{
          FormData.targetModeName
        }}</text>
        <text class="condition-input condition-placeholder" v-else
          >请选择模式</text
        >
        <text class="iconfont select-icon">&#xe671;</text>
      </view>
    </view>
  </view>
  <view class="footer-box">
    <view class="footer-but" @click.stop="handleConfirm"> 确定 </view>
  </view>
  <view class="footer-placeholder" />

  <uv-calendar
    ref="CalendarRef"
    @confirm="ConfirmCalendar"
    :minDate="minDate"
    :defaultDate="FormData.autoConvertDate ? [FormData.autoConvertDate] : defaultDate"
  ></uv-calendar>

  <uv-picker
    ref="PickerRef"
    :columns="[ModeList]"
    @confirm="ConfirmPicker"
    keyName="name"
  ></uv-picker>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import {
  getCurrentSubsidyModeApi,
  getSubsidyModeListApi,
  setSubsidyModeAutoEnabledApi,
  setSubsidyModeAutoApi,
  getSubsidyModeAutoApi,
  getValidQueueCountApi,
} from "@/api/ShopContent";
const PickerRef = ref<any>(null);
const SwitchSize = ref(uni.upx2px(46));
const valueStatus = ref(false);
const minDate = ref(null);
const CalendarRef = ref(null);
const ConfirmCalendar = (e) => {
  //   console.log("ConfirmCalendar = ", e);
  FormData.autoConvertDate = e[0];
};
const QueueCount = ref(0);
const getValidQueueCount = async () => {
  try {
    const { data } = await getValidQueueCountApi();
    // console.log("getValidQueueCount = ", data);
    QueueCount.value = data || 0;
  } catch (error) {
    console.log("error = ", error);
  }
};
const defaultDate = ref([]);
const FormData = reactive({});
const getSubsidyModeAuto = async () => {
  try {
    const { data } = await getSubsidyModeAutoApi();
    // console.log("getSubsidyModeAuto = ", data);
    let obj = data || {};
    Object.assign(FormData, {
      ...obj,
      autoConvertDate: obj.autoConvertDate
        ? obj.autoConvertDate.split(" ")[0]
        : "",
    });
    valueStatus.value = obj.enabled || false;
  } catch (error) {
    console.log("error = ", error);
  }
};
const SubsidyMode = reactive({});
const getCurrentSubsidyMode = async () => {
  try {
    const { data } = await getCurrentSubsidyModeApi();
    // console.log("getCurrentSubsidyMode = ", data);
    Object.assign(SubsidyMode, data || {});
  } catch (error) {
    console.log("error = ", error);
  }
};

const ModeList = ref<any>([]);
const getSubsidyModeList = async () => {
  try {
    const { data } = await getSubsidyModeListApi();
    // console.log("getCurrentSubsidyMode = ", data);
    ModeList.value = data || [];
  } catch (error) {
    console.log("error = ", error);
  }
};

const ChangeSwitch = async (e) => {
  //   console.log("ChangeSwitch = ", e);
  if (FormData.modeAutoId) {
    try {
      const { code } = await setSubsidyModeAutoEnabledApi(FormData.modeAutoId);
      uni.$uv.toast(`${e ? "开启" : "关闭"}自动切换成功`);
    } catch (error) {
      console.log("error = ", error);
    }
  }
  //   setSubsidyModeAutoEnabledApi(e);
};

const ModeClick = () => {
  if (FormData.targetModeId) {
    const index = ModeList.value.findIndex(
      (item) => item.modeId === FormData.targetModeId
    );
    PickerRef.value.setIndexs([index], true);
  }
  PickerRef.value.open();
};

const ConfirmPicker = (e) => {
  //   console.log("ConfirmPicker = ", e.value[0]);
  //   FormData.targetModeId = e.value[0].modeId;
  // 	FormData.targetModeName = e.value[0].name;
  if (e.value[0].modeId == SubsidyMode.modeId) {
    uni.$uv.toast("不能选择当前模式");
    return;
  }
  Object.assign(FormData, {
    targetModeId: e.value[0].modeId,
    targetModeName: e.value[0].name,
  });
};

const handleConfirm = async () => {
  if (!FormData.maxQueueCount && !FormData.autoConvertDate) {
    uni.$uv.toast(`排队订单数或到达指定日期至少填写一个`);
    return false;
  }
  if (!FormData.targetModeId) {
    uni.$uv.toast(`请选择自动更换模式`);
    return false;
  }
  uni.showLoading({ title: "正在处理中...", mask: true });
  try {
    const { data } = await setSubsidyModeAutoApi({
      ...FormData,
      enabled: valueStatus.value,
    });
    uni.hideLoading();
    uni.$uv.toast("设置成功");
    setTimeout(() => {
      uni.navigateBack();
    }, 500);
  } catch (error) {
    uni.hideLoading();
    console.log("error = ", error);
  }
};

onMounted(() => {
  // 获取当前日期对象
  const today = new Date();

  // 获取后一天的日期（自动处理跨月/跨年）
  const nextDay = new Date(today);
  nextDay.setDate(today.getDate() + 1);
  // console.log("today = ", nextDay);
  // 格式化日期为 YYYY-MM-DD
  const year = nextDay.getFullYear();
  const month = String(nextDay.getMonth() + 1).padStart(2, "0");
  const day = String(nextDay.getDate()).padStart(2, "0");
  console.log(`${year}-${month}-${day}`);
  minDate.value = `${year}-${month}-${day}`;
  defaultDate.value = [`${year}-${month}-${day}`]
  getSubsidyModeList();
  getCurrentSubsidyMode();
  getSubsidyModeAuto();
  getValidQueueCount();
});
</script>

<style lang="scss" scoped>
$pad_: 30rpx;

.placeholder {
  width: 100%;
  height: 12rpx;
  background: #f7f7f7;
}

.switchover-box {
  width: 100%;
  height: 112rpx;
  padding: 0 $pad_;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;

  .switchover-title {
    font-size: 28rpx;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    color: #1a1a1a;
  }

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

.condition-box {
  box-sizing: border-box;
  padding: $pad_;

  .condition-item {
    display: flex;
    align-items: center;

    .condition-lable {
      flex-shrink: 0;
      width: 40%;
      min-height: 1rpx;
      font-size: 28rpx;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #1a1a1a;
    }

    .condition-value {
      width: 60%;
      background: #ffffff;
      border: 1rpx solid #e6e6e6;
      border-radius: 10rpx;
      padding: 0 20rpx;
      .condition-input {
        width: 100%;
        height: 70rpx;
        font-size: 28rpx;
        font-family: PingFang SC, PingFang SC-Regular;
        font-weight: 400;
      }

      .condition-placeholder {
        color: #d9d9d9;
      }
    }

    .condition-text {
      font-size: 24rpx;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #ff0000;
      line-height: 36rpx;
      border: none;
      padding: 0;
    }

    .condition-or {
      padding: 30rpx 0;
      font-size: 24rpx;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #1a1a1a;
      line-height: 36rpx;
      border: none;
    }

    .calendar-box {
      height: 70rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .condition-input {
        flex: 1;
        height: 100%;
        display: flex;
        align-items: center;
      }

      .calendar-icon {
        flex-shrink: 0;
        font-size: 40rpx;
        color: #ffad00;
      }

      .select-icon {
        transform: rotate(90deg);
        color: #666666;
        font-size: 38rpx;
      }
    }
  }
}

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