<template>
  <div class="p-2">
    <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="100px">
            <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>
            <br />
            <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="emit('addHospital')"
              v-hasPermi="['patients:hospitalMealPlan: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="mealPlanList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="推荐时间" width="200px" align="center" prop="createTime" />
        <el-table-column label="看诊类型" width="100px" align="center" prop="type">
          <template #default="scope">
            <span>{{ getDictLabel(treatment_user_type, scope.row.type) || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="门诊/住院号" width="200px" align="center" prop="outpatientNo" />
        <el-table-column label="处方状态" width="100px" align="center" prop="status">
          <template #default="scope">
            <span>{{ getDictLabel(payment_status, scope.row.status) || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="推荐医生" width="150px" align="center" prop="createByUser" />
        <el-table-column label="操作" width="200px" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)">详情</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>
</template>

<script setup name="MealPlan" lang="ts">
import { listMealPlan, getMealPlan, delMealPlan, addMealPlan, updateMealPlan } from '@/api/patients/hospitalMealPlan';
import { MealPlanVO, MealPlanQuery, MealPlanForm } from '@/api/patients/hospitalMealPlan/types';
import { useHospitalStore } from '@/store/modules/hospital';

const useStore = useHospitalStore();
const { setHospitalList, hospitalList } = useStore;

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { treatment_user_type, payment_status } = toRefs<any>(proxy?.useDict('treatment_user_type', 'payment_status'));

const mealPlanList = ref<MealPlanVO[]>([]);
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 emit = defineEmits(['change', 'addHospital', 'back']);

const queryFormRef = ref<ElFormInstance>();
const mealPlanFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const props = defineProps({
  patientInfo: {
    type: Object,
    required: true,
    default: () => ({
      id: '',
      name: '',
      age: '',
      gender: ''
    })
  }
});

const initFormData: MealPlanForm = {
  id: undefined,
  type: props.patientInfo.type,
  patientId: props.patientInfo.id,
  outpatientNo: props.patientInfo.outpatientNo,
  deptId: props.patientInfo.deptId,
  recommendStartDate: undefined,
  recommendEndDate: undefined,
  totalPrice: undefined,
  status: undefined,
  remark: undefined,
  mealRecipeList: []
};
const data = reactive<PageData<MealPlanForm, MealPlanQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    patientId: props.patientInfo.id,
    outpatientNo: undefined,
    deptId: undefined,
    dateRange: [],
    searchValue: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    patientId: [{ required: true, message: '患者ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询院内膳食主列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMealPlan(queryParams.value);
  mealPlanList.value = res.rows;
  setHospitalList(mealPlanList.value);
  total.value = res.total;
  loading.value = false;
};

// 字典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 reset = () => {
  form.value = { ...initFormData };
  mealPlanFormRef.value?.resetFields();
  queryParams.value.dateRange = undefined;
  queryParams.value.type = undefined;
  queryParams.value.searchValue = undefined;
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const handleView = async (row?: MealPlanVO) => {
  emit('change', 'hospitalIndex', row);
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.dateRange = undefined;
  queryParams.value.type = undefined;
  queryParams.value.searchValue = undefined;
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MealPlanVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加院内膳食';
};

//
const handleDetail = (row?: MealPlanVO) => {
  console.log('row', JSON.stringify(row));
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MealPlanVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getMealPlan(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改院内膳食';
};

/** 提交按钮 */
const submitForm = (mealPlanForm) => {
  form.value.recommendStartDate = mealPlanForm.mealTimeRange[0];
  form.value.recommendEndDate = mealPlanForm.mealTimeRange[1];
  form.value.totalPrice = mealPlanForm.totalPrice;
  form.value.mealRecipeList = mealPlanForm.mealRecipeList;
  addMealPlan(form.value).finally(() => (buttonLoading.value = false));
  getList();
  mealPlanFormRef.value?.validate(async (valid: boolean) => {
    if (true) {
      form.value.recommendStartDate = mealPlanForm.mealTimeRange[0];
      form.value.recommendEndDate = mealPlanForm.mealTimeRange[1];
      form.value.mealRecipeList = mealPlanForm.mealRecipeList;
      buttonLoading.value = true;
      if (form.value.id) {
        await updateMealPlan(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMealPlan(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (id?: number) => {
  const _ids = id;
  await proxy?.$modal.confirm('是否确认作废院内膳食主编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMealPlan(_ids);
  proxy?.$modal.msgSuccess('作废成功');
  emit('back', 'hospitalIndex');

  await getList();
};

defineExpose({ submitForm, handleDelete });

onMounted(() => {
  getList();
});
</script>
