<script lang="ts" setup>
import {z} from "zod";
import ChooseImage from "@/components/choose-image/choose-image.vue";
import useEventEmit from "@/hooks/useEventEmit";
import {EventEnum} from '@/constant/enums'
import Hours from "./components/hours.vue";
import {appMerchantCategoryListGet, appMerchantDetailMerchantIdGet, appMerchantEditPost} from "@/service";
import {upload} from "@/utils/upload/alioss";
import {getStateListApi} from "@/pages-user/service";

const {t} = useI18n();
const formData = ref({
  logo: '',
  merchantName: '', // 商家名称
  phone: '', // 联系电话
  merchantAddress: '', // 商家地址
  merchantCategoryIds: '', // 商家分类ID
  merchantCategoryName: '', // 商家分类名称(仅用于显示)
  longitude: '', // 商家经度
  latitude: '', // 商家纬度
  businessHours: '', // 营业时间
  minOrderPrice: '', // 最小订单金额
  selfPickup: false, // 是否支持自取(1-支持 2-不支持)
  pickupTime: '', // 自取时长(如"30分钟")
  deliveryService: true, // 是否支持配送(1-支持 2-不支持)
  deliveryTime: '1', // 配送时长(单位：天，如"1")
  deliveryFee: '7', // 配送费
  shopImages: [], // 店铺图片URL(多张逗号分隔)
  stateName: '', // 店铺所在州名称
  state: '', // 店铺所在州信息
})

// 表单验证schema
const FormSchema = z.object({
  logo: z.string().min(1, {message: t("pages-user.store-management.index.prompt.logo")}),
  merchantName: z.string().min(1, {message: t("pages-user.store-management.index.prompt.merchantName")}),
  phone: z.string().min(1, {message: t("pages-user.store-management.index.prompt.phone")}),
  merchantAddress: z.string().min(1, {message: t("pages-user.store-management.index.prompt.merchantAddress")}),
  merchantCategoryIds: z.string().min(1, {message: t("pages-user.store-management.index.prompt.merchantCategoryIds")}),
  businessHours: z.string().min(1, {message: t("pages-user.store-management.index.prompt.businessHours")}),
  minOrderPrice: z.string().min(1, {message: t("pages-user.store-management.index.prompt.minOrderPrice")}),
  pickupTime: z.string().optional().refine((val) => {
    // 如果开启了自取，则必须填写自取时长
    return !formData.value.selfPickup || (val && val.length > 0);
  }, {message: t("pages-user.store-management.index.prompt.pickupTime")}),
  deliveryTime: z.string().optional().refine((val) => {
    // 如果开启了配送，则必须填写配送时长
    return !formData.value.deliveryService || (val && val.length > 0);
  }, {message: t("pages-user.store-management.index.prompt.deliveryTime")}),
  deliveryFee: z.string().optional().refine((val) => {
    // 如果开启了配送，则必须填写配送费
    return !formData.value.deliveryService || (val && val.length > 0);
  }, {message: t("pages-user.store-management.index.prompt.deliveryFee")}),
  shopImages: z.array(z.string()).min(1, {message: t("pages-user.store-management.index.prompt.shopImages")}),
});

// 选择店铺类型
useEventEmit(EventEnum.CHOOSE_STORE_TYPE, (data) => {
  console.log('选择店铺类型', data)
  // 处理数据
  if (data.length > 0) {
    formData.value.merchantCategoryIds = data.map(item => item.id).join(',')
    formData.value.merchantCategoryName = data.map(item => item.name).join('、')
  }
})

// 选择店铺地址
function handleAddressPicker() {
  uni.navigateTo({
    url: '/pages-user/pages/search-address/index',
  })
}

useEventEmit(EventEnum.CHOOSE_ADDRESS, (data) => {
  console.log('接收到的地址信息', data)

  // let stateName = '';
  // if (data.addressComponents && Array.isArray(data.addressComponents)) {
  //   // 先判断是否为中国地址
  //   const countryComponent = data.addressComponents.find(component =>
  //       component.types && component.types.includes('country')
  //   );
  //   const isChina = countryComponent && (countryComponent.shortText === 'CN' || countryComponent.longText === '中国');
  //
  //   if (isChina) {
  //     // 中国地址：优先取市级（locality），如果没有则取省级（administrative_area_level_1）
  //     const cityComponent = data.addressComponents.find(component =>
  //         component.types && component.types.includes('locality')
  //     );
  //     const provinceComponent = data.addressComponents.find(component =>
  //         component.types && component.types.includes('administrative_area_level_1')
  //     );
  //
  //     if (cityComponent) {
  //       stateName = cityComponent.longText || cityComponent.shortText || '';
  //     } else if (provinceComponent) {
  //       stateName = provinceComponent.longText || provinceComponent.shortText || '';
  //     }
  //   } else {
  //     // 美国等其他国家：取州级（administrative_area_level_1）
  //     const stateComponent = data.addressComponents.find(component =>
  //         component.types && component.types.includes('administrative_area_level_1')
  //     );
  //     if (stateComponent) {
  //       stateName = stateComponent.longText || stateComponent.shortText || '';
  //     }
  //   }
  // }

  // 解析地址信息并填充表单
  if (data && data.addressComponents) {
    // 重置地址相关字段
    formData.value.merchantAddress = ""
    formData.value.latitude = ""
    formData.value.longitude = ""
    formData.value.merchantAddress = data.formattedAddress
    formData.value.latitude = data.location?.lat || ""
    formData.value.longitude = data.location?.lng || ""
    // formData.value.state = stateName
  }
})


const chooseImageRef = ref();
const chooseImgType = ref('logo')

function chooseImage(type: string) {
  chooseImgType.value = type
  if (chooseImageRef.value?.init) {
    chooseImageRef.value.init();
  }
}

function onImageChange(e: any) {
  if (e.length > 0) {
    if (chooseImgType.value === 'logo') {
      uni.navigateTo({
        url: '/pages-user/pages/store-management/cropper-avatar?data=' + encodeURIComponent(e[0])
      })
    } else {
      formData.value.shopImages.push(e[0])
    }
  }
}

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

useEventEmit(EventEnum.CROPPER_AVATAR, (avatar) => {
  uni.showLoading({
    title: t('common.uploading'),
    mask: true,
  })
  upload(avatar, '.png', 'app/avatar/').then((res) => {
    formData.value.logo = res as string
  }).finally(() => {
    uni.hideLoading()
  })
})

function navigateToScope() {
  uni.navigateTo({url: '/pages-user/pages/store-management/scope?ids=' + formData.value.merchantCategoryIds})
}


const hoursRef = ref();

function openHours() {
  hoursRef.value.onOpen();
}

function handleHoursConfirm(e: any) {
  if (e) {
    formData.value.businessHours = e
  }
}

const merchantId = ref(null);
onLoad((options) => {
  if (options.id) {
    merchantId.value = options.id;
  }
  init()
})

function init() {
  appMerchantDetailMerchantIdGet({
    params: {
      merchantId: merchantId.value
    }
  }).then(res => {
    getStateList()
    console.log('商户详情', res)

    const { selfPickup, deliveryService, ...otherData } = res.data;

    // 1. 先处理基础数据的合并
    Object.assign(formData.value, {
      ...otherData,
      shopImages: (res.data.shopImages || '').split(',').filter(Boolean),
      selfPickup: selfPickup === 1,
      deliveryService: deliveryService === 1
    })

    // 2. 特殊处理：配送时长 (deliveryTime)
    // 处理配送时长：排除 0, "0", "0.00", null, "" 等情况
    const rawDeliveryTime = parseFloat(res.data.deliveryTime);
    formData.value.deliveryTime = (rawDeliveryTime > 0) ? res.data.deliveryTime : '1';

    // 处理配送费：排除 0, "0", "0.00", null, "" 等情况
    const rawDeliveryFee = parseFloat(res.data.deliveryFee);
    formData.value.deliveryFee = (rawDeliveryFee > 0) ? res.data.deliveryFee : '7';

    // 如果经纬度不存在就不要回显位置名字了
    if (!formData.value.latitude || !formData.value.longitude) {
      formData.value.merchantAddress = '';
    }

    if (!res.data.phone) {
      formData.value.phone = ''
    }

    // 处理所有字段的null值，将null重置为空字符串
    // 注意：这里要跳过你刚才处理好的配送时长和费用，防止被重置回空
    Object.keys(formData.value).forEach(key => {
      if (formData.value[key] === null) {
        formData.value[key] = ''
      }
    })

    appMerchantCategoryListGet({
      pageNum: 1,
      pageSize: 100,
    }).then(res => {
      let arr = (formData.value.merchantCategoryIds || '').split(',')
      formData.value.merchantCategoryName = res.data
          .filter(item => arr.includes(item.id))
          .map(item => item.name)
          .join('、')
    })
  })
}

const stateList = ref([])

function getStateList() {
  getStateListApi().then(res => {
    stateList.value = res.data

    // 回显数据
    if (formData.value.state) {
      stateListValue.value = formData.value.state
      const item = stateList.value.find(item => item.id === stateListValue.value)
      if (item) {
        formData.value.stateName = item.name
      }
    }
  })
}

// 表单验证函数
function validateForm() {
  try {
    FormSchema.parse(formData.value);
    return true;
  } catch (error) {
    if (error instanceof z.ZodError) {
      const firstError = error.errors[0];
      uni.showToast({
        title: firstError.message,
        icon: 'none',
        duration: 2000
      });
    }
    return false;
  }
}

// 保存表单
const loading = ref(false)

function handleSave() {
  if (!validateForm()) {
    return;
  }
  // 增加对输入类型的检查，起送金额必须为大于0的数字最多两位小数
  if (formData.value.minOrderPrice) {
    const amount = parseFloat(formData.value.minOrderPrice);
    if (isNaN(amount) || amount <= 0) {
      uni.showToast({
        title: t('pages-user.store-management.index.prompt.minOrderPriceTip'),
        icon: 'none',
        duration: 2000
      });
      return;
    }
  }
  console.log('保存表单数据:', formData.value);
  loading.value = true
  appMerchantEditPost({
    body: {
      ...formData.value,
      shopImages: formData.value.shopImages.join(','),
      selfPickup: formData.value.selfPickup ? 1 : 2,
      deliveryService: formData.value.deliveryService ? 1 : 2,
      id: merchantId.value
    }
  }).then(res => {
    uni.showToast({
      title: t('common.saveSuccess'),
      icon: 'none',
      duration: 2000
    });
    uni.navigateBack()
  }).finally(() => {
    loading.value = false
  })
}

const show = ref(false)
const stateListValue = ref(null)

function handleClickStatePicker() {
  console.log(stateListValue.value)
  const item = stateList.value.find(item => item.id === stateListValue.value)
  if (item) {
    formData.value.state = item.id
    formData.value.stateName = item.name
  }
  show.value = false
}
</script>

<template>
  <view>
    <navbar :title="t('pages-user.store-management.index.title')"/>
    <view class="px-30rpx pt-18rpx pb-134rpx">
      <view class="flex-center-sb">
        <view class="flex items-center">
          <view class="text-36rpx lh-36rpx text-#333 font-500">{{ t('pages-user.store-management.index.logo') }}</view>
          <view class="text-28rpx lh-28rpx text-#999 ml-10rpx">{{
              t('pages-user.store-management.index.logoSizeHint')
            }}
          </view>
        </view>
        <view class="flex items-center" @click="chooseImage('logo')">
          <image
              v-if="formData.logo"
              :src="formData.logo"
              class="w-76rpx h-76rpx rounded-50% mr-10rpx"
              mode="aspectFill"
          />
          <image
              v-else
              class="w-76rpx h-76rpx rounded-50% mr-10rpx"
              mode="aspectFill"
              src="@img/chef/default_avatar.png"
          />
          <image class="w-32rpx h-32rpx" src="@img/chef/115.png"></image>
        </view>
      </view>

      <!--Main Business Scope-->
      <view class="mt-44rpx" @click="navigateToScope">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
          {{ t('pages-user.store-management.index.mainBusinessScope') }}
        </view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <view class="text-30rpx lh-30rpx">
            <text v-if="formData.merchantCategoryName" class="text-#333">
              {{ formData.merchantCategoryName }}
            </text>
            <text v-else class="text-#999">{{ t('common.select') }}</text>
          </view>
          <image class="w-32rpx h-32rpx" src="@img/chef/115.png"></image>
        </view>
      </view>

      <!--Shop Names:-->
      <view class="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
          {{ t('pages-user.store-management.index.shopNames') }}
        </view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <wd-input
              v-model="formData.merchantName"
              :focus-when-clear="false"
              :placeholder="t('common.enter')"
              clearable
              confirm-type="done"
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              use-prefix-slot
          >
          </wd-input>
        </view>
      </view>

      <!--Shop Phone:-->
      <view class="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
          {{ t('pages-user.store-management.index.shopPhone') }}
        </view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <wd-input
              v-model="formData.phone"
              :focus-when-clear="false"
              :placeholder="t('common.enter')"
              clearable
              confirm-type="done"
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              use-prefix-slot
          >
          </wd-input>
        </view>
      </view>

      <!--Shop state:-->
      <view class="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
          {{ t('pages-user.store-management.index.shopState') }}
        </view>
        <view class="w-full h-98rpx lh-98rpx text-30rpx px-24rpx rounded-16rpx bg-#F6F6F6 flex-center-sb"
              @click="show = true">
          <view class="line-clamp-1">
            <text v-if="formData.stateName" class="text-#333">
              {{ formData.stateName }}
            </text>
            <text v-else class="text-#999">{{ t('common.select') }}</text>
          </view>

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

      <!--Shop Address:-->
      <view class="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
          {{ t('pages-user.store-management.index.shopLocation') }}
        </view>
        <view class="h-98rpx lh-98rpx text-30rpx px-24rpx rounded-16rpx bg-#F6F6F6 flex-center-sb"
              @click="handleAddressPicker">
          <view class="line-clamp-1">
            <text v-if="formData.merchantAddress" class="text-#333">
              {{ formData.merchantAddress }}
            </text>
            <text v-else class="text-#999">{{ t('common.select') }}</text>
          </view>

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

      <!--Business Hours:-->
      <view class="mt-44rpx" @click="openHours">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
          {{ t('pages-user.store-management.index.businessHours') }}
        </view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <view class="text-30rpx lh-30rpx line-clamp-1">
            <text v-if="formData.businessHours" class="text-#333">
              {{ formData.businessHours }}
            </text>
            <text v-else class="text-#999">{{ t('common.select') }}</text>
          </view>
          <image class="w-32rpx h-32rpx shrink-0" src="@img/chef/115.png"></image>
        </view>
      </view>

      <!--Delivery Amount:(最小订单金额)-->
      <view class="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
          {{ t('pages-user.store-management.index.deliveryAmount') }}
        </view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <wd-input
              v-model="formData.minOrderPrice"
              :focus-when-clear="false"
              :maxlength="10"
              :placeholder="t('common.enter')"
              clearable
              confirm-type="done"
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              type="digit"
              use-prefix-slot
          >
          </wd-input>
        </view>
      </view>

      <!-- 自取已隐藏 -->
      <view  class="mt-44rpx">
        <view class="flex-center-sb h-44rpx">
          <view class="text-36rpx lh-36rpx text-#333 font-500">{{
              t('pages-user.store-management.index.isSelfPickup')
            }}
          </view>
          <ca-switch
              v-model="formData.selfPickup"
              :offText="t('pages-user.store-management.index.off')"
              :onText="t('pages-user.store-management.index.on')"
              chuteSelColor="#00A76D"
          />
        </view>
        <view v-if="formData.selfPickup" class="animate-in fade-in animate-ease-out animate-duration-300 mt-44rpx">
          <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
            {{ t('pages-user.store-management.index.mealPickupTime') }}
            <text class="text-24rpx text-#999 ml-10rpx font-400">{{ t('common.minutes') }}</text>
          </view>
          <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
            <wd-input
                v-model="formData.pickupTime"
                :focus-when-clear="false"
                :maxlength="4"
                :placeholder="t('common.enter')"
                clearable
                confirm-type="done"
                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>
      </view>

      <!--Whether to deliver or not?-->
      <view class="mt-44rpx">
        <view class="flex-center-sb h-44rpx">
          <view class="text-36rpx lh-36rpx text-#333 font-500">{{
              t('pages-user.store-management.index.isDelivery')
            }}
          </view>
          <!-- <l-switch v-model="formData.deliveryService"
                    :placeholder="[t('pages-user.store-management.index.on'), t('pages-user.store-management.index.off')]"
                    dotSize="14px" height="22px"
                    width="53px"></l-switch> -->

          <ca-switch
              v-model="formData.deliveryService"
              :offText="t('pages-user.store-management.index.off')"
              :onText="t('pages-user.store-management.index.on')"
              chuteSelColor="#00A76D"
          />
        </view>
        <!--Delivery Time:-->
        <view v-if="formData.deliveryService" class="animate-in fade-in animate-ease-out animate-duration-300 mt-44rpx">
          <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
            {{ t('pages-user.store-management.index.deliveryTime') }}
            <text class="text-24rpx text-#999 ml-10rpx font-400">{{ t('common.days') }}</text>
          </view>
          <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
            <wd-input
                v-model="formData.deliveryTime"
                :focus-when-clear="false"
                :maxlength="4"
                :placeholder="t('common.enter')"
                clearable
                confirm-type="done"
                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>

        <!--Delivery Fee:-->
        <view v-if="formData.deliveryService" class="animate-in fade-in animate-ease-out animate-duration-300 mt-44rpx">
          <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
            {{ t('pages-user.store-management.index.deliveryFee') }}
          </view>
          <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
            <wd-input
                v-model="formData.deliveryFee"
                :focus-when-clear="false"
                :placeholder="t('common.enter')"
                clearable
                confirm-type="done"
                custom-class="!text-30rpx !bg-transparent flex-1"
                no-border
                placeholderStyle="font-size: 30rpx;color: #999;"
                type="digit"
                use-prefix-slot
            >
            </wd-input>
          </view>
        </view>
      </view>


      <!--Recommended Dish Pictures:-->
      <view class="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">
          {{ t('pages-user.store-management.index.recommendedDishPictures') }}
        </view>
        <view class="flex items-center gap-30rpx flex-wrap">
          <template v-for="(item, index) in formData.shopImages">
            <view class="relative w-240rpx h-240rpx">
              <image
                  v-if="item"
                  class="absolute top--10rpx right--10rpx z-1 w-36rpx h-36rpx"
                  src="@img/chef/190.png"
                  @click="removeImage(index)"
              ></image>
              <image
                  :src="item"
                  class="w-240rpx h-240rpx rounded-16rpx"
                  mode="aspectFill"
              ></image>
            </view>
          </template>
          <view v-if="formData.shopImages.length < 6" class="center flex-col w-240rpx h-240rpx rounded-20rpx bg-#F6F6F6"
                @click="chooseImage('shopImages')">
            <wd-icon color="#3D3D3D" name="add" size="38px"></wd-icon>
            <text class="text-30rpx lh-30rpx text-#333 mt-22rpx">{{
                t('pages-user.store-management.index.addPicture')
              }}
            </text>
          </view>
        </view>
      </view>
    </view>


    <fixed-bottom-large-btn
        :loading="loading"
        :text="t('pages-user.store-management.index.save')"
        class="!z-100"
        fixed
        @click="handleSave"
    />

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

    <Hours ref="hoursRef" @confirm="handleHoursConfirm"/>

    <wd-popup v-model="show" :safe-area-inset-bottom="true" custom-style="border-radius:20rpx 20rpx 0 0;"
              position="bottom">
      <view class="px-30rpx">
        <view class="flex-center-sb h-102rpx">
          <view class="text-30rpx text-#999" @click="show = false">{{ t('common.cancel') }}</view>
          <view class="text-34rpx text-#333">{{ t('common.select') }}</view>
          <view class="text-30rpx text-#FF6106" @click="handleClickStatePicker">{{ t('common.confirm') }}</view>
        </view>

        <wd-picker-view v-model="stateListValue" :columns="stateList" label-key="name" value-key="id"/>
      </view>
    </wd-popup>
  </view>
</template>

<style>
page {
  background-color: white;
}
</style>
<style lang="scss" scoped>
:deep(.l-switch--checked) {
  background-color: #00A76D !important;
}

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