import {
  ActionSheet,
  ActionSheetAction,
  Button,
  Cell,
  Field,
  Form,
  Popup,
  Radio,
  RadioGroup,
  Stepper,
  Sticky,
  Tag,
  Toast
} from 'vant'
import { computed, defineComponent, onMounted, reactive, ref } from 'vue'
import styles from './index.module.less'
import iconTips from '../../images/icon_tips.png'
import request from '@/helpers/request'
import ColPopup from '@/components/col-popup'
import SelectStudents, { IStudent } from '../select-students'
import Voice from '../../model/voice'
const fieldProps = {
  'is-link': true,
  readonly: true,
  'arrow-direction': 'down'
}
const init = () => {
  return reactive({
    courseName: '', // 课程名称
    classNum: 1, // 课时数
    singleClassTime: '', //单课时长
    freeCourseMinutes: '', // 休息时间
    studentIds: [] as IStudent[], //学员id集合
    subjectId: 0,
    subjectName: '',
    week: '', // 周几
    isSkipHolidays: true,
    startTime: '',
    endTime: ''
  })
}
export let params: any
export default defineComponent({
  name: 'ClassArrangement',
  props: {
    onSubmit: {
      type: Function,
      default: () => {}
    }
  },
  setup(props) {
    const selectStudentShow = ref(false)
    params = init()
    // 设置学员
    const studentRef = ref('') as any
    const students = ref<IStudent[]>([])
    const onSetStudents = (result: IStudent[]) => {
      students.value = result
      params.studentIds = students.value
      selectStudentShow.value = false
    }
    const onDeleteStudent = index => {
      const n = students.value.splice(index, 1)[0]
      studentRef?.value.onDelete(n)
    }

    // 训练声部
    const voiceShow = ref(false)
    const subjectList = ref<[]>([]) // 声部分类
    const getSubjectSelect = async () => {
      try {
        const teachRes = await request.post('/api-teacher/teacher/querySubject')
        subjectList.value = teachRes.data || []
      } catch {}
    }
    onMounted(() => {
      getSubjectSelect()
    })

    //上课时间
    type IClassTimeItem = {
      courseMinutes: string
      freeMinutes: string
      id: number
    }
    const classTime = ref<IClassTimeItem[]>([])
    const classTimeShow = ref(false)
    const getClassTime = async () => {
      try {
        const res = await request.get(
          '/api-teacher/sysConfig/queryByParamNameList',
          {
            params: {
              paramNames:
                'course_start_setting,course_end_setting,piano_time_setting'
            }
          }
        )
        if (res.code === 200) {
          for (let i = 0, len = res.data.length; i < len; i++) {
            if (res.data[i].paramName === 'course_start_setting') {
              params.startTime = res.data[i].paramValue
            }
            if (res.data[i].paramName === 'course_end_setting') {
              params.endTime = res.data[i].paramValue
            }
            if (res.data[i].paramName === 'course_start_setting') {
              params.startTime = res.data[i].paramValue
            }
            if (res.data[i].paramName === 'piano_time_setting') {
              let paramValue: IClassTimeItem[] = []
              try {
                paramValue = JSON.parse(res.data[i].paramValue)
              } catch (error) {}
              classTime.value = paramValue
            }
          }
        }
      } catch (error) {}
    }
    const actions = computed(() => {
      let list: ActionSheetAction[] = []
      classTime.value.forEach((n: IClassTimeItem) => {
        list.push({
          name: n.courseMinutes + '分钟'
        })
      })
      return list
    })
    onMounted(() => {
      getClassTime()
    })

    // 节假日
    const holidays = ref('')
    const getHolidays = async (year: string) => {
      try {
        let result = await request.get(
          '/api-teacher/courseSchedule/selectHoliday',
          { params: { year } }
        )
        holidays.value = result?.data?.holidaysFestivalsJson || ''
      } catch (error) {}
    }
    return () => {
      return (
        <>
          <Form
            scrollToError
            onSubmit={() => {
              if (props.onSubmit) {
                props.onSubmit(params)
              }
            }}
          >
            <div class={styles.container}>
              <Field
                label="课程名称"
                placeholder="请输入课程名称"
                maxlength={20}
                name="courseName"
                v-model={params.courseName}
                rules={[{ required: true, message: '请输入您的课程名称' }]}
              />
              <Field
                label="训练声部"
                placeholder="请选择训练声部"
                {...fieldProps}
                name="subjectName"
                modelValue={params.subjectName}
                onClick={() => (voiceShow.value = true)}
                rules={[{ required: true, message: '请选择训练声部' }]}
              />
              <Cell style={{ padding: 0 }}>
                <Field
                  name="students"
                  class={styles.student}
                  border={false}
                  label="上课学员"
                  placeholder="请选择上课学员"
                  modelValue={students.value.length}
                  {...fieldProps}
                  onClick={() => (selectStudentShow.value = true)}
                  rules={[
                    {
                      required: true,
                      validator: () => {
                        return students.value.length ? true : false
                      },
                      message: '请选择上课学员'
                    }
                  ]}
                />
                {students.value.length ? (
                  <div class={styles.tags}>
                    {students.value.map((n: IStudent, index: number) => (
                      <Tag closeable onClose={() => onDeleteStudent(index)}>
                        {n.userName}
                      </Tag>
                    ))}
                  </div>
                ) : null}
              </Cell>
              <Field
                label="课时数"
                placeholder="请输入课时数"
                v-slots={{
                  input: () => (
                    <Stepper disable-input v-model={params.classNum}></Stepper>
                  )
                }}
              />
              <Field
                class={styles.singleClassTime}
                label="单课时时长"
                {...fieldProps}
                modelValue={params.singleClassTime}
                onClick={() => (classTimeShow.value = true)}
                rules={[{ required: true, message: '请选择单课时时长' }]}
              />
              <Cell
                title="是否跳过节假日"
                v-slots={{
                  value: () => (
                    <RadioGroup
                      class={styles.holdays}
                      v-model={params.isSkipHolidays}
                    >
                      <Radio name={true} style={{ marginRight: '10px' }}>
                        是
                      </Radio>
                      <Radio name={false}>否</Radio>
                    </RadioGroup>
                  )
                }}
              />
              <Cell
                v-slots={{
                  title: () => (
                    <div class={styles.tips}>
                      <img class={styles.icon} src={iconTips} />
                      <span>温馨提醒</span>
                    </div>
                  ),
                  label: () => (
                    <div class={styles.tipsContent}>
                      {/* 1、云酷琴房时长按课程人数扣减（含老师），以45分钟1对1课程师生2人为例，课程结束后将消耗时长：2人*（2人-1）*45分钟=90分钟； */}
                      1、云酷琴房时长按课程学生人数扣减，以45分钟1对2课程为例，课程结束后将消耗时长：2人*45分钟=90分钟；
                      <br />
                      <br />
                      2、每节线上课平台赠送10分钟免费时长，分别为课前5分钟及课后5分钟，赠送时长不计算费用；
                      <br />
                      <br />
                      3、课程消耗时长按排课人数计算，无论实际到课人数是否为排课人数，都会按照排课人数扣费；
                      <br />
                      <br />
                      4、课程结束后费用立即结算；
                      <br />
                      <br />
                      5、琴房时长不足时，您将无法排课，请确保琴房剩余时长充足。
                    </div>
                  )
                }}
              />
              <Button
                block
                type="primary"
                round
                nativeType="submit"
                style={{ margin: '0 auto', width: '90%', marginTop: '20px' }}
                // onClick={() => setParmas()}
              >
                下一步
              </Button>
            </div>
          </Form>

          <Popup
            v-model:show={voiceShow.value}
            position="bottom"
            round
            closeable
            safe-area-inset-bottom
            class={styles.voicePopup}
          >
            <Voice
              class={styles.voicePopupContent}
              single
              selectType={'Radio'}
              subjectList={subjectList.value}
              onChoice={val => {
                const voice: any = subjectList.value.filter(
                  (n: any) => n.id === val
                )[0]
                if (voice) {
                  params.subjectId = voice.id
                  params.subjectName = voice.name
                  voiceShow.value = false
                } else {
                  params.subjectId = 0
                  params.subjectName = ''
                }
              }}
            />
          </Popup>

          {/* 选择学员 */}
          <ColPopup v-model={selectStudentShow.value}>
            <SelectStudents
              ref={studentRef}
              subjectList={subjectList.value}
              onSetStudents={onSetStudents}
            />
          </ColPopup>

          {/* 上课时间 */}
          <ActionSheet
            v-model:show={classTimeShow.value}
            actions={actions.value}
            cancelText="取消"
            closeOnClickAction
            onSelect={(value, index) => {
              params.singleClassTime = classTime.value[index].courseMinutes
              params.freeCourseMinutes = classTime.value[index].freeMinutes
            }}
          />
        </>
      )
    }
  }
})
