import ColHeader from '@/components/col-header'
import ColResult from '@/components/col-result'
import request from '@/helpers/request'
import { formatterDate } from '@/helpers/utils'
import {
  Row,
  Col,
  Button,
  CellGroup,
  Cell,
  Icon,
  Popup,
  List,
  DatetimePicker,
  ActionSheet,
  Toast,
  Dialog
} from 'vant'
import { defineComponent } from 'vue'
import dayjs from 'dayjs'
import Course from './components/course'
import styles from './index.module.less'
import Share from './model/share'
import ColPopup from '@/components/col-popup'
import StudentInfo from './model/student-info'
import StudentConfirm from './model/student-info/student-confirm'
import { useEventListener, useWindowScroll } from '@vueuse/core'
import { state } from '@/state'
import { callbackify } from 'util'

export const getAssetsHomeFile = (fileName: string) => {
  const path = `./images/${fileName}`
  const modules = import.meta.globEager('./images/*')
  return modules[path].default
}

export default defineComponent({
  name: 'PianoRoom',
  data() {
    return {
      shareStatus: false,
      teacherId: 0,
      typeStatus: false,
      courseTxt: '所有课程',
      actions: [
        { name: '所有课程' },
        { name: '未开始', status: 'NOT_START' },
        { name: '进行中', status: 'ING' },
        { name: '已完成', status: 'COMPLETE' },
        { name: '已取消', status: 'CANCEL' }
      ],
      remain: {
        frozenTime: 0,
        remainTime: 0,
        studentCount: 0
      },
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      monthTxt: dayjs().format('YYYY年MM月'),
      month: new Date(),
      params: {
        status: '',
        month: dayjs().format('YYYY-MM'),
        page: 1,
        rows: 20
      },
      timeShow: false,
      timeUpdateStatus: false,
      timeUpdateInfo: {} as any,
      timeUpdateTimer: new Date(),
      studentStatus: false,
      studentConfirm: false,
      studentChangeObject: {} as any,
      background: 'transparent',
      setLoading: false,
      startClassTime: '',
      endClassTime: '',
      minDate: new Date()
    }
  },
  async mounted() {
    await this._init()
    await this.getBaseData()
    await this.getList()
    useEventListener(document, 'scroll', evt => {
      const { y } = useWindowScroll()
      if (y.value > 45) {
        this.background = '#fff'
      } else {
        this.background = 'transparent'
      }
    })
  },
  methods: {
    async _init() {
      try {
        const res = await request.get(
          '/api-teacher/courseSchedule/selectRemainTime'
        )
        // console.log(res)
        const { frozenTime, remainTime, studentCount, teacherId } =
          res.data || {}
        this.remain = {
          frozenTime: frozenTime || 0,
          remainTime: remainTime || 0,
          studentCount: studentCount || 0
        }
        this.teacherId = teacherId
      } catch {}
    },
    async getBaseData() {
      try {
        const result = await request.get(
          '/api-teacher/sysConfig/queryByParamNameList',
          {
            params: {
              paramNames: 'course_start_setting,course_end_setting'
            }
          }
        )
        console.log(result)
        const tempResult = result.data
        for (let i = 0, len = tempResult.length; i < len; i++) {
          if (tempResult[i].paramName === 'course_start_setting') {
            this.startClassTime = tempResult[i].paramValue
              ? tempResult[i].paramValue.split(':')
              : []
          }
          if (tempResult[i].paramName === 'course_end_setting') {
            this.endClassTime = tempResult[i].paramValue
              ? tempResult[i].paramValue.split(':')
              : []
          }
        }
        console.log(this.startClassTime, this.endClassTime)
      } catch {}
    },
    onSearch() {
      this.dataShow = true
      this.loading = false
      this.finished = false
      this.list = []
      this.params.page = 1
      this.getList()
    },
    onSelect(item: any) {
      this.courseTxt = item.name
      this.params.status = item.status || ''
      this._init()
      this.onSearch()
    },
    async getList() {
      try {
        if (this.setLoading) return
        this.setLoading = true
        const res = await request.post(
          '/api-teacher/courseSchedule/selectCourseList',
          {
            data: this.params
          }
        )
        this.setLoading = false
        this.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (this.list.length > 0 && result.pageNo === 1) {
          return
        }
        this.list = this.list.concat(result.rows || [])
        this.finished = result.pageNo >= result.totalPage
        this.params.page = result.pageNo + 1
        this.dataShow = this.list.length > 0
      } catch {
        this.dataShow = false
        this.finished = true
      }
    },
    async onCourseDelete(item: any) {
      try {
        Dialog.confirm({
          title: '提示',
          message: '确定删除该课程吗？',
          confirmButtonColor: 'var(--van-primary)'
        }).then(async () => {
          await request.post('/api-teacher/courseSchedule/deleteCourse', {
            data: {
              courseId: item.courseId
            }
          })
          console.log('删除成功')
          Toast('课程删除成功')
          this._init()
          this.onSearch()
        })
      } catch {}
    },
    onTimeUpdateChange(item: any) {
      try {
        Dialog.confirm({
          title: '提示',
          message: '确定调整该课程吗？',
          confirmButtonColor: 'var(--van-primary)'
        }).then(async () => {
          const { courseId, singleCourseTime } = this.timeUpdateInfo
          const startTime = dayjs(item).format('YYYY-MM-DD HH:mm:ss')
          const endTime = dayjs(item)
            .add(singleCourseTime, 'minute')
            .format('YYYY-MM-DD HH:mm:ss')
          await request.post('/api-teacher/courseSchedule/updateCourseTime', {
            data: {
              courseId,
              startTime,
              endTime
            }
          })
          this.timeUpdateStatus = false
          Toast('课程调整成功')
          this.onSearch()
        })
      } catch {}
    },
    async onStudentChange(item: any) {
      try {
        const { courseId } = this.timeUpdateInfo
        await request.post('/api-teacher/courseSchedule/updateCourseStudent', {
          data: {
            studentIds: item,
            courseId
          }
        })
        this.studentConfirm = false
        Toast('学生调整成功')
        setTimeout(async () => {
          await this._init()
          this.onSearch()
        }, 1000)
      } catch {}
    },
    onTeacherAuth(callBack: any) {
      // 是否达人认证
      // 老师入驻状态 0、未申请 UNPAALY、未申请 DOING、审核中 PASS、通过 UNPASS、不通过,可用值:UNPAALY,DOING,PASS,UNPASS
      const data = state.user.data
      if (data.entryStatus === 'PASS') {
        callBack && callBack()
      } else if (data.entryStatus === 'DOING') {
        Toast('认证审核中，请稍后再试')
      } else {
        this.$router.push('/teacherCert')
      }
    },
    filterDate(type: string, options: any) {
      let value = 0
      if ((this as any).$refs.datetime) {
        const picker = (this as any).$refs.datetime.getPicker()
        value = picker.getValues()[3]?.split('时')[0] || 0
      }
      if (type == 'hour') {
        return options.filter(
          (option: any) =>
            Number(this.startClassTime[0]) <= Number(option) &&
            Number(this.endClassTime[0]) >= Number(option)
        )
      }
      if (type === 'minute') {
        return options.filter(
          (option: any) =>
            (Number(this.startClassTime[1]) <= Number(option) &&
              Number(this.endClassTime[1]) >= Number(option)) ||
            value != Number(this.endClassTime[0])
        )
      }
      return options
    }
  },
  render() {
    return (
      <>
        <div class={styles.roomHeader}>
          <ColHeader
            background={this.background}
            rightText="课程记录"
            onClickRight={() => {
              this.$router.push('/courseRecord')
            }}
            border={false}
          />
          <Row class={styles.countTimer}>
            <Col span={9}>
              <p class={styles.timer}>
                {this.remain.remainTime}
                <span>分钟</span>
              </p>
              <p class={styles.title}>
                <img src={getAssetsHomeFile('icon_last_timer.png')} />
                <span>琴房剩余时长</span>
              </p>
            </Col>
            <Col span={9}>
              <p class={styles.timer}>
                {this.remain.frozenTime}
                <span>分钟</span>
              </p>
              <p class={styles.title}>
                <img src={getAssetsHomeFile('icon_freeze_timer.png')} />
                <span>冻结时长</span>
              </p>
            </Col>
            <Col span={6}>
              <Button
                type="primary"
                round
                size="small"
                class={styles.chargeTimer}
                onClick={() => {
                  this.onTeacherAuth(() => {
                    this.$router.push({
                      path: '/accountRechargeTimer'
                    })
                  })
                }}
              >
                时长充值
                <img src={getAssetsHomeFile('icon_arrow.png')} />
              </Button>
            </Col>
          </Row>

          <CellGroup class={styles.studentList} border={false}>
            <Cell
              title={`我的学员 ${this.remain.studentCount} 人`}
              titleClass={styles.studentCount}
              isLink
              to={'/myStudent'}
              border={false}
            />
            <Cell valueClass={styles.btnGroupInvite}>
              <Button
                color="#E0F7F3"
                round
                block
                onClick={() => {
                  this.onTeacherAuth(() => {
                    this.shareStatus = true
                  })
                }}
              >
                <img src={getAssetsHomeFile('icon_invite_student.png')} />
                邀请学员
              </Button>
              <Button
                color="#E0F7F3"
                round
                block
                onClick={() => {
                  this.onTeacherAuth(() => {
                    this.$router.push('/classArrangement')
                  })
                }}
              >
                <img src={getAssetsHomeFile('icon_class_plan.png')} />
                排课
              </Button>
            </Cell>
          </CellGroup>
        </div>
        <div class={styles.searchList}>
          <div
            class={styles.dataItem}
            onClick={() => {
              this.timeShow = true
            }}
          >
            {this.monthTxt}
            <Icon
              classPrefix="iconfont"
              name="down"
              size={8}
              style={{ marginLeft: '4px' }}
              color="#CCCCCC"
            />
          </div>

          <div
            class={styles.dataItem}
            onClick={() => {
              this.typeStatus = true
            }}
          >
            {this.courseTxt}
            <Icon
              classPrefix="iconfont"
              name="down"
              size={8}
              style={{ marginLeft: '4px' }}
              color="#CCCCCC"
            />
          </div>
        </div>

        {this.dataShow ? (
          <List
            v-model:loading={this.loading}
            finished={this.finished}
            finishedText=" "
            class={[styles.liveList, 'mb12']}
            immediateCheck={false}
            onLoad={this.getList}
          >
            {this.list.map((item: any) => (
              <Course
                item={item}
                operation={item.status === 'NOT_START' ? true : false}
                onCourseDelete={this.onCourseDelete}
                onStudentAdjust={(item: any) => {
                  this.timeUpdateInfo = item
                  this.studentStatus = true
                }}
                onTimeAdjust={(item: any) => {
                  this.timeUpdateInfo = item
                  this.timeUpdateTimer = dayjs(item.startTime).toDate()
                  this.timeUpdateStatus = true
                }}
              />
            ))}
          </List>
        ) : (
          <ColResult btnStatus={false} classImgSize="SMALL" tips="暂无课程" />
        )}

        <Popup position="bottom" v-model:show={this.timeShow} round>
          <div class={styles.picker}>
            <DatetimePicker
              v-model={this.month}
              type="year-month"
              formatter={formatterDate}
              onConfirm={(item: any) => {
                this.monthTxt = dayjs(item).format('YYYY年MM月')
                this.params.month = dayjs(item).format('YYYY-MM')
                this.timeShow = false
                this.onSearch()
              }}
              onCancel={() => (this.timeShow = false)}
            />
          </div>
        </Popup>

        <Popup position="bottom" v-model:show={this.timeUpdateStatus} round>
          <div class={styles.picker}>
            <DatetimePicker
              v-model={this.timeUpdateTimer}
              type="datetime"
              minDate={this.minDate}
              formatter={formatterDate}
              filter={this.filterDate}
              ref="datetime"
              onConfirm={(item: any) => {
                this.onTimeUpdateChange(item)
              }}
              onCancel={() => (this.timeUpdateStatus = false)}
            />
          </div>
        </Popup>

        <ActionSheet
          v-model:show={this.typeStatus}
          actions={this.actions}
          closeOnClickAction
          cancelText="取消"
          onSelect={this.onSelect}
          onCancel={() => {
            this.typeStatus = false
          }}
        />
        <Popup v-model:show={this.shareStatus} round>
          <Share teacherId={this.teacherId} />
        </Popup>

        <Popup v-model:show={this.studentStatus} position="bottom" round>
          {this.studentStatus && (
            <StudentInfo
              courseId={this.timeUpdateInfo.courseId}
              onSubmit={(item: any) => {
                this.studentChangeObject = item
                this.studentStatus = false
                this.studentConfirm = true
              }}
            />
          )}
        </Popup>

        <Popup
          v-model:show={this.studentConfirm}
          position="bottom"
          round
          closeable
        >
          <StudentConfirm
            courseInfo={this.timeUpdateInfo}
            studentObject={this.studentChangeObject}
            onSubmit={async (item: any) => {
              await this.onStudentChange(item)
            }}
          />
        </Popup>
      </>
    )
  }
})
