<template>
  <ContentWrap>
    <div class="flex-between">
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
        <!-- <el-form-item label="机构">
          <el-select
            class="!w-240px mr5 ml5"
            v-model="queryParams.tenantId"
            @change="changeMonth"
            clearable
          >
            <el-option
              v-for="item in tenantList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item> -->
        <TenantSelect v-model="queryParams.tenantIds" placeholder="请选择机构名称" prop="tenantIds" @change="changeMonth" />
        <el-form-item label="活动月份" class="!w-240px">
          <TgDatePicker type="month" v-model="queryParams.month" @change="changeMonth" />

        </el-form-item>
        <el-form-item label="" class="!w-240px">
          <el-button type="warning" @click="exportPort">导 出</el-button>

        </el-form-item>

      </el-form>
    </div>
  </ContentWrap>

  <ContentWrap>
    <el-scrollbar>
      <el-calendar id="monthlyCalendar" v-model="calendarMonth">
        <template #date-cell="{ data }">
          <div :class="[data.isSelected ? 'is-selected' : '', 'flex-between']">
            <span>{{ data.day.split('-').slice(1).join('-') }}</span>
            <div :class="comAction.isFestival(data) ? 'festival-holiday' : ''"
              ><span v-html="comAction.solarToLunar(data)"></span
            ></div>
          </div>
          <el-scrollbar height="220px" ref="containerRef">
            <div
              class="item"
              v-for="item in monthInfo[data.day.split('-').slice(1).join('-')]?.child"
              :key="item"
              @click="openForm(item, true)"
            >
              <div class="mt2">{{ item.activityTitle }}</div>
              <div class="mt1 text"
                ><Icon icon="ep:clock" /><span class="ml1"
                  >{{ item.activityStartTime.split(' ')[1] }}-{{
                    item.activityEndTime.split(' ')[1]
                  }}</span
                ></div
              >
              <div class="mt1 text"
                ><Icon icon="ep:location-information" /><span class="ml1">{{
                  item.activityAddress
                }}</span></div
              >
            </div>
          </el-scrollbar>
        </template>
      </el-calendar>
    </el-scrollbar>
  </ContentWrap>

  <Form ref="formRef" @success="getList" />
</template>
<script setup lang="ts">
import { getMonthlyActivityByMonth } from '@/api/elderly/activity'
import { getTenant } from '@/api/system/dept'
import lunar from '@/utils/lunar'
import Form from './Form.vue'
import { formatTime } from '@/utils'
import { formatDate } from '@/utils/formatTime'
import { useUserStore } from '@/store/modules/user'
import ExcelJS from 'exceljs'
import { saveAs } from 'file-saver'
import { getAccessToken } from '@/utils/auth'
import { dayjs } from 'element-plus'
const userStore = useUserStore()
const formRef = ref()
const openForm = (row: any = {}, detail: boolean = false) => {
  formRef.value.open(row.tenantId, row.activityId, detail)
}

const comAction = {
  // 是否节假日
  isFestival(slotData) {
    // console.log(slotData);
    let solarDayArr = slotData.day.split('-')
    let lunarDay: any = lunar.solar2lunar(solarDayArr[0], solarDayArr[1], solarDayArr[2])

    // 公历节日\农历节日\农历节气
    let festAndTerm: any = []
    festAndTerm.push(lunarDay.festival == null ? '' : ' ' + lunarDay.festival)
    festAndTerm.push(lunarDay.lunarFestival == null ? '' : '' + lunarDay.lunarFestival)
    festAndTerm.push(lunarDay.Term == null ? '' : '' + lunarDay.Term)
    festAndTerm = festAndTerm.join('')

    return festAndTerm != ''
  },
  // 公历转农历
  solarToLunar(slotData) {
    // console.log(slotData);
    let solarDayArr = slotData.day.split('-')
    let lunarDay: any = lunar.solar2lunar(solarDayArr[0], solarDayArr[1], solarDayArr[2])

    // 农历日期
    let lunarMD = lunarDay.IMonthCn + lunarDay.IDayCn

    // 公历节日\农历节日\农历节气
    let festAndTerm = ''
    festAndTerm += lunarDay.festival == null ? '' : lunarDay.festival + '<br />'
    festAndTerm += lunarDay.lunarFestival == null ? '' : lunarDay.lunarFestival + '<br />'
    festAndTerm += lunarDay.Term == null ? '' : lunarDay.Term + '<br />'
    return festAndTerm == '' ? lunarMD : festAndTerm
  }
}

onMounted(async () => {
  calendarMonth.value = formatTime(Date.now(), 'yyyy-MM')
  queryParams.month = calendarMonth.value
  // await getTenantList()
  getList()
})

const tenantList = ref<{ id: string; name: string }[]>([])
const getTenantList = async () => {
  const res = await getTenant()
  tenantList.value = res
  // 如果只有一条数据就默认选中
  // if (res.length == 1) {
  //   queryParams.tenantId = res[0].id
  // }
}

const exportPort = async () => {
  const params = new URLSearchParams()
  params.append('month', queryParams.month)
  queryParams.tenantIds.map(item => {
    params.append('tenantIds', item)
  })
  const listData = await getMonthlyActivityByMonth(params)
  const exportList = listData || []

  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet('月度活动')

  const activityTypeMap: Record<string, string> = {
    '1': '节日庆典',
    '2': '健康讲座',
    '3': '文艺活动',
    '4': '体育健身',
    '5': '志愿服务',
    '6': '其他'
  }
  const statusMap: Record<number, string> = {
    0: '未开始',
    1: '进行中',
    2: '已结束'
  }

  worksheet.columns = [
    { header: '活动主题', key: 'activityTitle', width: 50 },
    { header: '活动类型', key: 'activityTypeText', width: 15 },
    { header: '活动日期', key: 'activityDate', width: 20 },
    { header: '活动开始时间', key: 'activityStartTime', width: 20 },
    { header: '活动结束时间', key: 'activityEndTime', width: 20 },
    { header: '活动地点', key: 'activityAddress', width: 30 },
    { header: '参与人数', key: 'number', width: 15 },
    { header: '报名开始时间', key: 'registrationStartTime', width: 20 },
    { header: '报名结束时间', key: 'registrationEndTime', width: 20 },
    { header: '状态', key: 'statusText', width: 15 },
    { header: '负责人', key: 'supervisorName', width: 15 },
    { header: '创建人', key: 'createdBy', width: 15 },
    { header: '活动说明', key: 'remarks', width: 60 }
  ]

  const headerRow = worksheet.getRow(1)
  headerRow.font = { bold: true, size: 12 }
  headerRow.fill = {
    type: 'pattern',
    pattern: 'solid',
    fgColor: { argb: 'FFE0E0E0' }
  }
  headerRow.alignment = { horizontal: 'center', vertical: 'middle' }

  for (let i = 0; i < exportList.length; i++) {
    const item = exportList[i]
    const row = worksheet.addRow({
      activityTitle: item.activityTitle,
      activityTypeText: activityTypeMap[item.activityType] || item.activityType,
      activityDate: item.activityDate,
      activityStartTime: item.activityStartTime,
      activityEndTime: item.activityEndTime,
      activityAddress: item.activityAddress,
      number: item.number,
      registrationStartTime: item.registrationStartTime,
      registrationEndTime: item.registrationEndTime,
      statusText: statusMap[item.status] || item.status,
      supervisorName: item.supervisorName,
      createdBy: item.createdBy,
      remarks: item.remarks
    })
    row.alignment = { vertical: 'top', wrapText: true }
  }

  const buffer = await workbook.xlsx.writeBuffer()
  const blob = new Blob([buffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })
  saveAs(blob, `月度活动_${queryParams.month}_${dayjs().format('YYYY-MM-DD')}.xlsx`)
}

const calendarMonth = ref()
const monthInfo = ref({})
const queryParams = reactive({
  month: '',
  tenantIds: userStore.orgTenantId
})
const getList = async () => {
  const params = new URLSearchParams()
  params.append('month', queryParams.month)
  if(typeof queryParams.tenantIds == 'number' || typeof queryParams.tenantIds == 'string'){
    params.append('tenantIds', props.tId)
  }else{
    queryParams.tenantIds.map(item=>{
      params.append('tenantIds', item)
    })
  }
  const res = await getMonthlyActivityByMonth(params)
  let dataInfo = {}
  res.forEach((item) => {
    item.activityDate = formatDate(item.activityDate, 'MM-DD')
    item.activityStartTime = item.activityStartTime
    item.activityEndTime = item.activityEndTime
    let { activityDate } = item
    if (!dataInfo[activityDate]) {
      dataInfo[activityDate] = {
        activityDate,
        child: []
      }
    }
    dataInfo[activityDate].child.push(item)
  })
  monthInfo.value = dataInfo
}

// // 在 script setup 中添加
// watch(calendarMonth, (newVal) => {
//   if (newVal) {
//     // formatDate 是你已经引入的工具函数，格式化为 'YYYY-MM'
//     queryParams.month = formatDate(newVal, 'YYYY-MM')
//     console.log(queryParams.month)
//     // 如果 formatDate 不合适，也可以手动格式化：
//     // queryParams.month = dayjs(newVal).format('YYYY-MM')
//   }
// })

const changeMonth = () => {
  calendarMonth.value = queryParams.month
  getList()
}
</script>
<style lang="scss">
.crown {
  width: 22px;
  margin-right: 5px;
}

#monthlyCalendar {
  min-width: 900px;
  .el-calendar__body {
    .el-calendar-table {
      border-collapse: separate;
      border-spacing: 15px;
      .el-calendar-table__row {
        width: 150px;
        height: 250px;
        .current {
          background-color: #f4f6f9;
          border-radius: 8px;

          &.is-today {
            background-color: var(--el-calendar-selected-bg-color);
            .item {
              color: #6f6d70;
              &:hover {
                background-color: var(--el-color-primary-light-7);
                color: #fff;
              }
            }
          }

          &.is-selected {
            background-color: var(--el-calendar-selected-bg-color);
          }
        }
        .next,
        .prev {
          background-color: #f6f6f6;
          border-radius: 8px;
        }
      }
      .el-scrollbar {
        .item {
          color: #6f6d70;
          box-sizing: border-box;
          font-size: 14px;
          padding-bottom: 3px;
          border-bottom: 1px solid #ddd;
          cursor: pointer;
          &:hover {
            background-color: var(--el-color-primary-light-7);
            color: #fff;
          }
        }
        .text {
          display: flex;
          align-items: center;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
    }
  }
  .f600 {
    font-weight: 600;
  }
}

.el-calendar-table td {
  border: none !important;
}
.el-calendar-table {
  thead {
    th {
      background-color: #f6f6f6;
      border-radius: 8px;
      margin: 5px;
      &:before {
        content: '星期';
      }
    }
  }
  .el-calendar-day {
    height: 100% !important;
    &:hover {
      cursor: auto;
      background-color: transparent;
    }
  }
}

.el-calendar__header {
  display: none;
}
</style>
