<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 dragImg from '@/components/drag-img/drag-img.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'
import { resolve } from 'dns'

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 useImg = ref(true)
const useVideo = ref(true)
const formData = ref({})
const formInited = ref(false)
const tagName = ref('')
const tagIds = ref([])
const imgList = ref([])
const publishing = ref(false)
const delImg = (index:number) =>{
	fileList.value = imgList.value
}
const sortChange = () =>{
	console.log('sort')
	fileList.value = imgList.value
}
const handleChange = ({ fileList: files }) => {  
  console.log(files)
  let arr = [];
  // for(let i in files){	  
	 //  if(files[i].status==="success"){
		//   arr.push(files[i])
	 //  }
  // }
  fileList.value = files
  imgList.value = files
  if(files.length > 0){
	  useVideo.value = false
  }else{
	  useVideo.value = true
  }
}
const handleVideoChange = ({ fileList: files }) => {
  fileList.value = files
  if(files.length > 0){
  	  useImg.value = false
  }else{
  	  useImg.value = true
  }
  // console.log(imgList.value)
}
const uploadImg = async (img) =>{
	 return new Promise((resolve)=>{
		 uni.uploadFile({
		 	url:action.value,
		 	filePath: img,
		 	name:img,
		 	success: (res) => {
		 		// console.log(res)
		 		resolve(res)
		 	}
		 })
	 })
}
const handleSubmit = async () => {
  if (circleType.value === CircleType.case) {
    const { valid, errors } = await dataFormRef.value.validate()
    console.log(valid, errors)
    if (!valid) {
      return false
    }
  }
  // if (!imgList.value.length) {
  //   toast(messages.moment.imageNotExist)
  //   return false
  // }
  // console.log(imgList.value)
  // let imgUrl = [];
  // for(let i in imgList.value){
	 //  let res = await uploadImg(imgList.value[i])
	 //  console.log(res)
	 //  imgUrl.push()
  // }
  // console.log(imgUrl)
  // return false
  if(useImg.value){
	  if (!imgList.value.length) {
	    toast(messages.moment.imageNotExist)
	    return false
	  }
  }else{
	  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: useImg.value?imgList.value.map(({ response }) => JSON.parse(response).data):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>
	<div class="flex">
		<div class="mr-[20rpx]" v-if="useImg">
			<wd-upload
			  :file-list="fileList"
			  image-mode="aspectFill"
			  accept="image"
			  :action="action"
			  :multiple="true"
			  :limit="String(circleType) === '2' ? 30 : 9"
			  @change="handleChange"
			></wd-upload>
			<div class="text-[24rpx] text-black/60 text-center">上传图片</div>
		</div>
		<div v-if="useVideo && String(circleType) === '1'">
			<wd-upload
			  :file-list="fileList"
			  image-mode="aspectFill"
			  accept="video"
			  :action="action"
			  :limit="1"
			  @change="handleVideoChange"
			></wd-upload>
			<div class="text-[24rpx] text-black/60 text-center">上传视频</div>
		</div>
	</div>
	<dragImg keyName='url' v-if="imgList.length > 0" v-model="imgList" @del="delImg" @sortChange="sortChange" :number="String(circleType) === '2' ? 30 : 9"></dragImg>
    <SectionHeading
      title="标签"
      custom-class="my-6"
      :path="`/pages-sub/publish/tags/index?tagName=${tagName}`"
      size="base"
    >
      <template #start>
        <div class="flex gap-2.5 overflow-x-scroll">
          <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 shrink-0"
              >
                <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>
    <div class="w-full relative z-9">
		<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>
  </div>
</template>
<style>
	.display{
		display: none !important;
	}
</style>