<!--日历组件-->
<template>
  <card-widget :style="style">
    <template #header v-if="showHeaderFlag">
      <div style="display: flex; position: relative">
        <div style="flex: 1; display: flex; align-items: center; justify-content: space-between">
          <span class="text_box">{{ title }}</span>
          <a-space>
            <a-button size="mini" class="today-btn" @click="jumpToday" style="height: 26px; font-size: 14px">今天</a-button>
          </a-space>
        </div>
      </div>
    </template>
    <template #body>
      <a-calendar v-model:value="dateValue" :fullscreen="false" valueFormat="YYYY-MM-DD" @panelChange="onPanelChange">
        <template #headerRender="{ value: current, onChange }">
          <div class="date-h">
            <left-outlined class="date-icon" @click="onChange(current.clone().subtract(1, 'month'))" />
            <span class="date-value"> {{ current.year() }}年 {{ current.month() + 1 }} 月 </span>
            <right-outlined class="date-icon" @click="onChange(current.clone().add(1, 'month'))" />
          </div>
        </template>
        <template #dateCellRender="{ current }">
          <div class="today" v-if="today == currentCompareDate(current)">今</div>
          <div class="has-schedule" v-if="Object.keys(workList).includes(currentCompareDate(current))"></div>
        </template>
      </a-calendar>
      <div class="user-schedule">
        <div class="user-schedule-h">
          <span>日程：{{ getScheduleDate }}</span>
          <a @click="addEditSchedule()">新增</a>
        </div>
        <div class="user-schedule-list">
          <div class="user-schedule-item" v-for="sItem in scheduleList" :key="sItem.id" @click="addEditSchedule(sItem)">
            <span :class="['user-schedule-item-status', { emergency: sItem.urgencyType == 20 }]"></span>
            <span class="user-schedule-item-time" v-if="sItem?.startTime">{{ getHm(sItem.startTime) }}</span>
            <span class="user-schedule-item-title">
              <a-tooltip placement="topLeft">
                <template #title>
                  <span>{{ sItem.title }}</span>
                </template>
                {{ sItem.title }}
              </a-tooltip>
            </span>
            <DeleteOutlined class="user-schedule-item-del" @click.stop="remove(sItem)" />
          </div>
          <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" v-if="scheduleList.length == 0" description="暂无日程"></a-empty>
        </div>
      </div>
    </template>
  </card-widget>

  <CalendarAddEdit v-model:visible="showAddEdit" v-if="showAddEdit" :data="current" :calendarDate="dateValue" @done="getCalendarList" />
</template>

<script setup name="CalendarWidget">
import { computed, onMounted, ref, defineAsyncComponent, watch, createVNode } from 'vue';
import { getNowTime } from '@/utils/common/time-util';
import { PortalCalendarApi } from '../../api/PortalCalendarApi';
import CardWidget from '@/views/home/components/card_widget.vue';
import { Empty, message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

const CalendarAddEdit = defineAsyncComponent(() => import('../operate/calendar-add-edit.vue'));

const props = defineProps({
  widget: Object,
  // 门户设计id
  designId: {
    type: String,
    default: ''
  }
});

const dateValue = ref('');

const year = ref('');

const month = ref('');

// 当前日期列表
const workList = ref({});

const showAddEdit = ref(false);

const current = ref(null);

// 日程列表
const scheduleList = ref([]);

const style = ref({});

const showHeaderFlag = ref(false);

const title = ref('');

const today = ref(getNowTime());

const getScheduleDate = computed(() => {
  if (!dateValue.value) return '';
  const arr = dateValue.value.split('-');
  return `${arr[1]}.${arr[2]}`;
});

const getHm = computed(() => val => {
  let backTime = val;
  if (val) {
    const timePart = val.split(' ')[1]; // 获取时间部分
    backTime = timePart.substring(0, 5); // 取前五个字符（hh:mm）
  }
  return backTime;
});

const currentCompareDate = computed(() => val => {
  const year = val.year();
  let month = val.month() + 1;
  if (month < 10) month = '0' + month;
  const date = val.date();
  return year + '-' + month + '-' + date;
});

onMounted(() => {
  updateWidget();
});

const updateWidget = () => {
  jumpToday();

  if (props.widget?.param) {
    title.value = props.widget?.param?.elementName;
    if (props.widget?.param?.config) {
      const { showHeader, borderLeft, borderRight, borderTop, borderBottom } = props.widget?.param?.config;
      showHeaderFlag.value = showHeader;
      style.value = {
        'border-left': borderLeft,
        'border-right': borderRight,
        'border-top': borderTop,
        'border-bottom': borderBottom
      };
    }
  }
};

const jumpToday = () => {
  dateValue.value = getNowTime();
  year.value = dateValue.value.split('-')[0];
  month.value = dateValue.value.split('-')[1];
  getCalendarList();
};

const onPanelChange = date => {
  year.value = date.split('-')[0];
  month.value = date.split('-')[1];
  getCalendarList();
};

// 获取列表
const getCalendarList = async () => {
  workList.value = await PortalCalendarApi.list({
    year: year.value,
    month: month.value
  });
  getScheduleList();
};

// 新增日程
const addEditSchedule = record => {
  current.value = record;
  showAddEdit.value = true;
};

// 获取日程列表
const getScheduleList = () => {
  if (dateValue.value) {
    if (workList.value?.[dateValue.value]) {
      scheduleList.value = workList.value?.[dateValue.value];
    } else {
      scheduleList.value = [];
    }
  } else {
    scheduleList.value = [];
  }
};

const remove = record => {
  Modal.confirm({
    title: '删除提醒',
    content: '删除后将无法恢复，确定删除吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      const res = await PortalCalendarApi.delete({ id: record.id });
      message.success(res.message);
      getCalendarList();
    }
  });
};

watch(
  () => dateValue.value,
  val => {
    getScheduleList();
  },
  { deep: true }
);

defineExpose({
  updateWidget
});
</script>

<style scoped lang="less">
.date-h {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 10px;
}
.date-icon {
  cursor: pointer;
  color: #adb5b8;
  font-size: 12px;
}
.date-value {
  color: #1b2c45;
  font-size: 16px;
  font-weight: 500;
}
:deep(.ant-picker-calendar .ant-picker-panel) {
  border-top: 0px;
}

.today-btn {
  display: flex;
  padding: 4px 12px !important;
  justify-content: center;
  align-items: center;
  height: 32px;
  border-radius: 4px;
  font-size: 14px !important;
  color: #43505e !important;
  border: 1px solid rgba(197, 207, 209, 0.4);
}

.user-schedule {
  margin-top: 8px;
  padding: 0 8px;
  height: calc(100% - 314px - 8px);

  .user-schedule-h {
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
      color: #43505e;
      font-size: 16px;
      font-weight: 700;
    }
  }

  .user-schedule-list {
    width: 100%;
    height: calc(100% - 26px);
    overflow-y: auto;
    position: relative;

    .user-schedule-item {
      width: 100%;
      display: flex;
      align-items: center;
      cursor: pointer;
      margin-top: 16px;

      .user-schedule-item-status {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 8px;
        margin-right: 8px;
        background-color: #1983ff;
      }

      .emergency {
        background-color: #ff3b4e;
      }

      .user-schedule-item-time {
        color: #4e5969;
        font-size: 16px;
        margin-right: 8px;
      }

      .user-schedule-item-title {
        width: calc(100% - 16px - 48px - 24px);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #43505e;
        font-size: 16px;
      }

      .user-schedule-item-del {
        display: none;
        margin-left: 8px;
        color: red;
      }

      &:hover {
        .user-schedule-item-title {
          color: var(--primary-color);
        }
        .user-schedule-item-del {
          display: inline-block;
        }
      }
    }

    .ant-empty {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -32px;
      margin-top: -42px;
    }
  }
}

:deep(.ant-picker-cell .ant-picker-cell-inner) {
  width: 100%;
  height: 100%;
  min-height: 45px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  font-weight: 600;
  border: 2px solid transparent;
}
:deep(.ant-picker-cell .ant-picker-cell-inner:hover) {
  background-color: rgba(78,110,242,.1) !important;
}
:deep(.ant-picker-cell-in-view.ant-picker-cell-today .ant-picker-cell-inner::before) {
  border: 0px;
}
:deep(.ant-picker-cell-in-view.ant-picker-cell-selected .ant-picker-cell-inner) {
  background-color: transparent;
  border: 2px solid #4e6ef2;
  color: #333;
}
.has-schedule {
  position: absolute;
  bottom: -7px;
  left: 50%;
  margin-left: -1px;
  width: 4px;
  height: 4px;
  background-color: #1983ff;
  border-radius: 50%;
}
.today {
  position: absolute;
  top: 0;
  right: 0;
  color: #fff;
  background: #6b88ff;
  font-size: 12px;
  line-height: 14px;
  padding: 1px 2px;
  font-weight: normal;
}
</style>
