<script setup lang="ts">
import type { ReportIndicatorModel }          from '@/model';
import { updateIndicatorByPatientIdMethod }   from '@/request/api/report.api';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons-vue';
import { accessAction, useRequest }           from 'alova/client';
import { Form, message as Message }           from 'ant-design-vue';
import type { Rule }                          from 'ant-design-vue/es/form';


const props = withDefaults(defineProps<{
  dataset: ReportIndicatorModel[];
  loading?: boolean;
  title?: string;

  patientId?: string;
  editable?: boolean;
}>(), {
  title: '指标信息',
});
const emits = defineEmits<{
  destroy: []
}>();

const modelRef = ref<Record<string, number>>({});
const rulesRef = reactive<Record<string, Rule[]>>({});
const { validate, validateInfos } = Form.useForm(modelRef, rulesRef);
watchEffect(() => {
  if ( props.editable ) {
    modelRef.value = {};
    let mmHg: string[] = [];
    for ( const { id, name, value, editor } of props.dataset ) {
      modelRef.value[ id ] = value as number;
      if ( [ '收缩压', '舒张压' ].includes(name) ) { mmHg.push(id); }
      if ( editor.step === 2 ) {
        rulesRef[ id ] ??= [];
        rulesRef[ id ].push({
          validator(_, value) {
            return value && value % 2 !== 0 ? Promise.reject() : Promise.resolve();
          },
          message: `${ name } 需要输入偶数`,
        });
      }
    }
    if ( mmHg.length === 2 ) {
      for ( const id of mmHg ) {
        rulesRef[ id ] ??= [];
        rulesRef[ id ].push({
          validator(_, value) {
            const length = mmHg.map(id => modelRef.value[ id ]).filter(Boolean).length;
            return length === 1 && !value ? Promise.reject() : Promise.resolve();
          },
          message: `请输入`,
        });
      }
    }
  }
});

const { loading: submitting, send: submit } = useRequest(
  () => updateIndicatorByPatientIdMethod(props.patientId!, modelRef.value),
  {
    immediate: false,
  },
).onSuccess(() => {
  Message.success(`指标信息保存成功`);
  accessAction('updatePatientIndicator', delegatedActions => {
    // 调用组件A中的send函数
    delegatedActions.send();
  });
  emits('destroy');
});

/*function openIndicatorRecordPreviewHandle(dataset: ReportIndicatorModel) {
  const id = `modal:record-indicator:preview`;
  const onDestroy = () => { VxeUI.modal.close(id); };
  onDestroy();
  VxeUI.modal.open({
    id, remember: true,
    showMaximize: true, mask: false, lockView: false, padding: false,
    resize: true, width: Math.floor(window.innerWidth * 0.5), height: Math.floor(window.innerHeight * 0.5),
    escClosable: true, maskClosable: true,
    title: `${dataset.name}: 指标信息更新记录`,
    slots: {
      default() {
        return h(ReportIndicatorChartWidget, {
          dataset,
          onDestroy,
        });
      },
    },
  });
}*/
</script>
<template>
  <div ref="container" class="card card__report-analysis">
    <div class="card__header sticky flex justify-between items-center">
      <div class="card__title">
        <span>{{ props.title }}</span>
        <a-spin v-if="props.loading" size="small" style="margin-left: 4px;" />
        <a-space style="margin-left: 8px">
          <slot name="tool-bar"></slot>
        </a-space>
      </div>
    </div>
    <div class="card__content" v-if="props.dataset">
      <a-form
        v-if="props.editable"
        :label-col="{span: 12}" :wrapperCol="{span:12}"
        :model="modelRef"
        @submit="validate().then(submit, ()=>{})"
      >
        <a-row :gutter="8">
          <a-col
            v-for="(item, index) in props.dataset" :key="item.id"
            :xxl="{span: 6}" :xl="{span: 8}" :lg="{span: 12}" :span="24"
          >
            <a-form-item :label="item.name" :html-for="item.id" v-bind="validateInfos[item.id]">
              <a-tooltip trigger="focus" placement="topLeft">
                <template #title>
                  {{ item.range[ 0 ] }} {{ item.unit }} - {{ item.range[ 1 ] }} {{ item.unit }}
                </template>
                <a-input-number
                  :id="item.id"
                  v-model:value="modelRef[item.id]"
                  v-bind="item.editor" :controls="true"
                  :addon-before="item.editor.prefix" :addon-after="item.editor.suffix"
                ></a-input-number>
              </a-tooltip>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="justify-center">
          <a-form-item style="margin: auto;">
            <a-space>
              <a-button type="primary" html-type="submit" :loading="submitting">保存</a-button>
              <a-button type="dashed" @click="$emit('destroy')">取消</a-button>
            </a-space>
          </a-form-item>
        </a-row>
      </a-form>
      <a-descriptions v-else-if="props.dataset?.length" :column="3" size="small">
        <a-descriptions-item v-for="item in props.dataset" :key="item.id" :label="item.name">
          <div v-if="item.value">
            <span>{{ item.value }}</span>
            <span v-if="item.unit">{{ item.unit }}</span>
            <ArrowUpOutlined class="icon" v-if="item.records?.[0]?.abnormal === 1" />
            <ArrowDownOutlined class="icon" v-if="item.records?.[0]?.abnormal === -1" />
          </div>
          <span v-else>-</span>
        </a-descriptions-item>
      </a-descriptions>
      <a-empty v-else description="暂无数据"></a-empty>
    </div>
  </div>
</template>
<style scoped lang="scss">
@import "@/themes/report-card";

.icon {
  margin-left: 8px;
  color: #ff7875;
  font-size: 16px;
}
</style>
