<template>
  <u-navbar title="个人资料" :autoBack="true" bgColor="#ffffff" placeholder safeAreaInsetTop :titleStyle="{ color: '#000' }"></u-navbar>
  <view class="info">
    <view style="background-color: #fff">
      <u-cell-group>
        <template v-for="(_, index) in mineinfo">
          <u-cell :title="_.title" :isLink="![1, 6].includes(index)">
            <!-- <u-cell :title="_.title" isLink> -->
            <template #value>
              <template v-if="_.type === 'jump'">
                <text class="info-text" @click="proxy.$h.jumpUrl(`${_.url}?flag=${_.flag}&title=${_.title}&isMyInfo=${_.isMyInfo}`)" :style="{ color: !['请选择', '暂无手机号'].includes(_.text) ? '#000' : '#999' }">{{ _.text }}</text>
              </template>
              <template v-if="_.type === 'selectData'">
                <text class="info-text" @click="showSelectSex = true" :style="{ color: _.text !== '请选择' ? '#000' : '#999' }">{{ _.text !== '请选择' ? proxy.$h.optObjectValue('sexData', _.text) : _.text }}</text>
              </template>
              <template v-if="_.type === 'upload'"><image @click="uploadAvatarHandler" class="info-avatar" :src="proxy.$h.downFile(_.imgUrl) || '/static/images/mAvatar.png'" mode="aspectFill" /></template>
              <template v-if="['input'].includes(_.type)"><up-input v-model="form[_.keyName]" :disabled="_.disabled" :placeholder="_.text" border="none" inputAlign="right" maxlength="11" disabledColor="#fff"></up-input></template>
            </template>
          </u-cell>
          <view class="grayLine" v-if="index === mineinfo.length - 2"></view>
        </template>
      </u-cell-group>
    </view>
    <view style="box-sizing: border-box; padding: 36rpx 30rpx">
      <view style="font-size: 15px; color: #303133; margin-bottom: 22rpx">个人介绍</view>
      <u-textarea v-model="form['introduction']" :placeholder="`介绍一下自己吧`" border="none" count maxlength="200"></u-textarea>
    </view>

    <view class="main">
      <view class="zhu" style="color: red">*注:昵称可输入1-12个字,一个月只能修改一次</view>
      <up-button color="#05B8D2" shape="circle" text="保存" throttleTime="1500" @click="confirmEditUserInfoHandler"></up-button>
    </view>
    <u-popup :show="showSelectSex" @close="showSelectSex = false" mode="bottom" round="16">
      <view v-for="(_, index) in sexList" :key="index" class="sexitem flexC" @click="selectSexHandler(_.value)">{{ _.title }}</view>
      <view class="grayline"></view>
      <view class="sexitem flexC" @click="showSelectSex = false">取消</view>
    </u-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, ComponentPublicInstance } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { useSelectDataStore } from '../../store/selectData'
import { getUserInfo, updateChange_userinfo, getDepartment } from '../../api'
import { sUserInfoType, ChangeUserInfoType, IndexListType } from '../../types'

const { proxy } = getCurrentInstance() as { proxy: ComponentPublicInstance }

const { SelectDepartmentList, SelectHospitalList } = storeToRefs(useSelectDataStore())

const mineinfo = ref([
  { keyName: 'avatar', title: '头像', text: '', type: 'upload', imgUrl: '' },
  { keyName: 'nickName', title: '昵称', text: '请输入昵称', type: 'input', disabled: false },
  { keyName: 'sex', title: '性别', text: '请选择', type: 'selectData' },
  { keyName: 'phone', title: '手机号', text: '暂无手机号', type: 'jump', url: '/pages2/mineinfo/phone' },
  { keyName: 'hospital', title: '坐诊医院', text: '请选择', type: 'jump', url: '/pages2/mineinfo/hospitalList', isMyInfo: 1, flag: 'ZUOZHENYIYUAN' },
  // { keyName: '', title: '标签', text: '请选择', type: 'jump', url: '/pages2/mineinfo/tag', flag: '' }, // 个人标签暂不可编辑
  { keyName: 'department', title: '科室', text: '请选择', type: 'jump', url: '/pages2/mineinfo/hospitalList', flag: 'KESHI' }
  // { keyName: 'introduction', title: '个人介绍', text: '介绍一下自己吧', type: 'textarea' }
])

const form = ref<{
  department?: { id: string; name: string }[]
  [property: string]: any
}>({
  nickName: '',
  introduction: '',
  department: [],
  hospital: ''
})

const showSelectSex = ref<boolean>(false)

const sexList = [
  { title: '男', value: 1 },
  { title: '女', value: 2 }
]

const textareaHeight = ref<number>(20)

const selectSexHandler = (value: number) => ((mineinfo.value[2].text = value + ''), (showSelectSex.value = false))

const uploadAvatarHandler = () => proxy.$h.upload('/sys/common/upload', (e: { upImg: string }) => (mineinfo.value[0].imgUrl = e.upImg))

const getInfoHandler = async () => {
  const { result }: { result: sUserInfoType } = await getUserInfo()

  const { result: departmentList }: { result: { records: IndexListType[] } } = await getDepartment({ keyword: '' })

  form.value.department = departmentList.records.flatMap(item => item.list).filter(item => result.department.includes(item.id))

  mineinfo.value[1].disabled = !Boolean(result?.isCanUpdateNickName)

  mineinfo.value[5].text = form.value.department.length ? form.value.department.map((_: { id: string; name: string }) => _.name).join() : '请选择'

  mineinfo.value[4].text = !['', null, undefined].includes(result.hospital) ? result.hospitalName : '请选择'

  form.value.hospital = result.hospitalId

  mineinfo.value[0].imgUrl = result.avatar

  mineinfo.value[2].text = result.sex + ''

  mineinfo.value[3].text = result.phone

  form.value.nickName = result.realname

  form.value.introduction = result.introduction
}

const linechangeHandler = e => {
  textareaHeight.value = e.detail.height
}

const confirmEditUserInfoHandler = async () => {
  await updateChange_userinfo({
    ...form.value,
    avatar: mineinfo.value[0].imgUrl as string,
    sex: Number(mineinfo.value[2].text),
    department: form.value.department?.map(_ => _.id),
    hospital: form.value.hospital
  } as ChangeUserInfoType)

  proxy.$h.timeCallBack('修改成功')
}

onLoad(() => {
  getInfoHandler()
})

onShow(() => {
  if (SelectDepartmentList.value.length > 0) {
    mineinfo.value[6].text = SelectDepartmentList.value.map((_: { id: string; name: string }) => _.name).join()

    form.value.department = SelectDepartmentList.value

    return
  }

  if (SelectHospitalList.value.length > 0) {
    mineinfo.value[4].text = SelectHospitalList.value.map((_: { id: string; name: string }) => _.name).join()

    form.value.hospital = SelectHospitalList.value[0].id

    return
  }
})
</script>

<style>
page {
  background: #f7f8fa !important;
}
</style>

<style lang="scss" scoped>
:deep(.u-line) {
  display: none !important;
}
:deep(.u-cell__body) {
  box-sizing: border-box;
  padding: 30rpx 30rpx;
  height: fit-content;
}
:deep(.u-textarea__field) {
  color: #000;
  font-size: 30rpx;
}
:deep(.uni-input-input) {
  font-size: 30rpx;
}
:deep(.u-textarea) {
  border-radius: 22rpx;
}
.main {
  box-sizing: border-box;
  padding: 0 24rpx;
  .zhu {
    margin: 20rpx 0 180rpx;
    font-size: 26rpx;
  }
}
.info {
  .sexitem {
    color: #333333;
    font-size: 34rpx;
    font-weight: 700;
    width: 100%;
    box-sizing: border-box;
    padding: 32rpx 0;
  }
  .grayline {
    width: 100%;
    height: 16rpx;
    background: #f2f2f2;
  }
  &-avatar {
    width: 124rpx;
    height: 124rpx;
    border-radius: 50%;
  }
  &-text {
    color: #999999;
    font-size: 30rpx;
    font-weight: 500;
  }
}
</style>