<route lang="json">
{ "style": { "navigationBarTitleText": "个人设置" } }
</route>
<script setup lang="ts">
import SectionHeading from '@/components/section-heading.vue'
import { useUserStore } from '../../../store'
import { storeToRefs } from 'pinia'
import {
  getUserAuthInfo,
  updateMemberUserInfo,
  getUserBasicInfo,
  updateUserAuthInfo,
} from '../../../core/libs/requests'
import { NetImages } from '../../../core/libs/net-images'
import FormMessageBox from '@/components/form-message-box.vue'
import { useMessage } from 'wot-design-uni'
import { requestToast } from '../../../core/utils/common'
import { DataFormSchema } from '../../../components/data-form'
import dayjs from 'dayjs'

const userStore = useUserStore()
const { userInfo, isDesigner } = storeToRefs(userStore)
const { setUserInfo } = userStore
const { confirm } = useMessage('nickname')
const formData = ref<any>({})
const schema = ref<DataFormSchema>()
const birthday = ref(dayjs().toDate().getTime())
const birthdayShow = ref(false)
const { data: userAuthInfo, run: setUserAuthInfo } = useRequest(() => getUserAuthInfo(), {})
const { data: userBasicInfo, run: setUserBasicInfo } = useRequest(
  () => getUserBasicInfo({ userId: userInfo.value.userId.toString() }),
  {},
)
const handleChooseAvatar = async ({ detail: { avatarUrl } }) => {
  const { data } = await uni.uploadFile({
    url: '/app-api/infra/file/upload',
    filePath: avatarUrl,
    name: 'file',
  })
  const { data: url } = JSON.parse(data)
  console.log(url)

  const { code, msg } = await updateMemberUserInfo({ avatar: url })
  if (code === 0) {
    uni.showToast({
      title: '修改成功',
      icon: 'none',
    })
    setUserInfo({
      ...userInfo.value,
      avatar: url,
    })
    return
  }
  uni.showToast({
    title: msg,
    icon: 'none',
    mask: true,
  })
}
const handleLogout = () => {
  userStore.clearUserInfo()
  uni.reLaunch({
    url: '/pages/home/index',
  })
}
const handleSetNickname = async () => {
  if (isDesigner.value) {
    return false
  }
  formData.value = {
    nickname: userInfo.value.nickname,
  }
  schema.value = { nickname: { type: 'TextField', label: '姓名', props: { type: 'nickname' } } }
  confirm({
    title: '修改姓名',
    beforeConfirm: async ({ resolve }) => {
      const { code } = await requestToast(() => updateMemberUserInfo(formData.value), {
        success: true,
        successTitle: '修改成功',
      })
      if (code === 0) {
        setUserInfo({
          ...userInfo.value,
          nickname: formData.value?.nickname,
        })
        resolve(true)
        formData.value = {}
      }
      resolve(false)
    },
  })
}
const handleSetSex = async () => {
  formData.value = {
    sex: userInfo.value.sex.toString(),
  }
  schema.value = {
    sex: {
      type: 'Radio',
      label: '性别',
      hiddenLabel: true,
      props: {
        columns: [
          { label: '男', value: '0' },
          { label: '女', value: '1' },
        ],
      },
    },
  }
  confirm({
    title: '修改性别',
    beforeConfirm: async ({ resolve }) => {
      const res = await Promise.all([updateMemberUserInfo(formData.value)])
      console.log(res)
      setUserInfo({
        ...userInfo.value,
        sex: formData.value.sex,
      })
      resolve(true)
      formData.value = {}
      uni.showToast({
        title: '修改成功',
        icon: 'none',
        mask: true,
      })
    },
  })
}
const handleSetEmployer = async () => {
  formData.value = {
    employer: userAuthInfo.value.employer,
  }
  schema.value = {
    employer: {
      type: 'TextField',
      label: '公司',
      hiddenLabel: true,
      props: {},
    },
  }
  confirm({
    title: '修改公司',
    beforeConfirm: async ({ resolve }) => {
      const { code } = await requestToast(
        () =>
          updateUserAuthInfo({
            ...userAuthInfo.value,
            employer: formData.value.employer,
          }),
        {
          success: true,
          successTitle: '修改成功',
        },
      )
      if (code === 0) {
        resolve(true)
        formData.value = {}
        setUserAuthInfo()
      }
      resolve(false)
    },
  })
}
const handeleSetBirthday = async () => {
  const { code, data } = await requestToast(
    () =>
      updateMemberUserInfo({
        birthday: dayjs(birthday.value).toDate().getTime(),
      }),
    {
      success: true,
      successTitle: '修改成功',
    },
  )
  if (code === 0) {
    // await setUserBasicInfo()
    setUserInfo({
      ...userInfo.value,
      birthday: dayjs(birthday.value).toDate().getTime(),
    })
    birthdayShow.value = false
  }
}
onMounted(async () => {
  await setUserAuthInfo()
  if (isDesigner.value) {
    await Promise.all([setUserBasicInfo()])
    console.log(userBasicInfo.value)
  }
  birthday.value = userInfo.value.birthday || dayjs().toDate().getTime()
})
</script>
<template>
  <div class="flex-grow bg-white flex flex-col p-4.5 gap-8">
    <div class="flex flex-col items-center">
      <button
        class="p-0 leading-0 bg-transparent after:b-none"
        open-type="chooseAvatar"
        @chooseavatar="handleChooseAvatar"
      >
        <wd-img
          round
          width="97"
          height="97"
          :src="(userInfo.avatar ?? '') === '' ? NetImages.DefaultAvatar : userInfo.avatar"
          custom-class="border border-white border-solid"
        ></wd-img>
      </button>
      <div
        class="mt-2 text-center text-black/40 text-xs font-normal font-['PingFang_SC'] leading-none"
      >
        更换头像
      </div>
    </div>
    <button
      class="w-full p-0 leading-0 bg-transparent hover:bg-transparent after:b-none"
      @click="handleSetNickname"
    >
      <SectionHeading
        title="姓名"
        size="sm"
        :end-text="userInfo.nickname"
        :end-arrow="!isDesigner"
      ></SectionHeading>
    </button>
    <template v-if="isDesigner">
      <div @click="handleSetSex">
        <SectionHeading
          title="性别"
          size="sm"
          :end-text="{ '0': '男', '1': '女' }[String(userInfo.sex)] ?? '设置'"
          end-arrow
        ></SectionHeading>
      </div>
      <div class="relative" @click="birthdayShow = true">
        <SectionHeading
          title="生日"
          size="sm"
          :end-text="
            (userInfo.birthday ?? '') === ''
              ? '设置'
              : dayjs(userInfo.birthday).format('YYYY-MM-DD')
          "
          end-arrow
        ></SectionHeading>
      </div>
      <!-- <div class="absolute left-0 top-0 w-full h-full opacity-" style="visibility: hidden">
          <wd-datetime-picker type="date" v-model="birthday" custom-class=""></wd-datetime-picker>
        </div> -->
    </template>
    <SectionHeading
      title="手机号"
      size="sm"
      :end-text="userInfo?.mobile"
      :end-arrow="true"
      path="/pages/mine/setting/mobile/index"
    ></SectionHeading>
    <template v-if="isDesigner">
      <div @click="handleSetEmployer">
        <SectionHeading
          title="公司"
          size="sm"
          :end-text="userAuthInfo?.employer"
          end-arrow
        ></SectionHeading>
      </div>
      <SectionHeading title="推荐人" size="sm" :end-text="userAuthInfo?.referrer"></SectionHeading>
      <SectionHeading
        title="经纪人"
        size="sm"
        :end-text="userBasicInfo?.brokerName"
      ></SectionHeading>
    </template>
    <div class="flex-1"></div>
    <div><wd-button block :round="false" @click="handleLogout">退出登录</wd-button></div>
    <FormMessageBox v-model="formData" selector="nickname" :schema="schema"></FormMessageBox>
    <wd-action-sheet v-model="birthdayShow" title="设置生日">
      <!-- <view style="padding: 15px 15px 150px 15px"> -->
      <wd-datetime-picker-view
        type="date"
        v-model="birthday"
        :minDate="dayjs().subtract(80, 'y').toDate().getTime()"
        :maxDate="dayjs().toDate().getTime()"
        label="年月日"
      />
      <!-- </view> -->
      <div class="px-4 pb-4">
        <wd-button block :round="false" @click="handeleSetBirthday">确定</wd-button>
      </div>
    </wd-action-sheet>
  </div>
</template>
<style lang="scss">
.aaaa {
  &:after {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    content: '';
    background: #03f463;
    border-radius: 10px;
    transform: skewX(15deg);
  }
  &::before {
    position: absolute;
    top: 0;
    right: -13px;
    width: 100px;
    height: 64px;
    content: '';
    background: orange;
    border-radius: 10px;
  }
}
</style>
