<template>
  <div class="app-container">
    <div style="width: 50%">
      <el-calendar
        v-model="selectedDate"
        @panel-change="
          (value) => {
            console.log(value);
          }
        "
      >
        <template #date-cell="{ data }">
          <div class="calendar-cell" @click="selectDate(data)">
            {{ data.day.split('-').slice(2).join('-') }}
            <div v-if="hasAppointment(data.day)" class="appointment-dot"></div>
          </div>
        </template>
      </el-calendar>
    </div>
    <div class="appointment-section">
      <div class="section-header">
        <h3>{{ selectedDateFormatted }} 的预约</h3>
        <el-button type="primary" @click="showAddForm">新增预约</el-button>
      </div>
      <div v-if="showForm" class="appointment-form">
        <el-form :model="appointmentForm" label-width="80px">
          <el-form-item label="患者姓名">
            <el-input v-model="appointmentForm.patientName" />
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="appointmentForm.patientTel" />
          </el-form-item>
          <el-form-item label="牙位">
            <el-input v-model="appointmentForm.toothPosition" />
          </el-form-item>
          <el-form-item label="预约医生" prop="practitionerId">
            <el-select
              v-model="appointmentForm.practitionerId"
              placeholder="预约医生"
              clearable
              filterable
              remote
              :remote-method="getInit"
            >
              <el-option
                v-for="item in participantListOptions"
                :key="item.practitionerId"
                :label="item.practitionerName"
                :value="item.practitionerId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="预约时间">
            <el-time-select
              v-model="appointmentForm.reservationTime"
              start="07:00"
              step="00:30"
              end="18:00"
              placeholder="选择时间"
            />
          </el-form-item>
          <!-- <el-form-item label="预约类型">
            <el-select v-model="appointmentForm.chiefComplaint" placeholder="请选择">
              <el-option label="初诊" value="初诊" />
              <el-option label="复诊" value="复诊" />
              <el-option label="检查" value="检查" />
              <el-option label="取药" value="取药" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="备注">
            <el-input v-model="appointmentForm.remark" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button @click="cancelForm">取消</el-button>
            <el-button type="primary" @click="saveAppointment">保存</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="appointment-list">
        <div v-if="currentAppointments.length === 0" class="empty-tips">当日无预约</div>
        <div
          v-for="appointment in currentAppointments"
          :key="appointment.id"
          class="appointment-card"
        >
          <div class="card-header">
            <span class="time">{{ appointment.reservationTime }}</span>
            <span>{{ appointment.practitionerName }}</span>
            <!-- <el-tag :type="getTagType(appointment.type)" size="small">
              {{ appointment.type }}
            </el-tag> -->
          </div>

          <div class="card-body">
            <div class="patient-info">
              <span style="margin-left: 0; font-size: 16px" class="descriptions-item-label">
                患者姓名：
              </span>
              <span>{{ appointment.patientName }}</span>
            </div>
            <div class="patient-info">
              <span style="margin-left: 0; font-size: 16px" class="descriptions-item-label">
                手机号：
              </span>
              <span>{{ appointment.patientTel }}</span>
            </div>
            <div class="patient-info">
              <span style="margin-left: 0; font-size: 16px" class="descriptions-item-label">
                牙位：
              </span>
              <span>{{ appointment.toothPosition }}</span>
            </div>
            <div v-if="appointment.remark" class="remark">
              <span style="margin-left: 0; font-size: 16px" class="descriptions-item-label">
                备注：
              </span>
              <span>{{ appointment.remark }}</span>
            </div>
          </div>

          <div class="card-actions">
            <el-button type="primary" size="small" @click="editAppointment(appointment)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="deleteAppointment(appointment.id)">
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import {
  getReservationInfo,
  addReservationInfo,
  editReservationInfo,
  delReservationInfo,
  queryParticipantList,
} from './api';
import { formatDateStr } from '@/utils/index';

const showForm = ref(false);
const selectedDate = ref(new Date());
const selectedDateStr = ref(formatDateStr(new Date(), 'YYYY-MM-DD'));
const isEditing = ref(false);
const editingId = ref(null);
const queryParams = ref({});
const currentAppointments = ref([]);
const participantListOptions = ref([]);
const { proxy } = getCurrentInstance();
// 预约数据
const appointments = ref([]);

// 预约表单
const appointmentForm = reactive({
  id: '',
  patientName: '',
  reservationTime: '',
  patientTel: '',
  remark: '',
});
getRecords(selectedDate.value);
getTodayRecords(selectedDateStr.value);
watch(
  () => selectedDate.value,
  (newValue) => {
    getRecords(newValue);
  },
  { immediate: true }
);
function getRecords(date) {
  let month = formatDateStr(date, 'YYYY-MM');
  getReservationInfo({
    pageNo: 1,
    pageSize: 1000,
    reservationTimeSTime: month + '-01 00:00:00',
    reservationTimeETime: month + '-31 23:59:59',
  }).then((res) => {
    appointments.value = res.data.records.map((item) => {
      return formatDateStr(item.reservationTime, 'YYYY-MM-DD');
    });
    console.log(appointments.value);
  });
}
getInit();
function getInit(value) {
  queryParticipantList({ searchKey: value }).then((res) => {
    participantListOptions.value = res.data;
  });
}

// 格式化选中的日期
const selectedDateFormatted = computed(() => {
  return selectedDate.value.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long',
  });
});
// 检查某天是否有预约
const hasAppointment = (date) => {
  return appointments.value.includes(date);
};

// 选择日期
const selectDate = (date) => {
  selectedDateStr.value = date.day;
  getTodayRecords(date.day);
  showForm.value = false;
};

function getTodayRecords(date) {
  queryParams.value.reservationTimeSTime = date + ' 00:00:00';
  queryParams.value.reservationTimeETime = date + ' 23:59:59';
  getReservationInfo(queryParams.value).then((res) => {
    currentAppointments.value = res.data.records;
  });
}

// 显示添加表单
const showAddForm = () => {
  resetForm();
  isEditing.value = false;
  showForm.value = true;
};

// 编辑预约
const editAppointment = (appointment) => {
  Object.assign(appointmentForm, appointment);
  appointmentForm.reservationTime = formatDateStr(appointmentForm.reservationTime, 'HH:mm');
  isEditing.value = true;
  editingId.value = appointment.id;
  showForm.value = true;
};

// 删除预约
const deleteAppointment = (id) => {
  delReservationInfo({ id: id }).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('操作成功');
    }
    getTodayRecords(selectedDateStr.value);
  });
};

// 保存预约
const saveAppointment = () => {
  if (isEditing.value) {
    let updateParams = {
      ...appointmentForm,
      reservationTime: selectedDateStr.value + ' ' + appointmentForm.reservationTime + ':00',
    };
    editReservationInfo(updateParams).then((res) => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('操作成功');
      }
      getTodayRecords(selectedDateStr.value);
    });
  } else {
    let saveParams = {
      ...appointmentForm,
      reservationTime: selectedDateStr.value + ' ' + appointmentForm.reservationTime + ':00',
    };
    addReservationInfo(saveParams).then((res) => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('操作成功');
      }
      getTodayRecords(selectedDateStr.value);
    });
  }
  cancelForm();
};

// 取消表单
const cancelForm = () => {
  showForm.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  Object.assign(appointmentForm, {
    patientName: '',
    reservationTime: '',
    patientTel: '',
    remark: '',
  });
  isEditing.value = false;
  editingId.value = null;
};

// 获取标签类型
const getTagType = (appointmentType) => {
  const types = {
    初诊: 'primary',
    复诊: 'success',
    检查: 'warning',
    取药: 'info',
  };
  return types[appointmentType] || '';
};
</script>

<style scoped>
.app-container {
  margin: 20px 100px;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  gap: 24px;
}

.calendar-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  cursor: pointer;
}

.appointment-dot {
  position: absolute;
  bottom: 5px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #f56c6c;
}

.appointment-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  width: 45%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.appointment-form {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f8f8f8;
  border-radius: 8px;
}

.appointment-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  max-height: 450px;
  overflow-y: auto;
}

.appointment-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  background-color: #fff;
  transition: box-shadow 0.3s;
}

.appointment-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.time {
  font-weight: bold;
  font-size: 16px;
}

.card-body {
  margin-bottom: 16px;
}

.patient-info,
.remark {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.patient-info .el-icon,
.remark .el-icon {
  margin-right: 8px;
  color: #909399;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.empty-tips {
  text-align: center;
  color: #999;
  padding: 40px 0;
  grid-column: 1 / -1;
}
</style>