<route lang="json">
{
  "style": {
    "navigationBarTitleText": "设计师认证",
    "navigationStyle": "custom"
  }
}
</route>
<script lang="ts" setup>
import Card from '@/components/card.vue'
import DataForm from '@/components/data-form.vue'
import NavBarEvo from '@/components/navbar-evo.vue'
import SectionHeading from '@/components/section-heading.vue'
import {
  createUserAuthInfo,
  getByDictType,
  getUserAuthInfo,
  updateUserAuthInfo,
  validateReferrerCode,
} from '../../../core/libs/requests'
import { DictType } from '../../../core/libs/models'
import { useUserStore } from '../../../store'
import pageHeaderFilter from '@designer-hub/assets/src/assets/svgs/pageHeaderFilter'
import { storeToRefs } from 'pinia'
import { useMessage, useToast } from 'wot-design-uni'
import { useRouter } from '../../../core/utils/router'
import { requestToast } from '../../../core/utils/common'
import { omit, pick } from 'radash'
import UploadEvo from '@/components/upload-evo.vue'
import { DataFormSchema } from '../../../components/data-form'
import { messages } from '../../../core/libs/messages'

const { alert } = useMessage()
const router = useRouter()
const userStore = useUserStore()
const { userInfo, isDesigner } = storeToRefs(userStore)
const { error } = useToast()
const formData = ref<any>({ mobile: userInfo.value?.mobile })
const attachment = ref()
const formInited = ref(false)
const uploadDisabled = ref(false)
const { data: userAuthInfo, run: setUserAuthInfo } = useRequest(() => getUserAuthInfo())
const schema = ref<DataFormSchema>({
  channelSource: {
    type: 'Select',
    label: '来源',
    labelWidth: 63,
    props: {
      placeholder: '请选择通过哪个渠道入驻的筑巢荟',
      columns: [],
      disabled: userAuthInfo.value != null,
      'onUpdate:modelValue': (value) => setReferrerExisting(value),
    },
  },
  referrer: {
    type: 'TextField',
    label: '推荐人',
    existing: true,
    labelWidth: 63,
    props: {
      placeholder: '请填写推荐人编号',
      disabled: false,
    },
  },
  designerName: {
    type: 'TextField',
    label: '姓名',
    labelWidth: 63,
    props: {
      placeholder: '请输入真实姓名',
    },
  },
  mobile: {
    type: 'TextField',
    label: '电话',
    labelWidth: 63,
    props: {
      placeholder: '请输入电话号码',
      disabled: true,
    },
  },
  employer: {
    type: 'TextField',
    label: '公司',
    labelWidth: 63,
    props: {
      placeholder: '请输入所在公司或自己公司名称',
    },
  },
  spatialExpertiseType: {
    type: 'Checkbox',
    label: '擅长空间类型',
    labelWidth: 84,
    props: {
      placeholder: ' ',
      columns: [],
    },
  },
})
const setReferrerExisting = (value: string) => {
  if (value === '4') {
    schema.value.referrer.existing = false
  } else {
    schema.value.referrer.existing = true
    schema.value.referrer.props.placeholder = {
      '1': '请填写渠道邀请码',
      '2': '请填写设计师会员号',
      '3': '请填写材料商名称',
    }[value]
  }
  formData.value.referrer = ''
}
const handleSubmit = async () => {
  console.log(formData.value)
  if (formData.value.channelSource && formData.value.channelSource !== '4' && !userAuthInfo.value) {
    if ((formData.value.referrer ?? '') === '') {
      uni.showToast({ title: messages.mine.authentication.referrerErrorText, icon: 'none' })
      return
    }
    const { data, code: status } = await requestToast(() =>
      validateReferrerCode({
        code: formData.value.referrer,
        channelSource: formData.value.channelSource,
      }),
    )
    if (data === false || status !== 0) {
      uni.showToast({ title: '推荐人编号不正确', icon: 'none' })
      return
    }
  }
  const body = {
    ...formData.value,
    spatialExpertiseType: formData.value.spatialExpertiseType?.join(','),
    attachment: attachment.value,
  }
  const rules = {
    channelSource: { required: true, message: messages.mine.authentication.channelSourceErrorText },
    // referrer: { required: true, message: messages.mine.authentication.referrerErrorText },
    designerName: { required: true, message: messages.mine.authentication.designerNameErrorText },
    employer: { required: true, message: messages.mine.authentication.employerErrorText },
    spatialExpertiseType: {
      required: true,
      message: messages.mine.authentication.spatialExpertiseTypeErrorText,
    },
    attachment: { required: true, message: messages.mine.authentication.attachmentErrorText },
  }
  // 校验上述字段
  const errors = Object.entries(rules)
    .filter(([key, value]) => (body[key] ?? '') === '')
    .map(([key, value]) => value.message)
  console.log(errors)
  if (errors.length > 0) {
    uni.showToast({ title: errors[0], icon: 'none' })
    return
  }

  if (!userAuthInfo.value) {
    console.log(3333)

    const { code, msg } = await createUserAuthInfo({
      gender: userInfo.value.sex,
      attachment: attachment.value,
      userId: userInfo.value.userId,
      ...formData.value,
      spatialExpertiseType: formData.value.spatialExpertiseType?.join(','),
    })
    if (code === 0) {
      router.replace(`/pages/mine/authentication/submit/success/index`)
    } else {
      error(msg)
    }
  } else {
    const toBeUpdate = {
      ...omit(formData.value, ['spatialExpertiseType']),
      spatialExpertiseType: formData.value.spatialExpertiseType?.join(','),
      attachment: attachment.value,
      id: userAuthInfo.value.id,
      gender: userInfo.value.sex,
    }
    const { code } = await requestToast(() => updateUserAuthInfo({ ...toBeUpdate, auditStatus: 1 }))
    if (code === 0) {
      router.replace(`/pages/mine/authentication/submit/success/index`)
    }
  }
}
onMounted(async () => {
  await setUserAuthInfo()
  if (userAuthInfo.value) {
    formData.value = {
      ...pick(userAuthInfo.value, [
        'channelSource',
        'referrer',
        'designerName',
        'designerName',
        'mobile',
        'employer',
      ]),
      channelSource: userAuthInfo.value.channelSource.toString(),
      spatialExpertiseType: userAuthInfo.value.spatialExpertiseType?.split(','),
    }
    setReferrerExisting(userAuthInfo.value.channelSource.toString())
    attachment.value = userAuthInfo.value.attachment
    // schema.value.channelSource.props.disabled = true
    // schema.value.referrer.props.disabled = true
  }
  const { data } = await getByDictType('member_channel_source')
  const { data: res } = await getByDictType(DictType.memberSpatialExpertiseType)
  console.log(res)
  schema.value.channelSource.props.columns = data
  schema.value.spatialExpertiseType.props.columns = res
  formInited.value = true
  if (userInfo.value.userAuthStatus === 1) {
    Object.entries(schema.value).forEach(([key]) => {
      schema.value[key].props.disabled = true
    })
    uploadDisabled.value = true
    alert({
      msg: '您的认证申请已提交，请耐心等待审核，审核通过后您将获得通知',
      title: '提示',
      confirmButtonText: '我知道了',
    })
  }
  if (userInfo.value.userAuthStatus === 2) {
    alert({
      title: '审核不通过',
      msg: userAuthInfo.value?.remark || '由于系统原因，您提交的认证暂时无法通过，请修改后重新提交',
    })
  }
})
defineExpose({})
</script>
<template>
  <div class="flex-grow">
    <div class="relative aspect-[3.6/1]">
      <div class="absolute top-0 left--1 right--1 bottom--18.5">
        <wd-img
          width="100%"
          height="100%"
          :src="'https://image.zhuchaohui.com/zhucaohui/21d6584cb711834f037a763855d05572433f776b308596d94aca97dd37e6cfa.png'"
        ></wd-img>
      </div>
      <div class="absolute top-0 left-0 right-0 bottom--18.5">
        <wd-img width="100%" height="100%" :src="pageHeaderFilter"></wd-img>
      </div>
    </div>
    <NavBarEvo transparent dark title="设计师认证"></NavBarEvo>
    <div class="flex-grow flex flex-col p-3.5 gap-3.5 relative">
      <Card>
        <SectionHeading size="base" title="基本信息" custom-class="mb-4"></SectionHeading>
        <template v-if="formInited">
          <DataForm v-model="formData" :schema="schema" direction="horizontal"></DataForm>
        </template>
      </Card>
      <Card>
        <SectionHeading
          size="base"
          title="上传附件"
          subtitle="请上传名片或者获奖信息凭证"
          custom-class="mb-4"
        ></SectionHeading>
        <div class="h-0.25 bg-[#e1e1e1] mb-5"></div>
        <!-- <wd-upload></wd-upload> -->
        <UploadEvo v-if="formInited" v-model="attachment" :disabled="uploadDisabled"></UploadEvo>
      </Card>
      <div class="flex-1"></div>
      <div>
        <wd-button
          v-if="!(isDesigner || String(userInfo.userAuthStatus) === '1')"
          block
          :round="false"
          :disabled="isDesigner || userInfo.userAuthStatus === 1"
          @click="handleSubmit"
        >
          提交
        </wd-button>
        <!-- <wd-button @click="handleSubmit">test</wd-button> -->
      </div>
    </div>
  </div>
</template>
