<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, getDesigners } from '../core/libs/agent-requests'
import { useFollowUp } from '../composables/followUp'
import AMapWX from '@/pages/common/amap-wx.130'

const action = ref(`${import.meta.env.VITE_SERVER_BASEURL}/app-api/infra/file/upload`)
const fileList = ref<string[]>([])
const userStore = useUserStore()
const { userInfo, isAgent, isMerchant } = storeToRefs(userStore)
const { schema, rules, schemaTypeOnline } = useFollowUp()
const publishState = ref(false)
const designerList = ref<any[]>([])
const dataForm = ref({
  stylistId: '',
  followType: '1',
  followTime: new Date().getTime(),
  address: {
    latitude: 0,
    longitude: 0,
    address: '',
  },
  imgUrl: '',
})
const currentAddress = ref<any>([])
const dataFormRef = ref<ComponentExposed<typeof DataForm>>()
const schemaTypeOnlineRef = ref<ComponentExposed<typeof DataForm>>()
// 地图实例化
const AmapFun = new AMapWX.AMapWX({ key: 'efde483f8801a09d3c5db032556e6593' })
const wxGetAddress = (longitude: number, latitude: number) => {
  return new Promise((resolve, reject) => {
    AmapFun.getRegeo({
      location: `${longitude},${latitude}`,
      success: (res: any) => {
        resolve(res)
      },
      fail: (err: any) => {
        reject(err)
      },
    })
  })
}
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
    }
    dataForm.value.address.address = ''
    dataForm.value.address.latitude = 0
    dataForm.value.address.longitude = 0
    dataForm.value.imgUrl = ''
    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
  }
  if (fileList.value.length) {
    const temp: string[] = []
    fileList.value.forEach((each: any) => {
      temp.push(JSON.parse(each.response).data)
    })
    dataForm.value.imgUrl = temp.join(',')
  }
  console.log(dataForm.value)
  if (!dataForm.value.imgUrl) {
    uni.showToast({ icon: 'none', title: '请上传图片' })
    return false
  }
  if (!dataForm.value.address && dataForm.value.followType === '1') {
    uni.showToast({ icon: 'none', title: '请刷新定位' })
    return false
  }
  const { code } = await requestToast(() => createFollowUp(dataForm.value), {
    success: true,
    successTitle: '跟进成功',
  })
  if (code === 0) {
    publishState.value = false
    dataForm.value = {
      stylistId: '',
      followType: '1',
      followTime: new Date().getTime(),
      address: {
        latitude: 0,
        longitude: 0,
        address: '',
      },
      imgUrl: '',
    }
    fileList.value = []
    uni.$emit('refresh')
  }
}
const handleChange = ({ fileList: files }) => {
  fileList.value = files
  console.log(fileList.value)
}
const getCurrentLocation = () => {
  uni.showToast({ icon: 'loading', title: '正在获取位置...' })
  uni.getLocation({
    type: 'gcj02',
    success: async (success: any) => {
      currentAddress.value = await wxGetAddress(success?.longitude, success?.latitude)
      const { name, latitude, longitude } = currentAddress.value[0]
      dataForm.value.address.address = name
      dataForm.value.address.latitude = latitude
      dataForm.value.address.longitude = longitude
      uni.hideToast()
    },
    fail: (err) => {
      console.log('获取地址失败', err)
      if (err.errCode === 1005 || err.errCode === 10001) {
        console.log('位置权限未授权')
        uni.authorize({
          scope: 'scope.userLocation',
          success: () => {
            uni.getLocation({
              type: 'gcj02',
              success: async (success) => {
                console.log('授权后，获取地址', success)
                currentAddress.value = await wxGetAddress(success?.longitude, success?.latitude)
                const { name, latitude, longitude } = currentAddress.value[0]
                dataForm.value.address.address = name
                dataForm.value.address.latitude = latitude
                dataForm.value.address.longitude = longitude
                uni.hideToast()
              },
              fail: function (err) {
                console.log('获取位置失败:', err)
                uni.hideToast()
              },
            })
          },
          fail: function () {
            uni.hideToast()
            // 用户拒绝授权,可以选择记录下来,不再提示
            uni.showToast({
              title: '您拒绝了位置授权',
              icon: 'none',
              duration: 2000,
            })
            // 可以引导用户去设置中授权
            uni.showModal({
              title: '提示',
              content: '请在系统设置中打开定位服务权限',
              success: function (modalRes) {
                if (modalRes.confirm) {
                  uni.openSetting()
                }
              },
            })
          },
        })
      }
    },
  })
}
onMounted(async () => {
  const {
    data: { list },
  } = await getDesigners({
    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 h-[calc(65vh)]! overflow-y-auto">
        <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"
              >
                <span
                  class="text-[#ef4343] text-base font-normal font-['PingFang_SC'] leading-normal visible"
                >
                  *
                </span>
                地址
              </label>
              <div
                class="wd-input h-[40px] lh-[40px] flex justify-between px-[20px]"
                @click="getCurrentLocation"
              >
                <div>
                  {{ !dataForm.address.address ? '点击获取当前位置' : dataForm.address.address }}
                </div>
                <wd-icon name="refresh" size="14px"></wd-icon>
              </div>
            </div>
          </template>
          <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">
              <span
                class="text-[#ef4343] text-base font-normal font-['PingFang_SC'] leading-normal visible"
              >
                *
              </span>
              图片
            </label>
            <wd-upload
              :file-list="fileList"
              image-mode="aspectFill"
              accept="media"
              :action="action"
              :multiple="true"
              :limit="9"
              @change="handleChange"
            ></wd-upload>
          </div>
        </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>
