import { defineComponent, onMounted, reactive, ref, watch } from 'vue'
import { NButton, NCalendar, NSpace, useDialog, useMessage } from 'naive-ui'
import dayjs from 'dayjs'
import styles from './index.module.less'
import { holidaysFestivalsQuery, holidaysFestivalsSave, holidaysFestivalsUpdate } from '../api'

export default defineComponent({
  name: 'system-holiday',
  setup() {
    const message = useMessage()
    const dialog = useDialog()
    const state = reactive({
      btnLoading: false,
      id: null,
      defaultYear: dayjs().year(),
      selectDate: [] as any
    })

    const onSelectDate = (info: any) => {
      const select = dayjs(info).format('YYYY-MM-DD')
      const findIndex = state.selectDate.findIndex((item: any) => item === select)
      console.log(findIndex, 'formatSelectedDate')
      if (findIndex !== -1) {
        state.selectDate.splice(findIndex, 1)
      } else {
        state.selectDate.push(select)
      }
      setTimeout(() => formatSelectedDate(), 100)
    }

    const formatSelectedDate = () => {
      const date = document.querySelectorAll('.n-calendar-date__date')
      date.forEach((dom: any) => {
        let className = dom.parentNode.parentNode.className
        className = className.replace(/n-calendar-cell--selecting/gi, '')
        className = className.replace(/n-calendar-cell--selected/gi, '')
        if (state.selectDate.indexOf(dom.title) !== -1) {
          className = className + ' n-calendar-cell--selecting'
        }
        // console.log(className, 'selected=', dom.title)
        dom.parentNode.parentNode.className = className
      })
    }

    // 切换月份时
    const onPanelChange = (info: any) => {
      if (info.year !== state.defaultYear) {
        dialog.warning({
          title: '提示',
          content: `此操作将清除${state.defaultYear}年未保存的节假日，是否继续？`,
          positiveText: '确定',
          negativeText: '取消',
          maskClosable: false,
          onPositiveClick: () => {
            state.defaultYear = info.year
            getHolidayList()
          },
          onNegativeClick: () => {
            if (info.month === 1) {
              const prevDom: any = document.querySelector('.n-calendar-prev-btn')
              prevDom.parentNode.parentNode.parentNode.click()
            } else if (info.month === 12) {
              const nextMonthDom: any = document.querySelector('.n-calendar-next-btn')
              nextMonthDom.parentNode.parentNode.parentNode.click()
            }
          },
          onClose: () => {
            if (info.month === 1) {
              const prevDom: any = document.querySelector('.n-calendar-prev-btn')
              prevDom.parentNode.parentNode.parentNode.click()
            } else if (info.month === 12) {
              const nextMonthDom: any = document.querySelector('.n-calendar-next-btn')
              nextMonthDom.parentNode.parentNode.parentNode.click()
            }
          }
        })
      } else {
        setTimeout(() => formatSelectedDate(), 100)
      }
    }

    // 获取当年的节假日
    const getHolidayList = async () => {
      try {
        const { data } = await holidaysFestivalsQuery({ year: state.defaultYear })
        console.log(data, 'data')
        const holidaysFestivals = data.holidaysFestivalsJson
          ? data.holidaysFestivalsJson.split(',')
          : []
        state.id = data.id || null
        state.selectDate = holidaysFestivals

        setTimeout(() => formatSelectedDate(), 100)
      } catch {}
    }

    const onSubmit = async () => {
      try {
        if (state.id) {
          await holidaysFestivalsUpdate({
            id: state.id,
            year: state.defaultYear,
            holidaysFestivalsJson: state.selectDate.join(',')
          })
        } else {
          await holidaysFestivalsSave({
            year: state.defaultYear,
            holidaysFestivalsJson: state.selectDate.join(',')
          })
        }
        message.success('保存成功')
        getHolidayList()
      } catch {}
    }

    onMounted(() => {
      getHolidayList()
    })
    return () => (
      <div class="system-menu-container">
        <h2>节假日设置</h2>

        <div class={['section-container', styles.calendar]}>
          <div style="width: 750px; margin: 10px auto; text-align: center">
            <NCalendar
              onPanelChange={(info: any) => onPanelChange(info)}
              onUpdateValue={(info: any) => onSelectDate(info)}
            />
          </div>
          <NSpace justify="center">
            <NButton
              type="primary"
              loading={state.btnLoading}
              onClick={onSubmit}
              //v-auth="holidaysFestivals/save1599946455757737985"
            >
              {/* [
                'holidaysFestivals/save1599946455757737985',
                'holidaysFestivals/update1599946545339682817'
              ] */}
              保存设置
            </NButton>
          </NSpace>
        </div>
      </div>
    )
  }
})
