<script setup lang="ts">
import SwiperImage from '@/components/Swiper.vue';
import { symptomStatus, nextStatus } from '@/model/options';
import type { EvaluationModel } from '@/model/follow.model';
import { tagEditMethod } from '@/request/api/system.api';
import { EvaluateDetailMethod, FillEvaluateMethod } from '@/request/api/follow.api';
import { useRequest } from 'alova/client';
import type { VxeGridProps } from 'vxe-table';
import { notification } from 'ant-design-vue';
import { HealthReportAnalysisItemConfig } from '@/model/health-report-analysis.config';
import { VxeUI } from 'vxe-pc-ui';

type FormModel = Partial<EvaluationModel>;

const defaultModel = {};

const props = defineProps<{ data: FormModel }>();
const emits = defineEmits<{
  submit: [data?: EvaluationModel];
}>();
// 获取表格数据
const gridArr = ref<string[]>([]);
const { loading, send: getDetail } = useRequest(EvaluateDetailMethod, {
  immediate: false,
  initialData: props.data ?? defaultModel,
}).onSuccess(({ data }) => {
  let medicalObj = {
    arrangeTime: data?.medicalTime,
    tonguefaceAnalysisReport: data?.tonguefaceAnalysisReport,
  };
  data.tasks.unshift(medicalObj);
  const tasks = data.tasks.map((item: any) => {
    let obj = {
      date: item.fillinTime || item.arrangeTime,
      k1: item.fillin?.symptomsList
        ?.filter((item: any) => item.type === '好' || item.type === '好转')
        .map((item: any) => item.name)
        .join(','),
      k2: item.fillin?.symptomsList
        ?.filter((item: any) => item.type === '不好' || item.type === '恶化')
        .map((item: any) => item.name)
        .join(','),
      k3: item?.analysis?.tongue.pictures[0],
      k4: item?.analysis?.tongue.pictures[1],
      k5: item?.analysis?.face.pictures[0],
    };
    item?.analysis?.tongue?.analysis.forEach((analysis: any) => {
      obj[analysis?.subcategory] = analysis.resultValue;
    });
    item.analysis?.face?.analysis.forEach((analysis: any) => {
      obj[analysis?.subcategory] = analysis?.resultValue;
    });
    return obj;
  });

  for (const item of HealthReportAnalysisItemConfig) {
    gridOptions.data.push({
      key: item.subcategory,
      title: item.subcategory,
    });
  }
  gridArr.value = tasks;
  loadAssessDetail(tasks);
});
const { loading: submitting, send: submit } = useRequest(tagEditMethod, {
  immediate: false,
}).onSuccess(({ data }) => {
  emits('submit');
});
// 渲染表格
const gridOptions = reactive<VxeGridProps<FormModel>>({
  border: true,
  showOverflow: true,
  height: 780,
  showHeader: false,
  columns: [{ field: 'title', title: '-', slots: { default: 'cell' } }],
  // columnConfig:{
  //   width:'auto'
  // },
  data: [
    { title: '日期', key: 'date', col0: '-' },
    { title: '好转', key: 'k1' },
    { title: '恶化', key: 'k2' },
    { title: '舌面', key: 'k3' },
    { title: '舌下', key: 'k4' },
    { title: '面部', key: 'k5' },
  ],
  cellStyle({ row, rowIndex, column, columnIndex }) {
    const value = row[column.field];
    const style = {};
    if (columnIndex === 1) {
      style.width = '100px';
    }
    if (value?.includes('(') && value?.includes(')')) {
      style.color = 'red';
    }

    if (columnIndex > 1 && value !== row.col1 && HealthReportAnalysisItemConfig.map((item) => item.subcategory).includes(row.key)) {
      style.background = 'yellow';
    }
    if (value?.startsWith('http')) {
      style.height = '100px';
    }
    return style;
  },
});

//加载详情
function loadAssessDetail(data = []) {
  const columns = gridOptions.columns;
  const rows = gridOptions.data;
  let col = columns.length;
  for (const item of data) {
    const field = `col${col}`;
    columns.push({
      field,
      title: `标题${col}`,
      slots: { default: 'cell' },
    });
    col++;
    for (let r = 0; r < rows.length; r++) {
      rows[r][field] = item[rows[r].key];
    }
  }
}

onBeforeMount(() => {
  if (props.data?.id) getDetail(props.data);
});
const radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
});
// 点击对比  查看
const imgArr = ref<string[]>([]);

function openSwiperImage(row, column) {
  const getImages = Object.keys(row)
    .map((key) => {
      return key.startsWith('col') ? row[key] : '';
    })
    .filter(Boolean)
    .map((item) => {
      gridArr.value.forEach((date) => {
        imgArr.value = [{ image: item, date: date.date }];
      });
      return imgArr.value;
    });
  const images = getImages.length > 0 ? getImages[0] : [];
  // 判断当表头等于姓名字段时执行一个方法
  VxeUI.modal.open({
    showHeader: true,
    showCancelButton: true,
    escClosable: true,
    destroyOnClose: true,
    id: `swiper-modal`,
    remember: true,
    storage: true,
    width: 800,
    height: 400,
    slots: {
      default() {
        return h(SwiperImage, <any>{
          images,
          onSubmit(data: EvaluationModel) {
            VxeUI.modal.close(`swiper-modal`);
          },
        });
      },
    },
  });
}

// 提交评估
function subEvalation() {
  FillEvaluateMethod(props.data).then(() => {
    notification.success({
      message: ``,
      description: '提交成功',
    });
    VxeUI.modal.close(`assess-modal`);
    emits('submit');
  });
}
const StatusTextMap: Record<string, string> = {
  '1': '痊愈',
  '2': '好转',
  '3': '无变化',
  '4': '恶化',
};
const DealTextMap: Record<string, string> = {
  '1': '复诊',
  '2': '中医调养',
};
</script>
<template>
  <div>
    <div class="flex" style="background: #eeeeee; padding: 10px; font-size: 13px; border: 0.5px solid lightgrey">
      <div class="border-r border-r-2 border-r-gray-300 border-r-solid pr-6 flex align--center justify-center">
        <div class="mr-2 font-bold" style="font-size: 14px">基本信息</div>
        <div class="mr-3">{{ props.data.medicalTime }}</div>
        <span class="mr-3">{{ props.data.patientName }}</span>
        <span class="mr-3"> {{ props.data.sex === '1' ? '女' : '男' }}</span>
        <span> {{ props.data.age }}岁</span>
      </div>
      <div class="border-r border-r-2 border-r-gray-300 border-r-solid pr-6 pl-6">诊断：{{ props.data?.diagnosis }}</div>
      <div class="pl-6" v-if="props.data?.syndromeList?.length > 0">症状：{{ props.data?.syndromeList?.join(',') }}</div>
    </div>

    <vxe-grid class="reverse-table detail" v-bind="gridOptions">
      <template #cell="{ row, rowIndex, column, columnIndex }">
        <a-image style="height: 100px" v-if="row[column.field] && rowIndex > 2 && rowIndex < 6 && columnIndex !== 0" :src="row[column.field]"></a-image>
        <div v-else-if="row[column.field] === '舌面' || row[column.field] === '舌下' || row[column.field] === '面部'">
          <div>{{ row[column.field] }}</div>
          <div @click="openSwiperImage(row, column)" style="margin-top: 10px; color: #1890ff">对比</div>
        </div>
        <span v-else-if="row[column.field] == props.data.medicalTime" style="color: red">{{ row[column.field] }}（就诊日） </span>
        <!-- <template v-else>{{ row[column.field] }}</template> -->
        <template v-else>{{ row[column.field]?.includes('(r)') ? row[column.field].replace('(r)', '') : row[column.field] }}</template>
      </template>
      <!--      已经评估-->
      <template #right v-if="props.data?.evaluateProgress === '1'">
        <div class="pl-6 pr-4">
          <div style="width: 160px; font-size: 16px" class="border-1 border-gray font-bold mt-2 mb-3">随访结果评估</div>
          <div style="width: 160px" class="border-1 border-gray font-bold mt-2 mb-3">疾病转归</div>
          <div class="mb-8 indent-6">
            {{ StatusTextMap[props?.data?.evaluate.evaluateSituation] || '' }}
          </div>
          <div class="font-bold mt-2 mb-1" v-if="props.data?.evaluateDesc">备注:</div>
          <p class="indent-6 w-30 text-pretty" v-if="props.data?.evaluateDesc">{{ props.data?.evaluateDesc }}</p>
          <div class="font-bold mb-4 mt-15">下一步处置</div>
          <div class="indent-6 font-bold">
            {{ DealTextMap[props?.data?.evaluate.evaluateDeal] || '' }}
          </div>
          <div class="mt-10 flex justify-end flex-col items-center">
            <div>{{ props.data?.evaluateBy }}</div>
            <div>{{ props.data?.evaluateTime }}</div>
          </div>
        </div>
      </template>
      <!--未评估-->
      <template #right v-else>
        <div class="pl-6 pr-4">
          <div style="font-size: 18px" class="border-1 border-gray font-bold mt-2 mb-3">随访结果评估</div>
          <div class="flex items-center justify-center mb-2">
            <div class="w-1 h-1 bg-blue-400"></div>
            <div style="width: 200px" class="border-1 border-gray font-bold ml-2">疾病转归</div>
          </div>
          <div class="ml-2 mb-3">
            <a-radio-group v-model:value="props.data.evaluateSituation">
              <a-radio :style="radioStyle" :value="item.value" v-for="item in symptomStatus">{{ item.label }} </a-radio>
            </a-radio-group>
          </div>
          <div class="flex items-center justify-center mb-2">
            <div class="w-1 h-1 bg-blue-400"></div>
            <div style="width: 200px" class="border-1 border-gray font-bold ml-2">备注</div>
          </div>
          <a-textarea v-model:value="props.data.evaluateDesc" placeholder="请输入" allow-clear style="margin-bottom: 20px" />
          <div class="flex items-center justify-center mb-2">
            <div class="w-1 h-1 bg-blue-400"></div>
            <div style="width: 200px" class="border-1 border-gray font-bold ml-2">下一步处置</div>
          </div>
          <div>
            <a-radio-group v-model:value="props.data.evaluateDeal">
              <a-radio :style="radioStyle" :value="item.value" v-for="item in nextStatus">{{ item.label }} </a-radio>
            </a-radio-group>
          </div>
          <div class="mt-20 flex justify-center" v-show="props.data.evaluateProgress !== '1'">
            <a-button type="primary" @click="subEvalation">完成</a-button>
          </div>
        </div>
      </template>
    </vxe-grid>
  </div>
</template>
<style scoped lang="scss">
.detail {
  :deep(.vxe-cell) {
    height: 100% !important;
  }
}
</style>
