<route lang="json">
{
  "style": {
    "navigationBarTitleText": "个人动态",
    "navigationBarBackgroundColor": "#fff"
  }
}
</route>
<script setup lang="ts">
import SectionHeading from '@/components/section-heading.vue'
import { createCircle, getByDictType } from '../../../core/libs/requests'
import { useUserStore } from '../../../store'
import { storeToRefs } from 'pinia'
import { useToast } from 'wot-design-uni'
import { CircleType, DictType } from '../../../core/libs/models'
import DataForm from '@/components/data-form.vue'
import { zipToObject } from 'radash'
import { useRouter } from '../../../core/utils/router'
import BottomAppBar from '@/components/bottom-app-bar.vue'
import { requestToast, toast } from '../../../core/utils/common'
import { messages } from '../../../core/libs/messages'
import { DataFormSchema } from '../../../components/data-form'
import { ComponentExposed } from 'vue-component-type-helpers'
import {AnalysisEventType, useAnalysis} from '@/composables/analysis'

const { report } = useAnalysis(false)
const router = useRouter()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const { error } = useToast()
const circleType = ref<CircleType>()
const content = ref('')
const fileList = ref([])
const action = ref(`${import.meta.env.VITE_SERVER_BASEURL}/app-api/infra/file/upload`)
const dataFormRef = ref<ComponentExposed<typeof DataForm>>()
const schema = ref<DataFormSchema>({
  caseName: {
    label: '案例名称:',
    type: 'TextField',
    required: true,
    labelWidth: 80,
    props: { placeholder: '填写案例位置/名称' },
  },
  spaceType: {
    label: '空间类别:',
    type: 'Select',
    required: true,
    labelWidth: 80,
    props: {
      placeholder: '选择',
      columns: [],
    },
  },
  designStyle: {
    label: '设计风格:',
    type: 'Select',
    required: true,
    labelWidth: 80,
    props: { columns: [], placeholder: '选择' },
  },
  // spaceAddr: { label: '空间位置', type: 'TextField' },
  spaceExtent: {
    label: '空间面积:',
    type: 'TextField',
    required: true,
    labelWidth: 80,
    props: { placeholder: '填写面积' },
  },
  circleDesc: {
    label: '案例描述:',
    type: 'Textarea',
    required: true,
    labelWidth: 80,
    props: { placeholder: '请简单描述您的案例和设计理念', maxlength: 500 },
  },
  // customerDemand: { label: '客户需求', type: 'TextField' },
})
const rules = {
  caseName: [{ required: true, message: '请填写案例名称' }],
  spaceType: [{ required: true, message: '请选择空间类别' }],
  designStyle: [{ required: true, message: '请选择设计风格' }],
  spaceExtent: [{ required: true, message: '请填写空间面积' }],
  circleDesc: [{ required: true, message: '请填写案例描述' }],
}
const formData = ref({})
const formInited = ref(false)
const tagName = ref('')
const tagIds = ref([])
const publishing = ref(false)
const handleChange = ({ fileList: files }) => {
  fileList.value = files
  console.log(fileList.value)
}
const handleSubmit = async () => {
  if (circleType.value === CircleType.case) {
    const { valid, errors } = await dataFormRef.value.validate()
    console.log(valid, errors)
    if (!valid) {
      return false
    }
  }
  if (!fileList.value.length) {
    toast(messages.moment.imageNotExist)
    return false
  }
  publishing.value = true
  const { code, msg, duration } = await requestToast(
    () =>
      createCircle({
        stylistId: userInfo.value.userId,
        stylistName: userInfo.value.nickname,
        bannerUrls: fileList.value.map(({ response }) => JSON.parse(response).data),
        tagName: tagName.value,
        headUrl: userInfo.value.avatar,
        circleDesc: content.value,
        circleType: circleType.value,
        tagIds: tagIds.value,
        ...formData.value,
      }),
    { success: true, successTitle: '发布成功' },
  )

  if (code === 0) {
    setTimeout(() => {
      publishing.value = false
      router.back()
    }, duration)
    await report(AnalysisEventType.PublishCircle)
    // publishing.value = false
    // router.back()
  }
}
const updateTagName = (options: { tagNames: string[]; tagIds: string[] }) => {
  if (options.tagNames.length === 0) {
    tagName.value = ''
    return
  }
  tagName.value = options.tagNames.join(',')
  tagIds.value = options.tagIds
}
onMounted(() => {
  uni.$on('updateTagName', updateTagName)
})
onUnmounted(() => {
  uni.$off('updateTagName', updateTagName)
})
onLoad(async (query: { circleType: '1' | '2' }) => {
  circleType.value = query.circleType as CircleType
  await uni.setNavigationBarTitle({ title: { '1': '个人动态', '2': '设计案例' }[circleType.value] })
  const optionsSchema = {
    designStyle: getByDictType(DictType.memberDesignStyle).then(({ data }) => data),
    spaceType: getByDictType(DictType.circleSpaceType).then(({ data }) => data),
  }
  const res = zipToObject(
    Object.keys(optionsSchema),
    await Promise.all(Object.values(optionsSchema)),
  )
  schema.value.designStyle.props.columns = res.designStyle
  schema.value.spaceType.props.columns = res.spaceType
  formInited.value = true
})
</script>
<template>
  <div class="flex-grow bg-white p-3.5 flex flex-col">
    <template v-if="circleType === CircleType.case && formInited">
      <DataForm
        ref="dataFormRef"
        v-model="formData"
        :schema="schema"
        :rules="rules"
        direction="horizontal"
      ></DataForm>
    </template>
    <template v-if="circleType === CircleType.moment">
      <wd-textarea v-model="content" placeholder="分享你此刻的想法" />
    </template>

    <!-- <div class="flex items-center">
      <img
        class="w-[100px] h-[100px] rounded-lg overflow-hidden"
        src="https://via.placeholder.com/100x100"
      />
      <div class="w-[100px] h-[100px] bg-[#f3f3f3] justify-center items-center inline-flex">
        <div class="w-7 h-7 relative flex-col justify-start items-start flex"></div>
      </div>
    </div> -->
    <div v-if="circleType === '2'" class="flex items-center">
      <span class="text-[#ef4343] text-base font-normal font-['PingFang_SC'] leading-normal">
        *
      </span>
      <SectionHeading
        title="实景图:"
        subtitle="首图建议尺寸1125x1104，最多可上传30张"
        size="base"
        custom-class="my-5"
      ></SectionHeading>
    </div>
    <wd-upload
      :file-list="fileList"
      image-mode="aspectFill"
      accept="media"
      :action="action"
      :multiple="true"
      :limit="String(circleType) === '2' ? 30 : 9"
      @change="handleChange"
    ></wd-upload>
    <SectionHeading
      title="标签"
      custom-class="my-6"
      :path="`/pages/publish/tags/index?tagName=${tagName}`"
      size="base"
    >
      <template #start>
        <div class="flex gap-2.5">
          <template v-if="tagName !== ''">
            <template v-for="it of tagName.split(',')" :key="it">
              <div
                class="h-6 px-2 py-0.5 bg-[#f3f3f3] rounded-[3px] justify-center items-center gap-2 inline-flex"
              >
                <div
                  class="text-center text-black/90 text-xs font-normal font-['PingFang_SC'] leading-tight"
                >
                  #{{ it }}
                </div>
              </div>
            </template>
          </template>
        </div>
      </template>
    </SectionHeading>
    <div class="flex-1"></div>
    <BottomAppBar fixed safe-area-inset-bottom placeholder>
      <div class="w-full">
        <wd-button type="primary" :round="false" block :loading="publishing" @click="handleSubmit">
          发布
        </wd-button>
      </div>
    </BottomAppBar>
  </div>
</template>
