<script lang="ts" setup>
import {
  appMerchantRecipeAddPost,
  appMerchantRecipeRecipeDetailPost,
  appMerchantRecipeUpdatePost,
  appRecipeCategoryListGet
} from "@/service";
import ChooseImage from "@/components/choose-image/choose-image.vue";
import {z} from "zod";

const {t} = useI18n()

const formData = ref({
  recipeName: '', // 菜谱名称
  recipeCategoryName: '', // 菜谱分类名称
  recipeCategoryId: '', // 菜谱分类ID
  ingredients: '', // 菜谱描述
  recipeImage: []
})

// Zod 表单校验 schema
const FormSchema = z.object({
  recipeName: z.string().min(1, {message: t("pages-user.recipe.schema.recipeName")}),
  recipeCategoryId: z.string().min(1, {message: t("pages-user.recipe.schema.recipeCategory")}),
  ingredients: z.string().min(1, {message: t("pages-user.recipe.schema.ingredients")}),
  recipeImage: z.array(z.string()).min(1, {message: t("pages-user.recipe.schema.recipeImage")})
})

function openClassification() {
  show.value = true
}

const chooseImageRef = ref()
const handleChooseImage = () => {
  chooseImageRef.value.init()
}

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

function removeImage(index: number) {
  formData.value.recipeImage.splice(index, 1)
}

const show = ref(false)
const typePickerValue = ref(null)
const columnsType = ref([])

function handleClose() {
  show.value = false
}

function handleSubmitPickType() {
  const data = columnsType.value.find(item => item.value === typePickerValue.value)
  formData.value.recipeCategoryName = data.label
  formData.value.recipeCategoryId = data.value
  show.value = false
}

onLoad((options) => {
  if (options.id) {
    formData.value.id = options.id
    getRecipeDetail()
  } else {
    getRecipeCategoryList()
  }
})

function getRecipeDetail() {
  appMerchantRecipeRecipeDetailPost({
    params: {
      recipeId: formData.value.id
    }
  }).then(res => {
    console.log('获取菜谱详情', res)
    formData.value.recipeName = res.data.recipeName
    // formData.value.recipeCategoryName = res.data.recipeCategoryName
    formData.value.recipeCategoryId = res.data.recipeCategoryId
    formData.value.ingredients = res.data.ingredients
    formData.value.recipeImage = res.data.recipeImage ? res.data.recipeImage.split(',') : []

    //确保Id加载完毕
    getRecipeCategoryList()
  })
}

function getRecipeCategoryList() {
  appRecipeCategoryListGet({
    options: {}
  }).then(res => {
    console.log('菜谱分类', res)
    columnsType.value = res.data.map((item) => {
      return {
        label: item.categoryName,
        value: item.id
      }
    })
    typePickerValue.value = columnsType.value[0].value

    if (formData.value.id && formData.value.recipeCategoryId) {
      // 编辑状态下，回显分类
      typePickerValue.value = formData.value.recipeCategoryId
      formData.value.recipeCategoryName = columnsType.value.find(item => item.value === typePickerValue.value)?.label || ''
    }
  })
}

function handleSubmit() {
  try {
    // 验证表单数据
    FormSchema.parse(formData.value)
    console.log('表单验证通过', formData.value)
    if (formData.value.id) {
      appMerchantRecipeUpdatePost({
        body: {
          ...formData.value,
          recipeImage: formData.value.recipeImage.join(',') // 将图片数组转换为逗号分隔的字符串
        }
      }).then(res => {
        uni.showToast({
          title: t('toast.submitSuccess'),
          icon: 'none'
        })
        uni.navigateBack()
      })
    } else {
      // 这里可以添加提交逻辑
      appMerchantRecipeAddPost({
        body: {
          ...formData.value,
          recipeImage: formData.value.recipeImage.join(',') // 将图片数组转换为逗号分隔的字符串
        }
      }).then(res => {
        uni.showToast({
          title: t('toast.submitSuccess'),
          icon: 'none'
        })
        uni.navigateBack()
      })
    }
  } catch (error) {
    if (error instanceof z.ZodError) {
      // 显示第一个验证错误
      const firstError = error.errors[0]
      uni.showToast({
        title: firstError.message,
        icon: 'none'
      })
    }
  }
}
</script>

<template>
  <view>
    <navbar :title="formData.id ? t('pages-user.recipe.editRecipe') : t('pages-user.recipe.addRecipe')"></navbar>
    <view class="px-30rpx">
      <!--Recipe Classification:-->
      <view class="mt-30rpx" @click="openClassification">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">{{
            t('pages-user.recipe.recipeClassification')
          }}
        </view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6 text-30rpx lh-30rpx">
          <template v-if="formData.recipeCategoryName">
            <text class="text-#333">
              {{ formData.recipeCategoryName }}
            </text>
          </template>
          <template v-else>
            <text class="text-#999">
              {{ t("common.select") }}
            </text>
          </template>
          <image class="w-32rpx h-32rpx" src="@img/chef/115.png"></image>
        </view>
      </view>

      <!--Recipe Name::-->
      <view class="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">{{ t('pages-user.recipe.recipeName') }}</view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <wd-input
              v-model="formData.recipeName"
              :focus-when-clear="false"
              :placeholder="t('pages-user.recipe.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="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">{{
            t('pages-user.recipe.ingredientsPreparation')
          }}
        </view>
        <view
            class="min-h-352rpx box-border bg-#F6F6F6 rounded-14rpx overflow-hidden px-18rpx py-10rpx"
        >
          <wd-textarea
              v-model="formData.ingredients"
              :maxlength="500"
              :placeholder="t('pages-user.recipe.enterPlaceholder')"
              auto-height
              custom-class="!bg-#F6F6F6"
              custom-textarea-container-class="!bg-#F6F6F6"
              no-border
          />
        </view>
      </view>


      <view class="mt-44rpx pb-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-10rpx">{{ t('pages-user.recipe.recipeImage') }}</view>
        <view class="text-22rpx lh-22rpx text-#999 mb-30rpx">{{ t('pages-user.recipe.dragTip') }}</view>

        <view class="grid grid-cols-3 gap-20rpx">
          <template v-for="(item, index) in formData.recipeImage">
            <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.recipeImage.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.recipe.addPicture') }}</text>
          </view>
        </view>
      </view>
    </view>


    <fixed-bottom-large-btn
        :text="t('common.submit')"
        class="z-100"
        fixed
        @click="handleSubmit"
    />

    <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">{{ t('common.placeholder.pleaseSelect') }}</view>
          <view class="text-30rpx text-#FF6106" @click="handleSubmitPickType">{{ t('common.confirm') }}</view>
        </view>
        <view class="bg-#fff px-54rpx py-56rpx">
          <wd-picker-view v-model="typePickerValue" :columns="columnsType"/>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

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