<template>
  <el-card class="left-card">
    <!-- 顶部标签页 -->
    <el-tabs v-model="activeTab" class="main-tabs">
      <el-tab-pane label="肠内营养" name="nutrition">
        <div class="content-wrapper">
          <!-- 日期和操作栏 -->
          <div class="operation-bar">
            <!-- 日期选择 -->
            <el-row>
              <el-col :span="8">
                <span class="label">日期时间：</span>
                <el-date-picker
                  v-model="prescriptionDate"
                  :clearable="false"
                  type="date"
                  :disabled-date="disabledBeforeToday"
                  placeholder="请选择"
                  value-format="YYYY-MM-DD"
                />
              </el-col>
              <el-col :span="4"> </el-col>
              <el-col class="right_btn" :span="12">
                <el-button type="primary" plain @click="submitForm('2')">存为草稿</el-button>
                <el-button type="primary" @click="submitForm('0')" :loading="buttonLoading">提交</el-button>
                <el-button type="danger" @click="deleteFrom">删除</el-button>
                <el-button type="primary" plain>打印知情同意书</el-button>
                <el-button type="success" @click="goHistoryPrescription">历史处方</el-button>
              </el-col>
            </el-row>

            <!-- 添加按钮组 -->
            <div class="add-buttons">
              <el-button :class="['add-btn', {'is-active': prescriptionType === 'normal'}]" @click="addPrescription">添加配置处方</el-button>
              <el-button :class="['add-btn', {'is-active': prescriptionType === 'package'}]" @click="addTemplate">添加预包装处方</el-button>
              <el-button :class="['add-btn', {'is-active': prescriptionType === 'long-term'}]" @click="addLongTerm">添加长期医嘱处方</el-button>
            </div>

            <!-- 开方原因 -->
            <!-- <div class="prescription-reason">
              <span class="reason-label">开方原因：</span>
              <span class="reason-value">1111</span>
            </div> -->
          </div>

          <!-- 处方提示信息 -->
          <!-- <div class="prescription-info">
            <div class="warning-box">
              当前处方中的脂肪、维生素A、维生素D、维生素E、维生素B1、维生素B2、维生素B6、维生素B12、硒(尼克黄)、维生素C、生物素、泛酸元素可能过量
            </div>
          </div> -->

          <!-- 处方表格 -->
          <div class="prescription-tables">
            <template v-if="tableType === 'normal'">
              <ConfigureTable @change="updateConfigureData" v-model="configData" />
              <MaterialTable v-model="configData" @change="updateMaterialData" />
            </template>
            <template v-else-if="tableType === 'package'">
              <PackageTable @change="updatePackageData" />
            </template>
            <template v-else>
              <NutritionTable @change="updateLongTermData" v-model="longTermData" :prescriptionDate="prescriptionDate" />
              <MaterialTable2 v-model="longTermData" @change="updateMaterial2Data" />
            </template>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="膳食治疗" name="therapy">
        <!-- 膳食治疗内容 -->
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import NutritionTable from './table/NutritionTable.vue';
import MaterialTable from './table/MaterialTable.vue';
import MaterialTable2 from './table/MaterialTable2.vue';
import PackageTable from './table/PackageTable.vue';
import ConfigureTable from './table/ConfigureTable.vue';

import {listEnteralNutrition, getEnteralNutrition, delEnteralNutrition, addEnteralNutrition, updateEnteralNutrition} from '@/api/patients/nutrition';
import {EnteralNutritionVO, EnteralNutritionQuery, EnteralNutritionForm, EnteralNutritionSaveForm} from '@/api/patients/nutrition/types';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const emit = defineEmits(['gotoTop']);
const buttonLoading = ref(false);
const {patientInfo} = defineProps<{patientInfo: any}>();

// 顶部tab切换
const activeTab = ref('nutrition');
const configData = ref('');
const packageData = ref('');
const longTermData = ref('');
const materialData = ref('');
const materialData2 = ref('');

// 表格类型
const tableType = ref<'normal' | 'package' | 'long-term'>('normal');

// 日期范围
const prescriptionDate = ref('');

// 处方类型
const prescriptionType = ref<'normal' | 'package' | 'long-term'>('normal');

const updateConfigureData = (val: string) => {
  configData.value = val;
};

const updateLongTermData = (val: string) => {
  longTermData.value = val;
};

const updatePackageData = (val: string) => {
  packageData.value = val;
};

const updateMaterialData = (val: string) => {
  materialData.value = val;
};

const updateMaterial2Data = (val: string) => {
  materialData2.value = val;
};

const deleteFrom = async () => {
  configData.value = JSON.stringify([]);
};

const submitForm = async (status: string) => {
  let param = ref<EnteralNutritionSaveForm>({});
  param.value.patientId = patientInfo.id;
  param.value.visitType = patientInfo.type;

  param.value.patientNo = patientInfo.outpatientNo;
  param.value.status = status;

  if (prescriptionType.value == 'normal') {
    param.value.chargeType = '3';
    if (!configData.value || configData.value.length == 0) {
      proxy?.$modal.msgError('营养产品不为空');
      return;
    }
    param.value.nutritionList = JSON.parse(configData.value);

    if (!materialData.value || materialData.value.length == 0) {
      proxy?.$modal.msgError('耗材不为空');
      return;
    }
    param.value.consumableList = JSON.parse(materialData.value);
  } else if (prescriptionType.value == 'package') {
    param.value.chargeType = '2';
    if (!packageData.value || packageData.value.length == 0) {
      proxy?.$modal.msgError('营养产品不为空');
      return;
    }
    param.value.nutritionList = JSON.parse(packageData.value);
  } else {
    param.value.chargeType = '4';
    if (!longTermData.value || longTermData.value.length == 0) {
      proxy?.$modal.msgError('营养产品不为空');
      return;
    }
    param.value.nutritionList = JSON.parse(longTermData.value);

    if (!materialData2.value || materialData2.value.length == 0) {
      proxy?.$modal.msgError('耗材不为空');
      return;
    }
    param.value.consumableList = JSON.parse(materialData2.value);
  }

  if (param.value.chargeType != '2') {
    for (let item of param.value.consumableList) {
      if (!item.consumableId) {
        proxy?.$modal.msgError('耗材没有选择');
        return;
      }

      item.groupNo = item.sn;
      let arr = item.consumableId.split('_');
      item.consumableId = arr[0];
    }

    for (let item of param.value.nutritionList) {
      if (!item.products || item.products.length == 0) {
        proxy?.$modal.msgError('营养产品没有记录');
        return;
      }

      let tsList = [];
      item.timeSlots.forEach((ts) => {
        tsList.push(ts.checked ? ts.time : '');
      });
      item.mealTime = tsList.join(',');
      item.prescriptionDate = prescriptionDate.value;
      item.prescriptionType = param.value.chargeType;

      for (let pd of item.products) {
        if (!pd.nutritionProductId) {
          proxy?.$modal.msgError('营养产品没有选择');
          return;
        }

        let arr = pd.nutritionProductId.split('_');
        pd.nutritionProductId = arr[0];
        pd.usage = item.usage ;
        pd.preparationVolumePerTime = item.preparationVolumePerTime ;
        pd.preparationConcentrationPerTime = item.preparationConcentrationPerTime ;
        pd.energyDensityPerTime = item.energyDensityPerTime ;

        pd.prescriptionDate = prescriptionDate.value;
        pd.groupNo = item.sn;
      }
    }
  } else {
    for (let item of param.value.nutritionList) {
      let tsList = [];
      item.timeSlots.forEach((ts) => {
        tsList.push(ts.checked ? ts.time : '');
      });
      item.mealTime = tsList.join(',');
      item.prescriptionDate = prescriptionDate.value;
      item.prescriptionType = param.value.chargeType;

      if (!item.nutritionProductId) {
        proxy?.$modal.msgError('营养产品没有选择');
        return;
      }

      let arr = item.nutritionProductId.split('_');
      item.nutritionProductId = arr[0];

      item.prescriptionDate = prescriptionDate.value;
      item.groupNo = item.sn;
    }
  }

  await addEnteralNutrition(param.value).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('操作成功');
};

// 添加配置处方
const addPrescription = () => {
  prescriptionType.value = 'normal';
  tableType.value = 'normal';
};

// 添加预包装处方
const addTemplate = () => {
  prescriptionType.value = 'package';
  tableType.value = 'package';
};

// 添加长期医嘱处方
const addLongTerm = () => {
  prescriptionType.value = 'long-term';
  tableType.value = 'long-term';
};

// 跳转历史处方页面
const goHistoryPrescription = () => {
  emit('gotoTop');
};

function formatDate(date) {
  const pad = (n) => (n < 10 ? '0' + n : n);
  return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate());
}

// 禁用今天之前的日期
const disabledBeforeToday = (date) => {
  const today = new Date();
  // 设置时间为今天凌晨，确保比较的是日期而非具体时间
  today.setHours(0, 0, 0, 0);
  return date < today;
};

onMounted(() => {
  let now = new Date();
  let start = formatDate(now);
  prescriptionDate.value = start;
});
</script>

<style lang="scss" scoped>
.left-card {
  flex: 1;
  position: relative;
  .main-tabs {
    :deep(.el-tabs__header) {
      margin-bottom: 20px;
    }
    :deep(.el-tabs__nav) {
      .el-tabs__item {
        font-size: 15px;
        padding: 0 30px;
        height: 40px;
        line-height: 40px;
      }
    }
  }
  .operation-bar {
    margin-bottom: 16px;
    .right_btn {
      margin-left: 0px;
    }

    .add-buttons {
      display: flex;
      gap: 12px;
      margin-top: 30px;
      margin-bottom: 12px;

      .add-btn {
        min-width: 120px;
        background-color: #fff;
        border: 1px solid #dcdfe6;
        color: #606266;
        transition: all 0.3s;

        &.is-active {
          background-color: var(--el-color-primary);
          border-color: var(--el-color-primary);
          color: #fff;
        }

        &:hover:not(.is-active) {
          border-color: var(--el-color-primary);
          color: var(--el-color-primary);
        }
      }
    }

    .prescription-reason {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #f56c6c;
      font-size: 14px;

      .reason-label {
        color: #606266;
      }

      .reason-value {
        color: #f56c6c;
      }
    }
  }

  .prescription-info {
    margin-bottom: 16px;

    .warning-box {
      padding: 8px 16px;
      background: #fff7e6;
      border: 1px solid #ffd591;
      border-radius: 4px;
      color: #fa8c16;
      border: 1px solid #fa8c16;
      font-size: 12px;
      line-height: 1.5;
    }
  }

  .prescription-tables {
    display: flex;
    flex-direction: column;
    gap: 20px;
    margin-bottom: 16px;
  }
}
</style>
