<script lang="ts" setup>
import {ref} from 'vue'
import {z} from "zod";
import ChooseImage from "@/components/choose-image/choose-image.vue";
import {
  appMerchantDishAddDishPost,
  appMerchantDishDetailGet,
  appMerchantDishEditDishPost,
  appMerchantDishRemovePost,
  appMerchantMenuMenuListByMerchantPost
} from "@/service";
import {useMessage} from "wot-design-uni";

const message = useMessage();
const {t} = useI18n()
// 表单数据
const formData = ref({
  id: '',
  dishName: '',
  dishDescription: '',
  menu: '',
  menuId: '',
  originalPrice: '', // 原价
  discountPrice: '', // 折扣价
  weight: '', // 重量(磅)
  tax: '', // 税费
  dishImage: [] as string[],
  merchantSideDishVoList: [] as any[], // 配菜列表
  isActive: true, // 是否激活
  stock: '', // 库存
})

// Zod 表单校验 schema
const FormSchema = z.object({
  dishName: z.string().min(1, t('pages-user.food.add-food.schema.dishName')),
  dishDescription: z.string().min(1, t('pages-user.food.add-food.schema.dishDescription')),
  menuId: z.string().min(1, t('pages-user.food.add-food.schema.menuId')),
  originalPrice: z.string().min(1, t('pages-user.food.add-food.schema.originalPrice')),
  discountPrice: z.string()
      .min(1, t('pages-user.food.add-food.schema.discountPriceRequired'))
      .refine(
          (val) => {
            const num = parseFloat(val.trim())
            return !isNaN(num) && num > 0
          },
          {message: t('pages-user.food.add-food.schema.discountPricePositive') ?? '折扣价必须大于0'},
      ),
  stock: z.string()
      .min(1, t('pages-user.food.add-food.stockRequired'))
      .refine(
          (val) => {
            const trimmed = val.trim()
            if (trimmed === '') return false
            const num = Number(trimmed)
            return Number.isInteger(num)
          },
          {message: t('pages-user.food.add-food.stockMustBeInteger')}
      )
      .refine(
          (val) => {
            const num = Number(val.trim())
            return num >= 0
          },
          {message: t('pages-user.food.add-food.stockMustBeNonNegative')}
      )
}).refine((data) => {
  if (data.discountPrice && data.discountPrice.trim() !== '') {
    const originalPrice = parseFloat(data.originalPrice)
    const discountPrice = parseFloat(data.discountPrice)
    if (!isNaN(originalPrice) && !isNaN(discountPrice)) {
      return discountPrice <= originalPrice
    }
  }
  return true
}, {
  message: t('pages-user.food.add-food.discountPriceError'),
  path: ['discountPrice']
})

// 图片上传
const chooseImageRef = ref()
const handleChooseImage = () => {
  chooseImageRef.value.init()
}

function onImageChange(files: string[]) {
  formData.value.dishImage.push(files[0])
}

// 删除图片
const removeImage = (index: number) => {
  formData.value.dishImage.splice(index, 1)
}

const merchantSideDishVoList = ref([])

function syncPriceFromSpec() {
  const specList = merchantSideDishVoList.value.merchantSideDishBoList
  if (specList && specList.length > 0) {
    const firstGroup = specList[0]
    const items = firstGroup.merchantSideDishItemBoList
    if (items && items.length > 0) {
      const first = items[0] as { price?: string; memberPrice?: string }
      const listPrice = first.price != null && String(first.price).trim() !== '' ? String(first.price).trim() : ''
      const memberPrice =
        first.memberPrice != null && String(first.memberPrice).trim() !== '' ? String(first.memberPrice).trim() : ''
      if (listPrice) {
        formData.value.originalPrice = listPrice
      }
      if (memberPrice) {
        formData.value.discountPrice = memberPrice
      }
    }
  }
}

/** 提交用：保持规格完整传递（包含第一项） */
function buildMerchantSideDishBoListForSubmit() {
  const raw = merchantSideDishVoList.value.merchantSideDishBoList
  if (!raw || !Array.isArray(raw) || raw.length === 0) {
    return raw || []
  }
  return JSON.parse(JSON.stringify(raw)) as any[]
}

/** 保存/编辑请求体：去掉详情里的 Vo 列表与旧 Bo 列表，只传去重后的 merchantSideDishBoList，避免修改时重复提交 */
function buildDishSaveBody(stockValue: number) {
  const fd = formData.value as Record<string, unknown>
  const {
    merchantSideDishVoList: _vo,
    merchantSideDishBoList: _bo,
    dishImage: _dishImgArr,
    ...rest
  } = fd
  return {
    ...rest,
    tax: Number(formData.value.tax) / 100 || 0,
    stock: stockValue,
    merchantSideDishBoList: buildMerchantSideDishBoListForSubmit(),
    dishImage: formData.value.dishImage.join(','),
    delFlag: formData.value.isActive ? 1 : 3
  }
}

function navigateTo(url: string) {
  uni.navigateTo({
    url,
    events: {
      acceptDataFromOpenedPage: function (data) {
        console.log(data)
        if (data) {
          merchantSideDishVoList.value = data
          syncPriceFromSpec()
        }
      },
    },
    success: function (res) {
      res.eventChannel.emit('acceptDataFromOpenerPage', {data: merchantSideDishVoList.value.merchantSideDishBoList || []})
    }
  })
}


onLoad((options) => {
  if (options && options.id) {
    formData.value.id = options.id
    getDishDetail()
  }
  // 商家查询菜单列表
  getMenuListByMerchant()
})

// 默认分页配置（避免一次请求 1000 条）
const DEFAULT_PAGE_SIZE = 10;
const DEFAULT_PAGE_NUM = 1;

const menuList = ref<any[]>([])

async function getMenuListByMerchant() {
  const allRows: any[] = []
  let pageNum = DEFAULT_PAGE_NUM

  while (true) {
    const res = await appMerchantMenuMenuListByMerchantPost({
      params: {
        pageSize: DEFAULT_PAGE_SIZE,
        pageNum
      }
    })

    const rows = res.rows || []
    allRows.push(...rows)

    if ((typeof res.total === 'number' && allRows.length >= res.total) || rows.length < DEFAULT_PAGE_SIZE) {
      break
    }

    pageNum += 1
    if (pageNum > 200) break
  }

  menuList.value = allRows

  if (menuList.value.length === 0) {
    uni.showToast({
      title: t('pages-user.food.add-food.tips'),
      icon: 'none'
    })
    return
  }

  selectedMenu.value = menuList.value[0]?.id

  // 回显 menu
  formData.value.menu = menuList.value.find(item => item.id === formData.value.menuId)?.menuName
}

// 获取菜品详情
function getDishDetail() {
  if (!formData.value.id) {
    return
  }
  appMerchantDishDetailGet({
    params: {
      dishId: formData.value.id
    }
  }).then(res => {
    console.log('获取菜品详情', res)

    const transformedData = res.data.merchantSideDishVoList.map(item => {
      // 检查目标属性是否存在
      if ('merchantSideDishItemVoList' in item) {
        const {merchantSideDishItemVoList, ...rest} = item;
        return {
          ...rest,
          merchantSideDishItemBoList: merchantSideDishItemVoList
        };
      }
      return {...item};
    });

    console.log('获取菜品详情', transformedData)
    merchantSideDishVoList.value.merchantSideDishBoList = transformedData

    // 安全处理库存值
    let stockValue = ''
    if (res.data.stock !== null && res.data.stock !== undefined) {
      const stock = Number(res.data.stock)
      // 确保库存是有效的非负整数
      if (Number.isInteger(stock) && stock >= 0) {
        stockValue = String(stock)
      }
    }

    formData.value = {
      ...res.data,
      dishImage: res.data.dishImage ? res.data.dishImage.split(',') : [],
      merchantSideDishBoList: transformedData,
      isActive: +res.data.delFlag === 1,
      stock: stockValue
    }
    console.log('获取菜品详情', formData.value)
  })
}

const show = ref(false)
const selectedMenu = ref('')

function chooseMenu() {
  if (menuList.value.length === 0) {
    uni.showToast({
      title: t('pages-user.food.add-food.tips'),
      icon: 'none'
    })
    return
  }
  show.value = true
}

function handleClose() {
  show.value = false
}

// 删除菜品
function deleteDish() {
  message
      .confirm({
        title: t("common.prompt.system-prompt"),
        msg: `${t("common.prompt.system-prompt-delete")}`,
        confirmButtonText: t("common.yes"),
        cancelButtonText: t("common.no"),
        cancelButtonProps: {
          customClass:
              "!h-88rpx !w-258rpx !min-w-auto !text-30rpx  !lh-42rpx !font-bold !border-#666666   !rounded-20rpx",
        },
        confirmButtonProps: {
          customClass:
              "!h-88rpx !w-258rpx !min-w-auto !text-30rpx !lh-42rpx !font-bold  !bg-primary  !rounded-20rpx",
        },
      })
      .then(async () => {
        appMerchantDishRemovePost({
          body: [formData.value.id]
        }).then((res) => {
          console.log('删除菜品', res)
          uni.showToast({
            title: t('toast.deleteSuccess'),
            icon: 'none'
          })
          uni.navigateBack()
        })
      })
      .catch(() => {
      });
}

function handleSubmit() {
  let data = menuList.value.find(item => item.id === selectedMenu.value)
  if (data) {
    formData.value.menu = data.menuName
    formData.value.menuId = data.id
  }
  handleClose()
}

function saveDish() {
  // Zod 表单验证
  const validationResult = FormSchema.safeParse(formData.value)
  if (!validationResult.success) {
    const firstError = validationResult.error.errors[0]
    uni.showToast({
      title: firstError.message,
      icon: 'none'
    })
    return
  }

  // 安全处理库存值
  const stockValue = formData.value.stock ? Number(formData.value.stock.trim()) : 0
  const body = buildDishSaveBody(stockValue)

  if (formData.value.id) {
    appMerchantDishEditDishPost({
      body
    }).then(() => {
      uni.showToast({
        title: t('toast.submitSuccess'),
        icon: 'none'
      })
      uni.navigateBack()
    })
  } else {
    appMerchantDishAddDishPost({
      body
    }).then(() => {
      uni.showToast({
        title: t('toast.submitSuccess'),
        icon: 'none'
      })
      uni.navigateBack()
    })
  }
}
</script>

<template>
  <view class="add-food-page">
    <!-- 状态栏 -->
    <navbar/>

    <!-- 页面内容 -->
    <view class="px-30rpx">
      <!-- 标题 -->
      <view class="mb-80rpx flex-center-sb mt-20rpx">
        <text class="text-46rpx lh-46rpx text-#333 font-500">{{ t('pages-user.food.add-food.title') }}</text>
        <view>
          <template v-if="formData.id">
            <view class="bg-#F2F2F2 rounded-32rpx w-134rpx h-64rpx center font-500 text-26rpx text-#333"
                  @click="deleteDish">
              {{ t('common.delete') }}
            </view>
          </template>
        </view>
      </view>

      <!-- 菜品名称 -->
      <view class="form-item mb-40rpx">
        <text class="label text-36rpx lh-36rpx text-#333 mb-20rpx block font-500">{{
            t('pages-user.food.add-food.name')
          }}
        </text>
        <view class="bg-#F6F6F6 rounded-16rpx h-98rpx px-24rpx flex items-center">
          <wd-input
              v-model="formData.dishName"
              :focus-when-clear="false"
              :placeholder="t('pages-user.food.add-food.enterPlaceholder')"
              clearable
              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-item mb-52rpx">
        <view class="flex-center-sb text-36rpx lh-36rpx text-#333 font-500 mb-24rpx">
          <text class="">{{ t('pages-user.food.add-food.description') }}</text>
          <text class="">{{ formData.dishDescription.length }}/4000</text>
        </view>
        <text class="text-28rpx lh-28rpx text-#999 mb-36rpx block">{{
            t('pages-user.food.add-food.descriptionTip')
          }}
        </text>
        <view class="bg-#F6F6F6 rounded-16rpx min-h-352rpx px-24rpx">
          <wd-textarea
              v-model="formData.dishDescription"
              :maxlength="4000"
              :placeholder="t('pages-user.food.add-food.enterPlaceholder')"
              auto-height
              custom-class="!bg-#F6F6F6"
              custom-textarea-container-class="!bg-#F6F6F6"
              no-border
          />
        </view>
      </view>

      <!-- 图片上传 -->
      <view class="form-item mb-52rpx">
        <view class="flex items-center mb-20rpx">
          <text class="text-36rpx lh-36rpx text-#333 mr-10rpx font-500">{{
              t('pages-user.food.add-food.pictures')
            }}
          </text>
          <text class="text-28rpx text-#999">({{ formData.dishImage.length }}/9)</text>
        </view>

        <view class="grid grid-cols-3 gap-20rpx">
          <template v-for="(item, index) in formData.dishImage">
            <view class="relative w-210rpx h-210rpx">
              <image
                  v-if="item"
                  class="absolute top-0rpx right-0rpx z-1 w-36rpx h-36rpx"
                  src="@img/chef/190.png"
                  @click="removeImage(index)"
              ></image>
              <image
                  :src="item"
                  class="w-210rpx h-210rpx rounded-16rpx"
                  mode="aspectFill"
              ></image>
            </view>
          </template>

          <view v-if="formData.dishImage.length < 9" class="w-210rpx h-210rpx center flex-col bg-#F6F6F6 rounded-20rpx"
                @click="handleChooseImage">
            <wd-icon color="#3D3D3D" name="add" size="32px"></wd-icon>
            <text class="text-30rpx lh-30rpx text-#333 mt-20rpx">{{ t('pages-user.food.add-food.addPicture') }}</text>
          </view>
        </view>
      </view>

      <!-- 菜单选择 -->
      <view class="form-item mb-52rpx" @click="chooseMenu">
        <text class="text-36rpx lh-36rpx text-#333 mb-20rpx block font-500">{{
            t('pages-user.food.add-food.menu')
          }}
        </text>
        <view
            class=" bg-#F6F6F6 rounded-32rpx h-98rpx px-24rpx flex-center-sb"
        >
          <view class="flex items-center">
            <image class="w-28rpx h-28rpx shrink-0 mr-16rpx" src="@img/chef/106.png"></image>
            <text :class="formData.menu ? 'text-#333' : 'text-#999'" class="text-30rpx">
              {{ formData.menu || t('pages-user.food.add-food.addMenu') }}
            </text>
          </view>

          <image class="w-32rpx h-32rpx shrink-0" src="@img/chef/115.png"></image>
        </view>
      </view>

      <!-- 价格（自动从第一项规格填充，只读） -->
      <view class="form-item mb-52rpx">
        <text class="label text-36rpx lh-36rpx text-#333 mb-20rpx block font-500">{{
            t('pages-user.food.add-food.price')
          }}
        </text>
        <view class="bg-#F6F6F6 rounded-16rpx h-98rpx px-24rpx flex items-center">
          <text class="text-30rpx text-#333 mr-20rpx">$</text>
          <wd-input
              v-model="formData.originalPrice"
              :focus-when-clear="false"
              custom-class="!text-30rpx !bg-transparent flex-1"
              disabled
              no-border
              placeholder="0.00"
              placeholderStyle="font-size: 30rpx;color: #999;"
              use-prefix-slot
          >
          </wd-input>
        </view>
        <text class="text-24rpx text-#999 mt-10rpx block">{{ t('pages-user.food.add-food.originalPriceAutoFillTip') }}</text>
      </view>

      <!-- 实际销售价格（自动从第一项规格会员价填充，只读） -->
      <view class="form-item mb-52rpx">
        <text class="label text-36rpx lh-36rpx text-#333 mb-20rpx block font-500">
          {{ t('pages-user.food.add-food.discountedPrice') }}
        </text>
        <view class="bg-#F6F6F6 rounded-16rpx h-98rpx px-24rpx flex items-center">
          <text class="text-30rpx text-#333 mr-20rpx">$</text>
          <wd-input
              v-model="formData.discountPrice"
              :focus-when-clear="false"
              custom-class="!text-30rpx !bg-transparent flex-1"
              disabled
              no-border
              placeholder="0.00"
              placeholderStyle="font-size: 30rpx;color: #999;"
              use-prefix-slot
          >
          </wd-input>
        </view>
        <text class="text-24rpx text-#999 mt-10rpx block">{{ t('pages-user.food.add-food.discountPriceAutoFillTip') }}</text>
      </view>

      <!-- 重量: -->
      <view class="form-item mb-52rpx">
        <text class="label text-36rpx lh-36rpx text-#333 mb-20rpx block font-500">
          {{ t('pages-user.food.add-food.weight') }}
        </text>
        <view class="bg-#F6F6F6 rounded-16rpx h-98rpx px-24rpx flex-center-sb">
          <wd-input
              v-model="formData.weight"
              :focus-when-clear="false"
              clearable
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholder="0.00"
              placeholderStyle="font-size: 30rpx;color: #999;"
              use-prefix-slot
          >
          </wd-input>
          <text class="text-30rpx text-#333 ml-20rpx">{{ t('pages-user.food.add-food.pound') }}</text>
        </view>
      </view>

      <!-- 税费: -->
      <view class="form-item mb-52rpx">
        <text class="label text-36rpx lh-36rpx text-#333 mb-20rpx block font-500">
          {{ t('pages-user.food.add-food.taxRate') }}
        </text>
        <view class="bg-#F6F6F6 rounded-16rpx h-98rpx px-24rpx flex-center-sb">
          <wd-input
              v-model="formData.tax"
              :focus-when-clear="false"
              clearable
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholder="0.00"
              placeholderStyle="font-size: 30rpx;color: #999;"
              use-prefix-slot
          >
          </wd-input>
          <text class="text-30rpx text-#333 ml-20rpx">%</text>
        </view>
      </view>

      <!-- 库存数量 -->
      <view class="form-item mb-52rpx">
        <text class="label text-36rpx lh-36rpx text-#333 mb-20rpx block font-500">
          {{ t('pages-user.food.add-food.stock') }}
        </text>
        <view class="bg-#F6F6F6 rounded-16rpx h-98rpx px-24rpx flex items-center">
          <wd-input
              v-model="formData.stock"
              :focus-when-clear="false"
              :maxlength="5"
              :placeholder="t('pages-user.food.add-food.stockPlaceholder')"
              clearable
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              type="number"
              use-prefix-slot
          >
          </wd-input>
        </view>
      </view>

      <!-- Item is active -->
      <view class="form-item mb-52rpx">
        <view class="flex-center-sb">
          <text class="text-36rpx lh-36rpx text-#333 mb-20rpx block font-500">
            {{
              formData.isActive ? t('pages-user.food.add-food.itemIsActive') : t('pages-user.food.add-food.itemIsNot')
            }}:
          </text>
          <wd-switch v-model="formData.isActive" active-color="#00A76D" size="20px"/>
        </view>
        <view class="text-28rpx lh-28rpx text-#999 mt-10rpx">
          {{ t('pages-user.food.add-food.itemActiveDesc') }}
        </view>
      </view>

      <view class="form-item mb-52rpx">
        <view class="flex-center-sb">
          <text class="text-36rpx lh-36rpx text-#333 mb-20rpx block font-500">
            {{ t('pages-user.food.add-food.specManagement') }}
          </text>
          <view class="bg-#F2F2F2 rounded-32rpx w-158rpx h-64rpx center font-500 text-26rpx text-#333"
                @click="navigateTo('/pages-user/pages/food/add-item')">
            <image class="w-28rpx h-28rpx shrink-0 mr-10rpx" src="@img/chef/107.png"></image>
            {{ t('pages-user.food.add-food.add') }}
          </view>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <fixed-bottom-large-btn
        :text="t('common.save')"
        class="z-100"
        fixed
        @click="saveDish"
    />

    <ChooseImage ref="chooseImageRef" @change="onImageChange"/>


    <wd-popup
        v-model="show"
        position="bottom"
        @close="handleClose"
    >
      <view>
        <view class="flex-center-sb h-102rpx bg-#F7F7F7 px-30rpx">
          <view class="text-30rpx text-#999">{{ t('common.cancel') }}</view>
          <view class="text-34rpx text-#333"></view>
          <view class="text-30rpx text-#FF6106" @click="handleSubmit">{{ t('common.confirm') }}</view>
        </view>
        <view class="bg-#fff px-54rpx py-56rpx">
          <wd-picker-view v-model="selectedMenu" :columns="menuList" label-key="menuName" value-key="id"/>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style>
page {
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
:deep(.uni-picker-view-wrapper) {
  & > uni-picker-view-column:first-of-type .uni-picker-view-group {
    .uni-picker-view-indicator {
      border-radius: 20rpx 0 0 20rpx !important;

      &:after {
        border: none;
      }

      &:before {
        border: none;
      }
    }
  }
}

:deep(.wd-picker-view-column__item) {
  line-height: 94rpx !important;
}

:deep(.uni-picker-view-indicator) {
  height: 94rpx !important;
}

:deep(.wd-input__clear) {
  background-color: transparent !important;
}
</style>