<route lang="yaml">
style:
  navigationBarTitleText: 添加标签
  navigationBarBackgroundColor: '#fff'
</route>
<script setup lang="ts">
import SectionHeading from '@/components/section-heading.vue'
import {
  createMemberTag,
  deleteMemberTag,
  getByDictType,
  getCircleTags,
  getMemberTags,
} from '../../../core/libs/requests'
import { DictType } from '../../../core/libs/models'
import { ref } from 'vue'
import { useUserStore } from '../../../store'
import { storeToRefs } from 'pinia'
import { useMessage } from 'wot-design-uni'
import FormMessageBox from '@/components/form-message-box.vue'
import { requestToast } from '../../../core/utils/common'

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const { confirm } = useMessage('wd-message-box-slot')
const { confirm: deleteConfirm } = useMessage()
const formData = ref({})
const { data: tagTypes, run: setTagTypes } = useRequest(() => getByDictType(DictType.circleTag), {
  initialData: [],
})
const { data: tagsData, run: setTagsData } = useRequest(() => getCircleTags({}), {
  initialData: { list: [] },
})
const { data: memberTags, run: setMemberTags } = useRequest(
  () => getMemberTags({ stylistId: userInfo.value?.userId.toString() }),
  {
    initialData: [],
  },
)
const selected = ref<string[]>([])
const tagIds = ref<string[]>([])

const handleClick = ({ tagName, tagId, isReport }) => {
  if (selected.value.includes(tagName)) {
    selected.value = selected.value.filter((it) => it !== tagName)
  } else {
    selected.value.push(tagName)
  }
  if (!isReport) return
  if (tagIds.value.includes(tagId)) {
    tagIds.value = tagIds.value.filter((it) => it !== tagId)
  } else {
    tagIds.value.push(tagId)
  }
}
const handleSubmit = async () => {
  await uni.navigateBack()
  uni.$emit('updateTagName', { tagNames: selected.value, tagIds: tagIds.value })
}
const handleAddTag = async () => {
  await confirm({
    title: '添加标签',
    beforeConfirm: async ({ resolve }) => {
      const { code } = await requestToast(
        () =>
          createMemberTag({
            ...formData.value,
            stylistId: userInfo.value?.userId,
            stylistName: userInfo.value?.nickname,
          }),
        {
          success: true,
          successTitle: '添加成功',
        },
      )
      if (code === 0) {
        await setMemberTags()
        formData.value = {}
        resolve(true)
      }
      resolve(false)
    },
  })
}
const handleDeleteTag = async (tag: any) => {
  deleteConfirm({
    title: '删除标签',
    msg: '确定删除该标签吗？',
    beforeConfirm: async ({ resolve }) => {
      const { code } = await requestToast(() => deleteMemberTag(tag.id), {
        success: true,
        successTitle: '删除成功',
      })
      if (code === 0) {
        await setMemberTags()
        resolve(true)
      }
      resolve(false)
    },
  })
}
onMounted(async () => {
  await setTagTypes()
  await setTagsData()
  await setMemberTags()
})
onLoad(async (query: { tagName: string }) => {
  if (query.tagName !== '') {
    selected.value = query.tagName.split(',')
  }
})
</script>
<template>
  <div class="bg-white flex-grow p-3.5 flex flex-col">
    <template v-for="{ value, label } of tagTypes" :key="value">
      <SectionHeading :title="label" custom-class="my-6" size="base"></SectionHeading>
      <div class="flex flex-wrap gap-2">
        <template
          v-for="{ id, labelName } of tagsData.list.filter(
            ({ labelType }) => labelType.toString() === value.toString(),
          )"
          :key="id"
        >
          <wd-tag
            @click="handleClick({ tagName: labelName, tagId: id, isReport: true })"
            :type="selected.includes(labelName) ? 'primary' : 'default'"
          >
            {{ labelName }}
          </wd-tag>
        </template>
      </div>
    </template>
    <SectionHeading title="自定义标签" custom-class="my-6" size="base"></SectionHeading>
    <div class="flex flex-wrap">
      <template v-for="(it, i) in memberTags" :key="i">
        <div class="relative">
          <div class="absolute right-0">
            <div
              class="w-5 h-5 bg-red-6 rounded-full flex items-center justify-center"
              @click="handleDeleteTag(it)"
            >
              <wd-icon name="close" color="#fff" size="12"></wd-icon>
            </div>
          </div>
          <wd-tag
            custom-class="m-1"
            @click="handleClick({ tagName: it.tagName, tagId: it.id, isReport: false })"
            :type="selected.includes(it.tagName) ? 'primary' : 'default'"
          >
            {{ it.tagName }}
          </wd-tag>
        </div>
      </template>
      <wd-tag custom-class="m-1" @click="handleAddTag">
        <wd-icon name="add"></wd-icon>
      </wd-tag>
    </div>
    <div class="flex-1"></div>
    <div><wd-button block :round="false" @click="handleSubmit()">确定</wd-button></div>
    <FormMessageBox
      v-model="formData"
      :schema="{ tagName: { type: 'TextField', label: '标签', hiddenLabel: true } }"
    ></FormMessageBox>
  </div>
</template>
