<script setup lang="ts">
import TabbarEvo from '@/components/tabbar-evo.vue'
import { currRoute } from '../utils'
import { defaultThemeVars } from '../core/themes/default'
import DataForm from '@/components/data-form.vue'
import { addUnit } from 'wot-design-uni/components/common/util'

import { useUserStore } from '../store'
import { storeToRefs } from 'pinia'
import {
  addBlue,
  channelTabbarHome,
  channelTabbarHomeActive,
  channelTabbarMine,
  channelTabbarMineActive,
} from '@designer-hub/assets/src/assets/svgs'
import { ComponentExposed } from 'vue-component-type-helpers'
import { getDesignerList } from '../core/libs/requests'
import { requestToast } from '@designer-hub/app/src/core/utils/common'
import { createFollowUp } from '../core/libs/agent-requests'
import { useFollowUp } from '../composables/followUp'
import { success } from '@/core/libs/svgs'

const userStore = useUserStore()
const { userInfo, isAgent, isMerchant } = storeToRefs(userStore)
const { schema, rules, schemaTypeOnline, schemaTypeOffline } = useFollowUp()
const publishState = ref(false)
const designerList = ref<any[]>([])
const dataForm = ref({
  stylistId: '',
  followType: '1',
})
const dataFormRef = ref<ComponentExposed<typeof DataForm>>()
const schemaTypeOfflineRef = ref<ComponentExposed<typeof DataForm>>()
const schemaTypeOnlineRef = ref<ComponentExposed<typeof DataForm>>()
const items = computed(() => {
  if (isAgent.value) {
    return [
      {
        title: '首页',
        iconPath: channelTabbarHome,
        selectedIconPath: channelTabbarHomeActive,
        path: '/pages/home/index',
      },
      {
        title: '跟进',
        iconPath: addBlue,
        selectedIconPath: addBlue,
        path: '/pages/publish/index',
        // hiddenTitle: true,
        main: true,
      },
      {
        title: '我的',
        iconPath: channelTabbarMine,

        selectedIconPath: channelTabbarMineActive,
        path: '/pages/mine/index',
      },
    ]
  }
  return [
    {
      title: '首页',
      iconPath: channelTabbarHome,
      selectedIconPath: channelTabbarHomeActive,
      path: '/pages/home/index',
    },
    {
      title: '我的',
      iconPath: channelTabbarMine,
      selectedIconPath: channelTabbarMineActive,
      path: '/pages/mine/index',
    },
  ]
})
const handleTabbarItemClick = (path: string) => {
  if (path === '/pages/publish/index') {
    if (schema.value.stylistId.props.columns.length > 0) {
      const { value } = designerList.value[0]
      dataForm.value.stylistId = value
    }
    publishState.value = true
    return
  }
  uni.switchTab({ url: path })
}
const handleAdd = async (e) => {
  console.log(e)
  publishState.value = true
}
const handleSubmit = async () => {
  const { valid } = await dataFormRef.value.validate()
  if (!valid) {
    return
  }
  console.log(dataForm.value)
  const { code } = await requestToast(
    () =>
      createFollowUp({ ...dataForm.value, address: { address: '', latitude: '', longitude: '' } }),
    {
      success: true,
      successTitle: '跟进成功',
    },
  )
  if (code === 0) {
    publishState.value = false
  }
}
const getCurrentLocation = () => {
  console.log('点击地址')
  uni.chooseAddress({
    success: (success) => {
      console.log('地理位置 成功', success)
    },
    fail: (fail) => {
      console.log('获取地址失败', fail)
    },
  })
}
onMounted(async () => {
  const {
    data: { list },
  } = await getDesignerList({
    brokerId: userInfo.value?.userId.toString(),
    pageNo: 1,
    pageSize: -1,
  })
  schema.value.stylistId.props.columns = list.map((item) => ({
    value: item.id,
    label: item.name,
  }))
  designerList.value = schema.value.stylistId.props.columns
  console.log('dataForm.value', designerList.value)
})
</script>

<template>
  <wd-config-provider :themeVars="defaultThemeVars" custom-class="flex-grow flex flex-col">
    <view class="bg-[#F2F3F6] pb-20 flex-grow">
      <slot />
    </view>

    <TabbarEvo
      :items="items"
      fixed
      safeAreaInsetBottom
      :current-path="currRoute().path"
      @click="handleTabbarItemClick"
    />
    <wd-action-sheet v-model="publishState" title="创建跟进" @close="publishState = false">
      <view class="flex flex-col p-4">
        <div>
          <DataForm
            ref="dataFormRef"
            :schema="schema"
            :rules="rules"
            direction="horizontal"
            v-model="dataForm"
          ></DataForm>
          <!-- 根据 followType 值 区分 线下 线上 -->
          <template v-if="dataForm.followType === '1'">
            <div
              class="grid mb-4 items-start"
              :style="{ 'grid-template-columns': `${addUnit(64)} auto` }"
            >
              <label
                class="text-sm font-normal leading-relaxed text-black/60 h-10 flex items-center"
              >
                地址
              </label>
              <div
                class="wd-input h-[40px] lh-[40px] flex justify-between px-[20px]"
                @click="getCurrentLocation"
              >
                <div>点击获取当前位置</div>
                <wd-icon name="refresh" size="14px"></wd-icon>
              </div>
            </div>
          </template>
          <DataForm
            ref="schemaTypeOnlineRef"
            :schema="schemaTypeOnline"
            :rules="rules"
            direction="horizontal"
            v-model="dataForm"
          ></DataForm>
        </div>
        <div><wd-button block :round="false" @click="handleSubmit">提交</wd-button></div>
      </view>
    </wd-action-sheet>
    <wd-toast />
    <wd-message-box />
  </wd-config-provider>
</template>

<style lang="scss">
/* stylelint-disable-next-line selector-type-no-unknown */
layout-tabbar-uni {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}
</style>
