<script setup lang='ts'>
import user from '~/store/user';
import { showSuccessToast, showFailToast } from 'vant';
import { REQUEST } from '~/utils/request'
import { resolveFileString } from '~/utils/helper'

const router = useRouter()
function onClickLeft() {
  router.back()
}

// 参数1为一个对象，返回一个新对象，新对象的属性值为原对象中属性值以参数2开头的属性
const filterObj = (obj: { [x: string]: any; }, prefix: string) => {
  const newObj: { [x: string]: any; } = {}
  for (const key in obj) {
    if (key.startsWith(prefix)) {
      if (key === 'dxp_pjxj') {
        newObj[key] = obj[key] * 1
        continue
      }
      if (key === 'dxp_user_avatar') {
        newObj[key] = obj[key] !== '' ? [{ url: obj[key] }] : []
        continue
      }
      if (key === 'dxp_wx_qrcode') {
        newObj[key] = obj[key] !== '' ? [{ url: obj[key] }] : []
        continue
      }
      newObj[key] = obj[key]
    }
  }
  return newObj
}

const form = reactive(filterObj((await request({
  url: '/dyaw/xlfw_pbgl/detail',
  data: {
    user_id: user.user_id
  }
}))?.data?.one_info, 'dxp_'))
console.log('form : ', form)

let readonly = $ref(true)
const FormRef = $ref()

async function onClickRight() {
  if (!readonly) {
    try {
      await FormRef?.validate()
    } catch (error) {
      showFailToast('校验未通过')
      return
    }

    await request({
      url: '/dyaw/xlfw_pbgl/edit',
      data: {
        dxp_id: form.dxp_id,
        dyaw_xlfw_pbgl: Object.assign({}, form, {
          dxp_user_avatar: form.dxp_user_avatar[0]?.url,
          dxp_wx_qrcode: form.dxp_wx_qrcode[0]?.url,
          dxp_keyowrd: undefined,
          dxp_bzxcs: undefined,
          dxp_pjxj: undefined,
          dxp_jdsc: undefined,
        })
      }
    }).then(res => {
      if (res.code === '1') {
        showSuccessToast('保存成功')
      } else {
        showFailToast(res.msg)
      }
    }).catch(err => {
      showFailToast(`error: ${err}`)
    })
  }
  readonly = !readonly

}

const handleAfterRead = (fileProxy) => {
  fileProxy.status = 'uploading'
  fileProxy.message = '上传中...'
  const { file } = fileProxy
  REQUEST.upload({
    url: '/upload/main/file',
    data: { filedata: file },
  }).then((res) => {
    console.log('res :>> ', res)
    if (res.code === '1') {
      // fileList.value.push(res.data)
      fileProxy.url = `${window.GLOBAL_CONFIG.oss}/${res.data.url}`
      fileProxy.res = {
        name: res.data.file_name,
        url: fileProxy.url,
        origin: res.data.url,
      }
      fileProxy.status = 'done'
      fileProxy.message = ''

      // emits('update:part', fileList.map((item) => item.res.name + ',' + item.res.url).join(';'))
      // emits('update:part', fileList.map((item) => item.res.name + ',' + item.res.url).join(';'))
      // emits('update:modelValue', fileList.map(item => `${item.res.name},${item.res.origin}`).join(';'))
      // emits('update:modelValue', fileList.map(item => `${item.res.origin}`).join(';'))
    }
    else {
      fileProxy.status = 'failed'
      fileProxy.message = '上传失败'
    }
  }).catch((err) => {
    console.error(err)
  })
}
</script>

<template>
  <div>
    <van-nav-bar title="个人中心" left-text="" left-arrow @click-left="onClickLeft"
      style="--van-nav-bar-background:#397FF6;--van-nav-bar-icon-color:#fff;--van-nav-bar-title-text-color:#fff;--van-nav-bar-title-font-size:18px;--van-nav-bar-text-color:#fff;"
      :right-text="readonly ? '编辑' : '保存'" @click-right="onClickRight" />

    <van-form :readonly="readonly" ref="FormRef">
      <van-cell-group>
        <van-field name="头像" label="头像">
          <template #input>
            <van-uploader :readonly="readonly" :deletable="!readonly" v-model="form.dxp_user_avatar"
              :after-read="handleAfterRead" :max-count="1" />
          </template>
        </van-field>
        <van-field v-model="form.dxp_user_name" name="账号" label="账号" :rules="[{ required: true, message: '请填写账号' }]" />
        <van-field v-model="form.dxp_user_realname" name="姓名" label="姓名"
          :rules="[{ required: true, message: '请填写姓名' }]" />
        <van-field v-model="form.dxp_user_phone" name="联系电话" label="联系电话"
          :rules="[{ required: true, message: '请填写正确的联系电话', pattern: /^1[3456789]\d{9}$/ }]" />
        <van-field name="微信二维码" label="微信二维码">
          <template #input>
            <van-uploader :readonly="readonly" :deletable="!readonly" v-model="form.dxp_wx_qrcode"
              :after-read="handleAfterRead" :max-count="1" />
          </template>
        </van-field>
        <van-field v-model="form.dxp_bzxcs" name="被咨询次数" label="被咨询次数" readonly :disabled="!readonly" />
        <van-field v-model="form.dxp_jdsc" name="接待时长" label="接待时长" readonly :disabled="!readonly" />
        <van-field name="平均星级" label="平均星级" readonly :disabled="!readonly">
          <template #input>
            <van-rate v-model="form.dxp_pjxj" readonly />
          </template>
        </van-field>
        <van-field v-model="form.dxp_jj" name="简介" label="简介" rows="2" autosize type="textarea" />
      </van-cell-group>
    </van-form>
  </div>
</template>
