<route lang="json">
{
  "style": {
    "navigationBarTitleText": "个人信息",
    "navigationBarBackgroundColor": "#ffffff"
  }
}
</route>
<script setup lang="ts">
import {
  createAward,
  createFocus,
  deleteAward,
  deleteStylistFamily,
  getAwards,
  getDesignerActivities,
  getDesignerBasicInfo,
  getDesignerExtraEvents,
  getDesignerFamilyInfo,
  getSalesOrdersCounts,
  saveDesignerFamilyInfo,
  getUserInfoById,
  getEditRecords,
  updateDesignerFamilyInfo,
} from '../../../../core/libs/agent-requests'
import { addUnit } from 'wot-design-uni/components/common/util'
import { messages } from '../../../../core/libs/messages'
import { omit } from 'radash'
import BottomAppBar from '@/components/bottom-app-bar.vue'
import { renders } from '../../../../core/libs/renders'
import DataRender from '@/components/data-render.vue'
import PageHelperEvo from '@/components/page-helper-evo.vue'
import { DataFormSchema } from '../../../../components/data-form'
import { DesignerAward, DesignerFamilyInfo } from '@designer-hub/app/src/core/libs/models'
import DataForm from '@/components/data-form.vue'
import { requestToast } from '@designer-hub/app/src/core/utils/common'
import { ComponentExposed } from 'vue-component-type-helpers'
import ListHelperEvo from '@/components/list-helper-evo.vue'
import SectionHeading from '@designer-hub/app/src/components/section-heading.vue'
import dayjs from 'dayjs'

const tab = ref('basic')
// 基础信息 家庭信息 奖项信息 销售信息 游学/活动信息
const tabs = [
  { label: '基础信息', value: 'basic' },
  { label: '家庭信息', value: 'family' },
  { label: '奖项信息', value: 'award' },
  { label: '销售信息', value: 'sale' },
  { label: '游学/活动信息', value: 'activity' },
  { label: '修改记录', value: 'record' },
  // { label: '其他活动信息', value: 'events' },
]
const id = ref()
const { data: basicData, run: setBasicData } = useRequest(() => getDesignerBasicInfo(id.value))
const { data: familyData, run: setData } = useRequest(() => getUserInfoById(id.value))
const { data: editData, run: setEditData } = useRequest(() => getEditRecords())
const query = computed(() => ({ userId: id.value }))
const eventsQuery = computed(() => ({ type: '3' }))
const recordQuery = computed(() => ({ pageNo: 1, pageSize: 10 }))
const actionSheetStatus = ref(false)
const schema = ref<DataFormSchema>()
const fileList = ref<any[]>([])
const formData = ref({
  focus: '',
  awardsFileUrl: '',
})
const formDataFoucs = ref<{
  focus: string
}>({
  focus: '',
})
const submitType = ref<'family' | 'award' | 'updateFamily'>()
const familyPageRef = ref<ComponentExposed<typeof PageHelperEvo>>()
const awardsListRef = ref<ComponentExposed<typeof ListHelperEvo>>()
const saleListRef = ref<ComponentExposed<typeof ListHelperEvo>>()
const activityListRef = ref<ComponentExposed<typeof ListHelperEvo>>()
const getFormDataFoucs = computed(() => familyData.value?.focus)
// const {} = useRequest()
const handleEditBasicInfo = async () => {
  await uni.navigateTo({ url: `/pages/agent/designer/archives/basic-info/index?id=${id.value}` })
}
const handleAddFamilyInfo = async (item: DesignerFamilyInfo) => {
  submitType.value = 'family'
  const familySchema: DataFormSchema<Omit<DesignerFamilyInfo, 'userId' | 'createTime' | 'id'>> = {
    familyRelation: {
      type: 'TextField',
      label: messages.objects.designerFamilyInfo.familyRelation,
      props: {
        placeholder: `请输入${messages.objects.designerFamilyInfo.familyRelation}`,
      },
    },
    familyName: {
      type: 'TextField',
      label: messages.objects.designerFamilyInfo.familyName,
      props: {
        placeholder: `请输入${messages.objects.designerFamilyInfo.familyName}`,
      },
    },
    familySex: {
      type: 'Radio',
      label: messages.objects.designerFamilyInfo.familySex,
      props: {
        columns: [
         { label: '未知', value: 0 },
         { label: '男', value: 1 },
         { label: '女', value: 2 },
        ],
      },
    },
    familyBirthday: {
      type: 'TimePick',
      label: messages.objects.designerFamilyInfo.familyBirthday,
      props: {
        type: 'date',
        placeholder: `请选择${messages.objects.designerFamilyInfo.familyBirthday}`,
        minDate: new Date('1925-01-01').getTime(),
        // defaultVale: new Date('1990-01-01').getTime(),
      },
    },
    familyInterset: {
      type: 'TextField',
      label: messages.objects.designerFamilyInfo.familyInterset,
      props: {
        placeholder: `请输入${messages.objects.designerFamilyInfo.familyInterset}`,
      },
    },
    familyOccupation: {
      type: 'TextField',
      label: messages.objects.designerFamilyInfo.familyOccupation,
      props: {
        placeholder: `请输入${messages.objects.designerFamilyInfo.familyOccupation}`,
      },
    },
  }

  schema.value = familySchema
  actionSheetStatus.value = true
}
const action = ref(`${import.meta.env.VITE_SERVER_BASEURL}/app-api/infra/file/upload`)
const handleUploadChange = ({ fileList }) => {
  formData.value.awardsFileUrl = fileList
    .map((item: any) => {
      if (item.response) {
        return JSON.parse(item.response).data
      } else {
        return item.url
      }
    })
    .join(',')
}
const handleAddAward = async () => {
  submitType.value = 'award'
  fileList.value = []
  schema.value = {
    awardsName: {
      type: 'TextField',
      label: messages.objects.designerAward.awardsName,
      props: {
        placeholder: messages.objects.designerAward.awardsNamePlaceHolder,
      },
    },
    awardsRank: {
      type: 'TextField',
      label: messages.objects.designerAward.awardsRank,
      props: {
        placeholder: messages.objects.designerAward.awardsRankPlaceHolder,
      },
    },
    awardsTime: {
      type: 'TimePick',
      label: messages.objects.designerAward.awardsTime,
      props: {
        defaultValue: dayjs().toDate(),
        placeholder: messages.objects.designerAward.awardsTimePlaceHolder,
        type: 'date',
      },
    },
    // awardsFileUrl: {
    //   type: 'ImageUploader',
    //   label: messages.objects.designerAward.awardsFileUrl,
    //   callback: handleUploadChange,
    // },
  }
  actionSheetStatus.value = true
}
const handleSubmit = async () => {
  switch (submitType.value) {
    case 'family': {
      const { code } = await requestToast(
        () => saveDesignerFamilyInfo({ ...formData.value, userId: id.value }),
        {
          success: true,
          successTitle: '保存成功',
        },
      )
      if (code === 0) {
        actionSheetStatus.value = false
        familyPageRef.value?.reload()
      }
      break
    }
    case 'updateFamily': {
      const { code } = await requestToast(
        () => updateDesignerFamilyInfo({ ...formData.value, userId: id.value }),
        {
          success: true,
          successTitle: '修改成功',
        },
      )
      if (code === 0) {
        actionSheetStatus.value = false
        familyPageRef.value?.reload()
      }
      break
    }
    case 'award':
      {
        const { code } = await requestToast(
          () => createAward({ ...formData.value, userId: Number(id.value) }),
          {
            success: true,
            successTitle: '保存成功',
          },
        )
        if (code === 0) {
          actionSheetStatus.value = false
          formData.value = {}
          awardsListRef.value?.reload()
        }
      }
      break
    default:
      break
  }
}
const handleDeleteAward = async (item: DesignerAward) => {
  await requestToast(() => deleteAward(item.id), {
    success: true,
    successTitle: '删除成功',
  })
  awardsListRef.value?.reload()
}
const handleDeleteFamilyInfo = async (item: DesignerFamilyInfo) => {
  await requestToast(() => deleteStylistFamily(item.id), {
    success: true,
    successTitle: '删除成功',
  })
  familyPageRef.value?.reload()
}
const handleUpdateFamily = (item) => {
  submitType.value = 'updateFamily'
  const familySchema: DataFormSchema<Omit<DesignerFamilyInfo, 'userId' | 'createTime' | 'id'>> = {
    familyRelation: {
      type: 'TextField',
      label: messages.objects.designerFamilyInfo.familyRelation,
      props: {
        placeholder: `请输入${messages.objects.designerFamilyInfo.familyRelation}`,
      },
    },
    familyName: {
      type: 'TextField',
      label: messages.objects.designerFamilyInfo.familyName,
      props: {
        placeholder: `请输入${messages.objects.designerFamilyInfo.familyName}`,
      },
    },
    familySex: {
      type: 'Radio',
      label: messages.objects.designerFamilyInfo.familySex,
      props: {
        columns: [
          { label: '男', value: 1 },
          { label: '女', value: 2 },
          { label: '未知', value: 0 },
        ],
      },
    },
    familyBirthday: {
      type: 'TimePick',
      label: messages.objects.designerFamilyInfo.familyBirthday,
      props: {
        type: 'date',
        placeholder: `请选择${messages.objects.designerFamilyInfo.familyBirthday}`,
        minDate: new Date('1925-01-01').getTime(),
        // defaultVale: new Date('1990-01-01').getTime(),
      },
    },
    familyInterset: {
      type: 'TextField',
      label: messages.objects.designerFamilyInfo.familyInterset,
      props: {
        placeholder: `请输入${messages.objects.designerFamilyInfo.familyInterset}`,
      },
    },
    familyOccupation: {
      type: 'TextField',
      label: messages.objects.designerFamilyInfo.familyOccupation,
      props: {
        placeholder: `请输入${messages.objects.designerFamilyInfo.familyOccupation}`,
      },
    },
  }
  formData.value = item
  schema.value = familySchema
  actionSheetStatus.value = true
}
const handleSubmitFocus = async () => {
  await requestToast(() => createFocus({ ...formDataFoucs.value, userId: id.value }), {
    success: true,
    successTitle: '保存成功',
  })
  await setData()
  formDataFoucs.value.focus = familyData.value?.focus as any
}
onLoad(async (query?: Record<string | 'id', any>) => {
  id.value = query?.id
  await setData()
  formDataFoucs.value.focus = familyData.value?.focus as any
})
onShow(async () => {
  switch (tab.value) {
    case 'basic':
      await setBasicData()
      break
    case 'sale':
      await saleListRef.value?.reload()
      break
    case 'activity':
      await activityListRef.value?.reload()
      break
    case 'record':
      await setEditData()
      break
    default:
      break
  }
  await setBasicData()
})
</script>
<template>
  <div class="flex-grow flex flex-col">
    <div class="mx--3.5 fixed left-4 w-full bg-white z-10">
      <wd-tabs v-model="tab" :swipeable="true" :slidable-num="4">
        <template v-for="(it, index) in tabs" :key="index">
          <wd-tab :title="it.label" :name="it.value"></wd-tab>
        </template>
      </wd-tabs>
    </div>
    <div class="flex flex-col flex-grow gap-5 mt-3">
      <template v-if="tab === 'basic'">
        <div class="bg-white mt-4 flex flex-col gap-5 p-4">
          <template
            v-for="([key, value], index) in Object.entries(
              omit(basicData, [
                'id',
                'userId',
                'maritalStatus',
                'imageNumber',
                'createTime',
                'referrerId',
              ]),
            )"
            :key="index"
          >
            <div class="flex items-center justify-between">
              <div class="text-black/40 text-base font-normal font-['PingFang_SC'] leading-none">
                {{ (messages.objects?.designerBasiceInfo as any)[key] }}
              </div>
              <template v-if="key === 'avatar'">
                <DataRender v-bind="{ type: 'Avatar', value: value }"></DataRender>
              </template>
              <template
                v-else-if="
                  key === 'birthday' ||
                  key === 'cooperationTime' ||
                  key === 'createTime' ||
                  key === 'joinTime'
                "
              >
                <DataRender v-bind="{ type: 'Date', value: value }"></DataRender>
              </template>
              <template v-else-if="key === 'sex'">
                <DataRender
                  v-bind="{
                    type: 'Select',
                    value: value,
                    options: [
					  { label: '未知', value: 0 },
                      { label: '男', value: 1 },
                      { label: '女', value: 2 },
                    ],
                  }"
                ></DataRender>
              </template>
              <template v-else-if="key === 'retryStatus'">
                <DataRender
                  v-bind="{
                    type: 'Select',
                    value: value,
                    options: [
                      { label: '弱绑定', value: 0 },
                      { label: '强绑定', value: 1 },
                      { label: '公开', value: 3 },
                    ],
                  }"
                ></DataRender>
              </template>
              <!-- <template v-else-if="key === 'imageUrl'">
                <DataRender
                  v-bind="{
                    type: 'img',
                    value: value,
                  }"
                ></DataRender>
              </template> -->
              <template v-else-if="key === 'retryStatus'">
                <DataRender
                  v-bind="{
                    type: 'Select',
                    value: value,
                    options: [
                      { label: '弱绑定', value: 0 },
                      { label: '强绑定', value: 1 },
                      { label: '公开', value: 3 },
                    ],
                  }"
                ></DataRender>
              </template>
              <template v-else-if="key === 'sharingIntent'">
                <DataRender
                  v-bind="{
                    type: 'Select',
                    value: value,
                    options: [
                      { label: '不愿意', value: 3 },
                      { label: '一般', value: 1 },
                      { label: '愿意', value: 2 },
                      { label: '非常愿意', value: 4 },
                    ],
                  }"
                ></DataRender>
              </template>
              <template v-else-if="key === 'imageUrl'">
                <SectionHeading
                  :end-text="`${basicData.imageNumber}张`"
                  end-arrow
                  :path="`/pages/agent/designer/archives/award/imgs?id=${id ?? ''}`"
                ></SectionHeading>
              </template>

              <template v-else>
                <DataRender v-bind="{ type: 'Original', value: value }"></DataRender>
              </template>
            </div>
            <!-- <SectionHeading size="base" :title="messages.objects.designerBasiceInfo[key]">
          <template #append>
            <DataRender v-bind="renders.designerBasiceInfo[key](value)"></DataRender>
          </template>
        </SectionHeading> -->
            <div class="w-full h-.25 bg-[#f4f4f4]"></div>
          </template>
        </div>
      </template>
      <template v-if="tab === 'family'">
        <div class="bg-white p-4 mt-4 flex-grow flex flex-col">
          <div class="flex items-center justify-between">
            <div>家庭信息</div>
            <div>
              <wd-button type="text" icon="add-circle1" @click="handleAddFamilyInfo">
                添加家庭信息
              </wd-button>
            </div>
          </div>
          <ListHelperEvo ref="familyPageRef" :request="getDesignerFamilyInfo" :query="query">
            <template #list="{ list }">
              <template v-for="(item, index) in list" :key="index">
                <div class="flex flex-col gap-4 py-4">
                  <SectionHeading
                    title="关系"
                    size="base"
                    :end-text="item.familyRelation"
                  ></SectionHeading>
                  <SectionHeading
                    title="姓名"
                    size="base"
                    :end-text="item.familyName"
                  ></SectionHeading>
                  <SectionHeading
                    title="性别"
                    size="base"
                    :end-text="item.familySexStr"
                  ></SectionHeading>
                  <SectionHeading
                    title="生日"
                    size="base"
                    :end-text="
                      item.familyBirthday && dayjs(item.familyBirthday).format('YYYY-MM-DD')
                    "
                  ></SectionHeading>
                  <SectionHeading
                    title="爱好"
                    size="base"
                    :end-text="item.familyInterset"
                  ></SectionHeading>
                  <SectionHeading
                    title="职业"
                    size="base"
                    :end-text="item.familyOccupation"
                  ></SectionHeading>
                  <div style="display: flex">
                    <wd-button type="text" @click="handleUpdateFamily(item)">编辑</wd-button>
                    <wd-button type="text" @click="handleDeleteFamilyInfo(item)">删除</wd-button>
                  </div>
                  <div v-if="!(index === list.length - 1)" class="w-full h-1 bg-[#dadada]"></div>
                </div>
              </template>
            </template>
          </ListHelperEvo>
          <!--          <PageHelperEvo ref="familyPageRef" :request="getDesignerFamilyInfo" :query="query">-->
          <!--            -->
          <!--          </PageHelperEvo>-->
        </div>
      </template>
      <template v-if="tab === 'award'">
        <div class="bg-white p-4 mt-4 flex-grow flex flex-col">
          <div class="flex items-center justify-between">
            <div>奖项信息</div>
            <div>
              <wd-button type="text" icon="add-circle1" @click="handleAddAward">
                添加获奖信息
              </wd-button>
            </div>
          </div>
          <ListHelperEvo ref="awardsListRef" :request="getAwards" :query="{ userId: id }">
            <template #list="{ list }">
              <template v-for="(item, i) in list" :key="i">
                <div class="flex flex-col gap-4 py-4">
                  <SectionHeading
                    title="奖项名称"
                    size="base"
                    :end-text="item.awardsName"
                  ></SectionHeading>
                  <SectionHeading
                    title="奖项日期"
                    :end-text="item.awardsTime && dayjs(item.awardsTime).format('YYYY-MM-DD')"
                  ></SectionHeading>
                  <SectionHeading title="奖项名次" :end-text="item.awardsRank"></SectionHeading>
                  <SectionHeading
                    title="奖项照片"
                    end-arrow
                    :path="`/pages/agent/designer/archives/award/photos/index?urls=${item.awardsFileUrl ?? ''}`"
                  ></SectionHeading>
                  <wd-button type="text" @click="handleDeleteAward(item)">删除</wd-button>
                  <div v-if="!isLast" class="w-full h-1 bg-[#dadada]"></div>
                </div>
              </template>
            </template>
          </ListHelperEvo>
        </div>
      </template>

      <template v-if="tab === 'sale'">
        <div class="bg-white p-4 mt-4 flex-grow flex flex-col">
          <div class="flex items-center justify-between">
            <div>销售信息</div>
          </div>
          <ListHelperEvo ref="saleListRef" :request="getSalesOrdersCounts" :query="{ userId: id }">
            <template #list="{ list }">
              <template v-for="(item, index) in list" :key="index">
                <div class="flex flex-col gap-4 py-4">
                  <div v-if="index === list.length - 1" class="w-full h-1 bg-[#dadada]"></div>
                  <SectionHeading
                    :title="item.label"
                    size="base"
                    :end-text="index !== list.length - 2 ?String(item.value):''"
                    end-arrow
                    :path="
                      !(index === list.length - 1)
                        ? !(index === list.length - 2)
						?`/pages/agent/designer/archives/sale-info/index?id=${id}&type=${item.type}`
						:`/pages/agent/designer/archives/sale-info/history?data=${item.value}`
                        : `/pages/agent/designer/archives/sale-info/others/index?id=${id}`
                    "
                  ></SectionHeading>
                </div>
              </template>
            </template>
          </ListHelperEvo>
        </div>
      </template>
      <template v-if="tab === 'activity'">
        <div class="bg-white p-4 mt-4 flex-grow flex flex-col">
          <SectionHeading title="游学/活动信息"></SectionHeading>
          <ListHelperEvo
            ref="activityListRef"
            :request="getDesignerActivities"
            :query="{ userId: id }"
          >
            <template #list="{ list }">
              <template v-for="(item, index) in list" :key="index">
                <div class="">
                  <template v-if="item.type === 'line'">
                    <div class="w-full h-1 bg-[#dadada]"></div>
                  </template>
                  <template v-else>
                    <div class="py-4">
                      <SectionHeading
                        :title="item.label"
                        :end-text="index !== list.length - 2?`${item.value}次`:''"
                        :path="
                          index === list.length - 1
                            ? `/pages/agent/designer/archives/activity/others/index?id=${id}`
                            : index === list.length - 2
							?`/pages/agent/designer/archives/activity/history?data=${item.value}`
							:item.value > 0
                              ? `/pages/agent/designer/archives/activity/index?userId=${id}&type=${item.type}&subType=${item.subType}`
                              : ''
                        "
                      ></SectionHeading>
                    </div>
                  </template>
                  <div v-if="!(index === list.length - 1)" class="w-full h-.25 bg-[#f4f4f4]"></div>
                </div>
              </template>
            </template>
          </ListHelperEvo>
          <SectionHeading title="游学/活动关注点">
            <template #append>
              <wd-button type="text" @click="handleSubmitFocus">保存</wd-button>
            </template>
          </SectionHeading>
          <DataForm
            v-model="formDataFoucs"
            :schema="{ focus: { type: 'Textarea', hiddenLabel: true } }"
          ></DataForm>
        </div>
      </template>
      <template v-if="tab === 'events'">
        <PageHelperEvo :request="getDesignerExtraEvents" :query="eventsQuery">
          <template #default="{ source }">
            <template v-for="(it, index) in source?.list" :key="index">
              <div>{{ it }}</div>
            </template>
          </template>
        </PageHelperEvo>
      </template>
      <template v-if="tab === 'record'">
        <div class="bg-white p-4 mt-4 flex-grow flex flex-col">
          <SectionHeading title="修改记录"></SectionHeading>
          <PageHelperEvo :request="getEditRecords" :query="query">
            <template #default="{ source }">
              <template v-for="(it, index) in source?.list" :key="index">
                <div class="record">
                  <div class="record-time">
                    <div class="time">{{ dayjs(it.createTime).format('YYYY-MM-DD') }}</div>
                    <div class="createBy">经纪人：{{ it.createName }}</div>
                  </div>
                  <div class="record-title">修改信息：</div>
                  <div class="record-content">{{ it.content }}</div>
                </div>
              </template>
            </template>
          </PageHelperEvo>
        </div>
      </template>
    </div>
    <BottomAppBar fixed placeholder>
      <wd-button v-if="tab === 'basic'" block :round="false" @click="handleEditBasicInfo">
        编辑
      </wd-button>
      <wd-button v-if="tab === 'family'" block :round="false" @click="handleAddFamilyInfo">
        新增
      </wd-button>
    </BottomAppBar>
    <wd-action-sheet v-model="actionSheetStatus">
      <div class="p-4">
        <DataForm :schema="schema" :direction="'horizontal'" v-model="formData"></DataForm>
        <template v-if="submitType == 'award'">
          <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">
              附件
            </label>
            <wd-upload
              :file-list="fileList"
              image-mode="aspectFill"
              :action="action"
              @change="handleUploadChange"
            ></wd-upload>
          </div>
        </template>
        <wd-button :round="false" block @click="handleSubmit">提交</wd-button>
      </div>
    </wd-action-sheet>
  </div>
</template>
<style lang="scss" scoped>
.record {
  padding: 60rpx 0;
  border-bottom: 2rpx solid #f5f5f5;
  .record-time {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.45);
  }
  .record-title {
    margin-bottom: 14rpx;
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.45);
  }
  .record-content {
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.85);
  }
}
::v-deep .wd-radio__label {
  line-height: 30px !important;
}
</style>
