<template>
  <div class="p-2">
    <div v-show="type == 'list'">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div v-show="showSearch" class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="120px">
              <el-form-item label="时间：">
                <el-date-picker
                  v-model="queryParams.dateRange"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item label="看诊类型：">
                <el-select v-model="queryParams.type" class="spec-unit-select">
                  <el-option v-for="dict in treatment_user_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="营养设定方式：">
                <el-select v-model="queryParams.settingType" class="spec-unit-select">
                  <el-option v-for="dict in nutrition_setting_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-input v-model="queryParams.searchValue" placeholder="门诊/住院号、医生" style="width: 240px" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </transition>

      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['patients:nutritionSetting:add']">新增营养设定</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>
        <el-table v-loading="loading" border :data="settingList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="时间" align="center" prop="createTime" />
          <el-table-column label="看诊类型" align="center" prop="type">
            <template #default="scope">
              <span>{{ getDictLabel(treatment_user_type, scope.row.type) || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="门诊/住院号" align="center" prop="outpatientNo" />
          <el-table-column label="营养设定方式" align="center" prop="settingType">
            <template #default="scope">
              <span>{{ getDictLabel(nutrition_setting_type, scope.row.settingType) || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所需热量(kcal/d)" align="center" prop="caloriesKcalPerDay" />
          <el-table-column label="评估医生" align="center" prop="createByUser" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <!-- <el-tooltip content="修改" placement="top">
                                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['patients:nutritionSetting:edit']"></el-button>
                            </el-tooltip> -->
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['patients:nutritionSetting:remove']"
                  >删除</el-button
                >
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>
    </div>
    <div>
      <el-dialog
        :title="'选择营养设定'"
        v-model="dialog.visible"
        width="737px"
        append-to-body
        :close-on-click-modal="false"
        :show-close="true"
        class="nutrition-setting-dialog"
      >
        <el-row :gutter="20" style="margin-bottom: 10px">
          <el-col :span="12">
            <el-button
              :class="['setting-type-btn', form.settingType === '1' ? 'active' : '']"
              style="width: 100%; height: 46px"
              @click="handleSelectSettingType('1', 'BEE')"
              >BEE</el-button
            >
          </el-col>
          <el-col :span="12">
            <el-button
              :class="['setting-type-btn', form.settingType === '2' ? 'active' : '']"
              style="width: 100%; height: 46px"
              @click="handleSelectSettingType('2', 'DRIS')"
              >DRIS</el-button
            >
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-button
              :class="['setting-type-btn', form.settingType === '3' ? 'active' : '']"
              style="width: 100%; height: 46px"
              @click="handleSelectSettingType('3', '拇指测法')"
              >拇指测法</el-button
            >
          </el-col>
          <el-col :span="12">
            <el-button
              :class="['setting-type-btn', form.settingType === '4' ? 'active' : '']"
              style="width: 100%; height: 46px"
              @click="handleSelectSettingType('4', '烧伤公式')"
              >烧伤公式</el-button
            >
          </el-col>
        </el-row>
      </el-dialog>
    </div>
    <div v-show="type == 'addForm'">
      <!-- 添加或修改营养设定对话框 -->
      <add-form :form="form" :rules="rules" :buttonLoading="buttonLoading" :cancel="cancel" :handleCancelOne="handleCancelOne" :title="title" />
    </div>
  </div>
</template>

<script setup name="NutritionSetting" lang="ts">
// 变量声明区
import {ref, reactive, toRefs, onMounted, getCurrentInstance, nextTick} from 'vue';
import {listSetting, getSetting, delSetting, addSetting, updateSetting} from '@/api/patients/nutritionSetting';
import {NutritionSettingVO, NutritionSettingQuery, NutritionSettingForm} from '@/api/patients/nutritionSetting/types';
import AddForm from './addForm.vue';
const emit = defineEmits(['change']);
import {log} from 'vxe-table';

const {proxy} = getCurrentInstance();
const {treatment_user_type, nutrition_setting_type} = toRefs(proxy?.useDict('treatment_user_type', 'nutrition_setting_type'));

const settingList = ref<NutritionSettingVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const type = ref('list');
const title = ref('');

const queryFormRef = ref();
const NutritionSettingFormRef = ref();

const dialog = reactive({
  visible: false,
  title: ''
});

const props = defineProps({
  patientInfo: {
    type: Object,
    required: true,
    default: () => ({
      id: '',
      name: '',
      age: '',
      deptId: '',
      gender: ''
    })
  }
});

const initFormData: NutritionSettingForm = {
  id: undefined,
  caloriesKcalPerDay: undefined,
  caloriesKcalPerKgDay: undefined,
  caloriesKjPerDay: undefined,
  proteinCaloriePercentage: undefined,
  fatCaloriePercentage: undefined,
  carbohydrateCaloriePercentage: undefined,
  proteinGPerKgDay: undefined,
  proteinGPerDay: undefined,
  fatGPerKgDay: undefined,
  fatGPerDay: undefined,
  carbohydrateGPerKgDay: undefined,
  carbohydrateGPerDay: undefined,
  calcium: undefined,
  potassium: undefined,
  sodium: undefined,
  magnesium: undefined,
  phosphorus: undefined,
  chloride: undefined,
  iron: undefined,
  selenium: undefined,
  manganese: undefined,
  fluoride: undefined,
  molybdenum: undefined,
  zinc: undefined,
  copper: undefined,
  iodine: undefined,
  chromium: undefined,
  vitaminA: undefined,
  vitaminD: undefined,
  vitaminE: undefined,
  vitaminK: undefined,
  vitaminBOne: undefined,
  vitaminBTwo: undefined,
  vitaminBSix: undefined,
  vitaminBTwelve: undefined,
  niacin: undefined,
  vitaminC: undefined,
  folicAcid: undefined,
  choline: undefined,
  biotin: undefined,
  pantothenicAcid: undefined,
  dietaryFiber: undefined,
  settingType: undefined,
  type: props.patientInfo?.type,
  deptId: props.patientInfo?.deptId,
  deptName: undefined,
  outpatientNo: props.patientInfo?.outpatientNo,
  bmi: props.patientInfo?.bmi,
  height: props.patientInfo?.height,
  weight: props.patientInfo?.weight,
  activity: props.patientInfo?.activity,
  stressType: undefined,
  highHip: undefined,
  lowHip: undefined,
  burnArea: undefined,
  gender: props.patientInfo?.gender,
  age: props.patientInfo?.age
};

const form = ref({...initFormData});
const queryParams = ref({
  patientId: props.patientInfo?.id,
  dateRange: [new Date(), new Date()],
  type: '',
  settingType: '',
  searchValue: '',
  pageNum: 1,
  pageSize: 10
});

const rules = ref({
  height: [{required: true, message: '身高不能为空', trigger: 'blur'}],
  activity: [{required: true, message: '体力活动不能为空', trigger: 'change'}],
  // 只有在 BEE 公式下才校验应激状态
  stressType: [
    {
      required: true,
      message: '应激状态不能为空',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (title.value === 'BEE' && (value === undefined || value === null || value === '')) {
          callback(new Error('应激状态不能为空'));
        } else {
          callback();
        }
      }
    }
  ]
});

// 事件函数区
const handleDelete = async (row?: NutritionSettingVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除营养设定编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delSetting(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleExport = () => {
  proxy?.download(
    '/patients/nutritionSetting/export',
    {
      ...queryParams.value
    },
    `setting_${new Date().getTime()}.xlsx`
  );
};

const handleSelectSettingType = (settingType, typeName) => {
  form.value.settingType = settingType;
  title.value = typeName;
  dialog.visible = false;
  nextTick(() => {
    type.value = 'addForm';
  });
};

// 字典label工具
function getDictLabel(dictList: any[], value: string) {
  if (!dictList || !Array.isArray(dictList)) return value || '--';
  const found = dictList.find((item) => item.value === value);
  return found ? found.label : value || '--';
}

const cancel = () => {
  reset();
  dialog.visible = false;
};
const handleCancel = () => {
  type.value = 'list';
};
const handleCancelOne = () => {
  getList();
  type.value = 'list';
};
const reset = () => {
  form.value = {...initFormData};
  NutritionSettingFormRef.value?.resetFields();
};
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.dateRange = undefined;
  queryParams.value.type = undefined;
  queryParams.value.settingType = undefined;
  queryParams.value.searchValue = undefined;
  handleQuery();
};
const handleSelectionChange = (selection: NutritionSettingVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
const handleAdd = () => {
  dialog.visible = true;
  dialog.title = '选择营养设定方式';
};
const handleUpdate = async (row?: NutritionSettingVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getSetting(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改营养设定';
};

const getList = async () => {
  loading.value = true;
  //  这里补充你的获取数据逻辑
  const res = await listSetting(queryParams.value);
  settingList.value = res.rows || [];
  total.value = res.total;
  loading.value = false;
};

onMounted(() => {
  getList();
});
</script>
<style scoped>
.nutrition-setting-dialog .setting-type-btn {
  font-size: 18px;
  border: 1.5px solid #409eff;
  color: #409eff;
  background: #fff;
  transition:
    background 0.2s,
    color 0.2s;
}

.nutrition-setting-dialog .setting-type-btn.active,
.nutrition-setting-dialog .setting-type-btn:active,
.nutrition-setting-dialog .setting-type-btn:focus {
  background: #e6f0ff;
  color: #409eff;
  border-color: #409eff;
}
</style>
