<template>
  <view class="min-page bg-f7 u-p-t-30 u-font-28">
    <up-sticky>
      <view class="bg-fff u-flex default-box-padding">
        <image
          style="width: 60rpx; height: 60rpx"
          src="/pageMarket/static/images/new-user-discount.png"
        ></image>
        <view class="u-flex-1 u-flex u-p-l-24">
          <view class="u-font-28 u-flex-1 u-p-r-4">
            <view class="color-333 font-bold">新客立减 </view>
            <view class="color-666 u-m-t-4 u-font-24">首单下单减免金额 </view>
          </view>
          <up-switch
            v-model="newUserDiscountStore.config.isEnable"
            size="18"
            :active-value="1"
            :inactive-value="0"
          ></up-switch>
        </view>
      </view>
    </up-sticky>
    <view class="default-box-padding">
      <view
        class="bg-fff default-box-radius default-box-padding u-flex u-row-between"
      >
        <text class="color-000 font-bold">活动时间</text>
        <my-time-area
          startText="开始时间"
          endText="结束时间"
          v-model:startDate="form.startTime"
          v-model:endDate="form.endTime"
        ></my-time-area>
      </view>

      <view class="default-box-radius bg-fff u-m-t-32 default-box-y-padding">
        <view
          class="u-flex u-p-b-16 default-box-x-padding"
          style="align-items: baseline"
        >
          <view class="font-bold">减免方式</view>
          <view class="u-m-l-32">
            <up-radio-group v-model="form.discountType">
              <up-radio key="FIXED" name="FIXED" label="固定金额"
                >固定金额</up-radio
              >
              <up-radio key="RANDOM" name="RANDOM" label="随机立减"
                >随机立减</up-radio
              >
            </up-radio-group>
            <view class="u-flex u-m-t-16" v-if="form.discountType === 'FIXED'">
              <input
                class="number-box"
                placeholder="请输入内容"
                placeholder-class="color-999 u-font-28"
                type="digit"
                v-model="form.discountAmount"
              />
              <view class="unit">元</view>
            </view>
          </view>
        </view>
        <up-line></up-line>
        <view
          class="u-flex default-box-x-padding default-box-y-padding"
          v-if="form.discountType === 'RANDOM'"
        >
          <view class="font-bold u-m-r-14 no-wrap">随机减免方案</view>
          <my-button height="60rpx" @click="addItem"><text class="no-wrap">添加方案</text></my-button>
          <text class="color-red u-font-24 u-m-l-14"
            >所有概率相加必须等于100%</text
          >
        </view>
        <view class="table" v-if="form.discountType === 'RANDOM'">
          <view
            class="header u-flex u-row-between color-666 default-box-x-padding u-p-t-48 u-p-b-48 bg-f7"
          >
            <view class="">减免金额（元）</view>
            <view class="">概率（%）</view>
            <view class="">操作</view>
          </view>
          <view
            class="tr color-666 u-flex u-row-between default-box-x-padding u-p-t-48 u-p-b-48"
            v-for="(item, index) in form.randomDiscountList"
            :key="index"
          >
            <view class="" style="min-width: 200rpx">{{ item.amount }}</view>
            <view class="">{{ item.probability }}</view>
            <view class="u-flex gap-20">
              <text class="color-main" @click="editItem(index)">编辑</text>
              <text class="color-red" @click="deleteItem(index)">删除</text>
            </view>
          </view>
        </view>
        <view class="u-flex default-box-x-padding u-col-baseline u-m-t-32">
          <text class="font-bold no-wrap">可使用类型</text>
          <view class="u-m-l-42">
            <my-dine-types
              v-model="form.useTypeList"
              :radioCustomStyle="{ marginRight: '10rpx' }"
            ></my-dine-types>
          </view>
        </view>
      </view>
    </view>

    <my-bottom-btn-group
      @cancel="cancel"
      @save="save"
      direction="column"
    ></my-bottom-btn-group>

    <Modal
      v-model="modalData.show"
      :title="modalData.title"
      @confirm="handleConfirm"
    >
      <view class="u-p-l-38 u-p-r-38 u-p-t-40 u-p-b-40">
        <view class="u-flex" style="gap: 50rpx">
          <text class="u-font-32" style="min-width: 128rpx">减免金额</text>
          <view class="u-flex u-m-t-16">
            <input
              class="number-box"
              placeholder="减免金额"
              placeholder-class="color-999 u-font-28"
              type="digit"
              v-model="modalData.form.amount"
            />
            <view class="unit">元</view>
          </view>
        </view>
        <view class="u-flex u-m-t-40 u-col-baseline" style="gap: 50rpx">
          <text class="u-font-32 text-right" style="min-width: 128rpx"
            >概率</text
          >
          <view>
            <view class="u-flex u-m-t-16">
              <input
                class="number-box"
                placeholder="概率"
                placeholder-class="color-999 u-font-28"
                type="digit"
                v-model="modalData.form.probability"
              />
              <view class="unit">%</view>
            </view>
            <view class="u-m-t-18 color-666 u-font-28"
              >所有概率相加必须等于100%</view
            >
          </view>
        </view>
      </view>
    </Modal>
  </view>
</template>

<script setup>
import Modal from "@/pageMarket/components/modal.vue";

import { ref, reactive, computed, watch, onMounted ,nextTick} from "vue";
import { useNewUserDiscountStore } from "@/store/market.js";

const isLoading = ref(false);
const newUserDiscountStore = useNewUserDiscountStore();

const modalData = reactive({
  show: false,
  title: "",
  key: "",
  index: -1,
  form: {
    amount: "",
    probability: "",
  },
});

function resetModalData() {
  modalData.index = -1;
  modalData.form = {
    amount: "",
    probability: "",
  };
}

function addItem() {
  resetModalData();
  modalData.show = true;
  modalData.key = "add";
  modalData.title = "添加方案";
}
function editItem(index) {
  modalData.index = index;
  modalData.form = {...form.randomDiscountList[index]}
  modalData.show = true;
  modalData.key = "edit";
  modalData.title = "编辑方案";
}

function handleConfirm() {
  if (modalData.form.amount == "") {
    uni.showToast({
      title: "请填写减免金额",
      icon: "none",
    });
    return;
  }
  if (modalData.form.probability == "") {
    uni.showToast({
      title: "请填写概率",
      icon: "none",
    });
    return;
  }

  modalData.show = false;
  if (modalData.key == "add") {
    form.randomDiscountList.push(modalData.form);
  } else if (modalData.key == "edit") {
    form.randomDiscountList[modalData.index] = modalData.form;
  }
  resetModalData();
}

const form = reactive({
  startTime: "",
  endTime: "",
  discountType: "FIXED",
  useTypeList: [],
  randomDiscountList: [],
  discountAmount: "",
});

function cancel() {
  uni.navigateBack({
    delta: 1,
  });
}
function deleteItem(index) {
  form.randomDiscountList.splice(index, 1);
}
function save() {
  if (form.useTypeList.length == 0) {
    uni.showToast({
      title: "请选择可使用类型",
      icon: "none",
    });
    return;
  }
  if(form.discountType == "FIXED" && !form.discountAmount ){
    uni.showToast({
      title:'请填写减免金额',
      icon:'none'
    })
    return;
  }
  newUserDiscountStore
    .editConfig(
      {
        ...form,
        startTime: form.startTime ? form.startTime + " 00:00:00" : "",
        endTime: form.endTime ? form.endTime + " 23:59:59" : "",
      },
      false
    )
    .then((res) => {
      if (res) {
        uni.showToast({
          title: "保存成功",
          icon: "none",
        });
        init();
      }
    });
}

watch(
  () => newUserDiscountStore.config.isEnable,
  (newVal) => {
    if(isLoading.value) return;
    newUserDiscountStore.editConfig().then((res) => {
      if (res) {
        uni.showToast({
          title: "操作成功",
          icon: "none",
        });
      }
    });
  }
);

async function init() {
  const res = await newUserDiscountStore.getConfig();
  const data = {
    ...res,
    startTime: res.startTime ? res.startTime.split(" ")[0] : "",
    endTime: res.endTime ? res.endTime.split(" ")[0] : "",
    useTypeList: res.useTypeList || [],
    randomDiscountList: res.randomDiscountList || [],
  };
  console.log(data);
  Object.assign(form, data);
  nextTick(() => {
    isLoading.value = false;

  })
}

onMounted(() => {
  init();
});
</script>
<style lang="scss" scoped>
.tr {
  border-bottom: 1px solid #f7f7f7;
  &:last-child {
    border-bottom: none;
  }
}
:deep(.fixed-bottom) {
  left: 110rpx;
  right: 110rpx;
  align-items: stretch;
}
</style>
