<template>
  <full-page :customScroll="empty">
    <template #header>
      <view class="flex items-center bg-white text-base px-15 py-12">
        <view class="flex-shrink-0 mr-5 text-gray">档案所属人</view>
        <view class="text-dark">{{ name }}</view>
      </view>
      <view class="flex items-center py-12 px-15">
        <view class="min-w-90 flex items-center bg-white rounded-sm px-10 mr-5" @click="selectType()">
          <view class="leading-normal text-base py-5 px-10 text-dark mr-5">
            {{ tempType[type] || '全部' }}
          </view>
          <uni-icons type="down" size="16" color="#666" />
        </view>
        <view class="w-100 flex items-center bg-white rounded-sm mr-5">
          <uni-datetime-picker v-model="dates" type="daterange">
            <view class="flex items-center rounded-sm mr-5 px-10 bg-white">
              <view class="flex-grow w-0 text-dark truncate leading-normal text-base py-5 mr-5">
                {{ dates.length ? dates.join(' ~ ') : '时间筛选' }}
              </view>
              <uni-icons type="down" size="16" color="#666" />
            </view>
          </uni-datetime-picker>
        </view>
        <view class="flex-grow"></view>
      </view>
    </template>
    <view v-if="list.length === 0" class="flex items-center justify-center h-full">
      <empty-data />
    </view>
    <view v-else class="px-15 pb-15">
      <!-- v-for="customer in list" :key="customer._id" -->
      <view v-for="i in list" :key="i._id" class="bg-white rounded shadow-lg mb-10"
        @click="toRecord(i.medicalType, i._id)">
        <view class="flex items-center py-12 px-15">
          <view class="text-lg font-semibold text-dark mr-5">
            {{ i.date }}
          </view>
          <view v-if="i.medicalType === 'outpatient'"
            class="mr-5 px-10 leading-normal text-white text-base bg-warning rounded-full">门诊信息</view>
          <view v-else-if="i.medicalType === 'inhospital'"
            class="mr-5 px-10 leading-normal text-white text-base bg-success rounded-full">住院信息</view>
          <view v-if="i.corp === '其他'" class="px-10 leading-normal text-white text-base bg-danger rounded-full">
            外院
          </view>
          <view class="flex-grow"></view>
          <view class="flex items-center text-base text-primary">
            <view class="mr-5">查看详情</view>
            <uni-icons type="right" :size="14" color="#0074ff" />
          </view>
        </view>
        <view v-if="i.rows.length" class="px-15 border-b">
          <view v-for="row in i.rows" :key="row.key" class="flex leading-normal mb-10">
            <view class="flex-shrink-0 mr-5 w-90 text-base text-gray">{{ row.label }}：</view>
            <view v-if="row.title === 'diagnosisName'" class="w-0 flex-grow text-base text-dark">
              {{ row.value && row.value.join ? row.value.join(', ') : '' }}
            </view>
            <view v-else-if="row.title === 'files'" class="w-0 flex-grow text-base text-dark">
              <view v-if="row.value && row.value.length" class="w-full flex flex-wrap">
                <image v-for="file in row.value" :src="file.url" class="file-icon" @click.stop="preview(file)" />
              </view>
            </view>
            <view v-else class="w-0 flex-grow text-base text-dark">
              {{ row.value }}
            </view>
          </view>
          <!-- <view class="flex leading-normal mb-10">
            <view class="flex-shrink-0 mr-5 w-90 text-base text-gray">临床诊断：</view>
            <view class="w-0 flex-grow text-base text-dark">龋齿</view>
          </view>
          <view class="flex leading-normal mb-10">
            <view class="flex-shrink-0 mr-5 w-90 text-base text-gray">临床诊断：</view>
            <view class="w-0 flex-grow text-base text-dark">龋齿</view>
          </view> -->
        </view>
        <view v-if="i.dataSource === 'customerReport'" class="px-15 py-12 text-base text-dark">
          记录时间：{{ i.createTime }} 记录人：自己
        </view>
      </view>
    </view>
    <template #footer>
      <button-footer v-if="healthTempList.length" confirmText="+新增健康档案" :showCancel="false" @confirm="addArchive()" />
    </template>
  </full-page>
</template>
<script setup>
import { computed, ref, watch } from 'vue';
import dayjs from 'dayjs';
import useGuard from '@/hooks/useGuard';
import api from '@/utils/api';

import ButtonFooter from '@/components/button-footer.vue';
import EmptyData from '@/components/empty-data.vue';
import FullPage from '@/components/full-page.vue';
import { toast } from '../../utils/widget';

const tempType = {
  outpatient: '门诊信息',
  inhospital: '住院信息'
}
const empty = ref(false)
const { useLoad, useShow } = useGuard();
const corpId = ref('');
const customerId = ref('');
const dates = ref([])
const list = ref([]);
const name = ref('');
const team = ref(null);
const type = ref('all');
const teamId = ref('');
const page = ref(1);
const more = ref(false)
const loading = ref(false);
const qrcode = computed(() => team.value && Array.isArray(team.value.qrcodes) ? team.value.qrcodes[0] : null)
const healthTempList = computed(() => qrcode.value && Array.isArray(qrcode.value.healthTempList) ? qrcode.value.healthTempList.map(i => ({ label: tempType[i.templateType], value: i.templateType })).filter(i => i.label) : [])
const tempShowField = ref(null);

const config = {
  outpatient: ["corp", "deptName", "doctor", "diagnosisName", "files"],
  inhospital: ["corp", "diagnosisName", "operation", "operationDate", "outhosDate", "files"],
};

function addArchive() {
  if (healthTempList.value.length > 1) {
    uni.showActionSheet({
      title: '选择新增档案类型',
      itemList: healthTempList.value.map(i => i.label),
      success: function (res) {
        toRecord(healthTempList.value[res.tapIndex].value)
      }
    });
  } else {
    toRecord(healthTempList.value[0].value)
  }
}

function getTempRows(type, data) {
  if (config[type] && tempShowField.value && tempShowField.value[type]) {
    const list = [];
    let titles = config[type];
    if (data.corp === '其他') {
      titles = ['corpName', 'diagnosisName', 'files']
    }
    titles.forEach(i => {
      if (tempShowField.value[type][i]) {
        list.push({ title: i, label: tempShowField.value[type][i], value: data[i], key: `${i}_${data._id}` })
      }
    })
    return list;
  }
  return []
}

function toRecord(type, id = '') {
  uni.navigateTo({
    url: `/pages/health/record?type=${type}&teamId=${teamId.value}&corpId=${corpId.value}&id=${id}&customerId=${customerId.value}`
  })
}

function preview(file) {
  if (/image/i.test(file.type)) {
    uni.previewImage({
      urls: [file.url]
    })
  }
}

function selectType() {
  const itemList = [{ label: '全部', value: 'all' }, ...healthTempList.value]
  uni.showActionSheet({
    title: '选择新增档案类型',
    itemList: itemList.map(i => i.label),
    success: function (res) {
      type.value = itemList[res.tapIndex].value;
      page.value = 1;
      getList()
    }
  });
}

async function getTeam() {
  const res = await api('getTeamData', { teamId: teamId.value, corpId: corpId.value });
  if (res && res.data) {
    team.value = res.data;
  } else {
    toast(res?.message || '获取团队信息失败')
  }
}

async function getList() {
  if (!tempShowField.value) {
    await getTeamHealthTemps()
  }
  if (loading.value) return;
  const params = {
    corpId: corpId.value,
    memberId: customerId.value,
    page: page.value,
    pageSize: 20,
    medicalType: ['outpatient', 'inhospital']
  }
  if (type.value !== 'all') {
    params.medicalType = [type.value]
  }
  if (dates.value.length) {
    params.startTime = dayjs(dates.value[0]).valueOf();
    params.endTime = dayjs(dates.value[1]).valueOf();
  }
  loading.value = true;
  const res = await api('getCustomerMedicalRecord', params);
  loading.value = false;
  const arr = res && Array.isArray(res.list) ? res.list.map(i => ({
    ...i,
    date: i.sortTime && dayjs(i.sortTime).isValid ? dayjs(i.sortTime).format('YYYY-MM-DD') : '',
    createTime: i.createTime && dayjs(i.createTime).isValid ? dayjs(i.createTime).format('YYYY-MM-DD HH:mm') : '',
    rows: getTempRows(i.medicalType, i)
  })) : [];
  list.value = page.value === 1 ? arr : [...list.value, ...arr];
  more.value = page.value < res.pages;
  console.log(list.value)
}

async function getTeamHealthTemps() {
  const res = await api('getTeamHealthTemps', { teamId: teamId.value, corpId: corpId.value });
  if (res && res.success) {
    const arr = res && Array.isArray(res.data) ? res.data : [];
    tempShowField.value = arr.reduce((m, item) => {
      const templateList = Array.isArray(item.templateList) ? item.templateList : [];
      const data = {}
      templateList.forEach(i => (data[i.title] = i.name));
      m[item.templateType] = data
      return m
    }, {})
  } else {
    toast(res?.message || '获取团队健康档案模板失败');
    return Promise.reject()
  }
}

useLoad(options => {
  name.value = decodeURIComponent(options.name || '');
  teamId.value = options.teamId;
  corpId.value = options.corpId;
  customerId.value = options.id || '';
  getTeam()
  // getTeamHealthTemps();
})

useShow(() => {
  page.value = 1;
  getList()
})

watch(dates, n => {
  page.value = 1;
  getList()
})
</script>
<style>
.min-w-90 {
  min-width: 180rpx;
}

.w-90 {
  width: 160rpx;
}

.w-100 {
  width: 240rpx;
}

.whitespace-nowrap {
  white-space: nowrap;
}

.file-icon {
  margin-right: 10rpx;
  margin-bottom: 10rpx;
  width: 80rpx;
  height: 80rpx;
}
</style>
