<script lang="ts" setup>
const {t} = useI18n()

interface SpecValue {
  name: string
  price: string
  memberPrice: string
  actualSalePrice: string
}

interface SpecGroup {
  sideDishName: string
  isRequired: 1 | 2,
  merchantSideDishItemBoList: SpecValue[]
}

const formData = reactive({
  merchantSideDishBoList: [] as SpecGroup[]
})

const addSpecGroup = () => {
  const newGroup: SpecGroup = {
    sideDishName: '',
    isRequired: 1,
    merchantSideDishItemBoList: [
      {
        name: '',
        price: '',
        memberPrice: '',
        actualSalePrice: ''
      }
    ]
  }
  formData.merchantSideDishBoList.push(newGroup)
}

const removeSpecGroup = (groupIndex: number) => {
  formData.merchantSideDishBoList.splice(groupIndex, 1)
}

const addSpecValue = (groupIndex: number) => {
  const newValue: SpecValue = {
    name: '',
    price: '',
    memberPrice: '',
    actualSalePrice: ''
  }
  formData.merchantSideDishBoList[groupIndex].merchantSideDishItemBoList.push(newValue)
}

const removeSpecValue = (groupIndex: number, valueIndex: number) => {
  if (formData.merchantSideDishBoList[groupIndex].merchantSideDishItemBoList.length > 1) {
    formData.merchantSideDishBoList[groupIndex].merchantSideDishItemBoList.splice(valueIndex, 1)
  }
}

const submitForm = () => {
  for (let i = 0; i < formData.merchantSideDishBoList.length; i++) {
    const group = formData.merchantSideDishBoList[i]
    if (!group.sideDishName.trim()) {
      uni.showToast({
        title: t('pages-user.food.add-item.validation.enterSpecName', {index: i + 1}),
        icon: 'none'
      })
      return
    }

    for (let j = 0; j < group.merchantSideDishItemBoList.length; j++) {
      const value = group.merchantSideDishItemBoList[j]
      if (!value.name.trim() || !value.price.trim() || !value.memberPrice.trim() || !value.actualSalePrice.trim()) {
        uni.showToast({
          title: t('pages-user.food.add-item.validation.completeAllFields', {index: i + 1}),
          icon: 'none'
        })
        return
      }
    }
  }

  if (formData.merchantSideDishBoList.length === 0) {
    uni.showToast({
      title: t('pages-user.food.add-item.validation.addAtLeastOne'),
      icon: 'none'
    })
    return
  }

  console.log('Submit form:', formData)

  uni.showToast({
    title: t('pages-user.food.add-item.validation.submittedSuccessfully'),
    icon: 'none'
  })
  eventChannel.emit('acceptDataFromOpenedPage', formData);
  uni.navigateBack()
}

let instance = null
let eventChannel = null
onMounted(() => {
  instance = getCurrentInstance().proxy
  eventChannel = instance.getOpenerEventChannel();

  eventChannel.on('acceptDataFromOpenerPage', function (data) {
    console.log('acceptDataFromOpenerPage', data.data)
    if (data.data && data.data.length > 0) {
      formData.merchantSideDishBoList = data.data.map((group: SpecGroup) => ({
        ...group,
        merchantSideDishItemBoList: (group.merchantSideDishItemBoList || []).map((item) => ({
          ...item,
          memberPrice:
            item.memberPrice !== undefined && item.memberPrice !== null && String(item.memberPrice) !== ''
              ? String(item.memberPrice)
              : '',
          actualSalePrice:
            item.actualSalePrice !== undefined && item.actualSalePrice !== null && String(item.actualSalePrice) !== ''
              ? String(item.actualSalePrice)
              : ''
        }))
      }))
    }
  })
})
onUnload(() => {
  instance = null
  eventChannel = null
})

addSpecGroup()

function handleClickItem(group: SpecGroup) {
  group.isRequired = group.isRequired === 1 ? 2 : 1
}
</script>

<template>
  <view class="add-item-page bg-#F6F6F6 min-h-100vh">
    <!-- 状态栏 -->
    <navbar :title="t('pages-user.food.add-item.title')"/>

    <!-- 页面内容 -->
    <view class="content px-30rpx pt-40rpx pb-200rpx">
      <view
          v-for="(group, groupIndex) in formData.merchantSideDishBoList"
          :key="groupIndex"
          class="spec-group mb-40rpx"
      >
        <view class="flex-center-sb mb-26rpx">
          <text class="text-28rpx text-#999 block">{{ t('pages-user.food.add-item.spec') }} {{
              groupIndex + 1
            }}:
          </text>

          <view
              class="w-48rpx h-48rpx"
              @tap="removeSpecGroup(groupIndex)"
          >
            <image class="w-48rpx h-48rpx" src="@img/chef/190.png"></image>
          </view>
        </view>
        <view class="bg-white rounded-20rpx px-20rpx py-30rpx relative">
          <view class="mb-20rpx">
            <text class="text-36rpx text-#333 font-500 mb-20rpx block">{{
                t('pages-user.food.add-item.specType')
              }}
            </text>
            <view class="bg-#F6F6F6 rounded-16rpx h-98rpx px-24rpx flex items-center">
              <wd-input
                  v-model="group.sideDishName"
                  :focus-when-clear="false"
                  :placeholder="t('pages-user.food.add-item.enterPlaceholder')"
                  clearable
                  confirm-type="search"
                  custom-class="!text-30rpx !bg-transparent flex-1"
                  no-border
                  placeholderStyle="font-size: 30rpx;color: #999;"
                  use-prefix-slot
              >
              </wd-input>
            </view>
          </view>

          <view class="mb-44rpx flex-center-sb">
            <text class="text-36rpx text-#333 font-500 mb-20rpx block">
              {{ t('pages-user.food.add-item.isRequired') }}
            </text>
            <view class="shrink-0" @click="handleClickItem(group)">
              <image
                  :src="
              group.isRequired === 1
                ? '/static/images/chef/133.png'
                : '/static/images/chef/134.png'
            "
                  class="w-48rpx h-48rpx shrink-0"
                  mode="aspectFit"
              />
            </view>
          </view>

          <text class="text-36rpx text-#333 font-500 mb-30rpx block">
            {{ t('pages-user.food.add-item.specValue') }}
          </text>

          <view class="values-list">
            <view
                v-for="(value, valueIndex) in group.merchantSideDishItemBoList"
                :key="valueIndex"
                class="mb-10rpx last:mb-0"
            >
              <view class="bg-white py-28rpx border-2rpx border-solid border-#DFDFDF rounded-16rpx px-20rpx">
                <view class="flex-center-sb mb-26rpx">
                  <text class="text-26rpx text-#333 font-500 block">{{ t('pages-user.food.add-item.value') }}
                    {{ valueIndex + 1 }}:
                  </text>

                  <view
                      class="w-48rpx h-48rpx"
                      @click="removeSpecValue(groupIndex, valueIndex)"
                  >
                    <image class="w-48rpx h-48rpx" src="@img/chef/190.png"></image>
                  </view>
                </view>
                <view class="form-row flex items-center mb-24rpx">
                  <text class="label text-28rpx text-#333 w-120rpx">{{ t('pages-user.food.add-item.name') }}</text>
                  <view class="bg-#F6F6F6 rounded-16rpx h-88rpx px-20rpx flex-1 flex items-center">
                    <wd-input
                        v-model="value.name"
                        :focus-when-clear="false"
                        :placeholder="t('pages-user.food.add-item.enterPlaceholder')"
                        clearable
                        confirm-type="search"
                        custom-class="!text-30rpx !bg-transparent flex-1"
                        no-border
                        placeholderStyle="font-size: 30rpx;color: #999;"
                        use-prefix-slot
                    >
                    </wd-input>
                  </view>
                </view>

                <view class="form-row flex items-center mb-24rpx">
                  <text class="label text-28rpx text-#333 w-120rpx">{{ t('pages-user.food.add-item.price') }}</text>
                  <view class="bg-#F6F6F6 rounded-16rpx h-88rpx px-20rpx flex-1 flex items-center">
                    <wd-input
                        v-model="value.price"
                        :focus-when-clear="false"
                        :placeholder="t('pages-user.food.add-item.enterPlaceholder')"
                        clearable
                        confirm-type="search"
                        custom-class="!text-30rpx !bg-transparent flex-1"
                        no-border
                        placeholderStyle="font-size: 30rpx;color: #999;"
                        use-prefix-slot
                    >
                    </wd-input>
                  </view>
                </view>

                <view class="form-row flex items-center mb-24rpx">
                  <text class="label text-28rpx text-#333 w-120rpx">{{ t('pages-user.food.add-item.memberPrice') }}</text>
                  <view class="bg-#F6F6F6 rounded-16rpx h-88rpx px-20rpx flex-1 flex items-center">
                    <wd-input
                        v-model="value.memberPrice"
                        :focus-when-clear="false"
                        :placeholder="t('pages-user.food.add-item.enterPlaceholder')"
                        clearable
                        confirm-type="search"
                        custom-class="!text-30rpx !bg-transparent flex-1"
                        no-border
                        placeholderStyle="font-size: 30rpx;color: #999;"
                        use-prefix-slot
                    >
                    </wd-input>
                  </view>
                </view>

                <view class="form-row flex items-center">
                  <text class="label text-28rpx text-#333 w-120rpx">{{ t('pages-user.food.add-item.actualSalePrice') }}</text>
                  <view class="bg-#F6F6F6 rounded-16rpx h-88rpx px-20rpx flex-1 flex items-center">
                    <wd-input
                        v-model="value.actualSalePrice"
                        :focus-when-clear="false"
                        :placeholder="t('pages-user.food.add-item.enterPlaceholder')"
                        clearable
                        confirm-type="search"
                        custom-class="!text-30rpx !bg-transparent flex-1"
                        no-border
                        placeholderStyle="font-size: 30rpx;color: #999;"
                        use-prefix-slot
                    >
                    </wd-input>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <view
              class="bg-#F2F2F2 rounded-20rpx h-88rpx center mt-24rpx"
              @click="addSpecValue(groupIndex)"
          >
            <text class="text-30rpx text-#333 font-500">+ {{ t('pages-user.food.add-item.add') }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <fixed-bottom-large-btn
        :text="t('common.submit')"
        class="z-100"
        fixed
        @click="submitForm"
    />
  </view>
</template>

<style>
page {
  background-color: #F6F6F6;
}
</style>