import {
  Fragment,
  PropType,
  defineComponent,
  onMounted,
  reactive,
  ref
} from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NForm,
  NFormItem,
  NInputGroup,
  NInputGroupLabel,
  NInputNumber,
  NSpace,
  NTooltip,
  useMessage
} from 'naive-ui';

export default defineComponent({
  name: 'train-update',
  props: {
    /** 初始数据 */
    item: {
      type: Object,
      default: () => ({})
    },
    /** 操作类型 */
    type: {
      type: String as PropType<'train' | 'homework'>,
      default: 'train'
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    // 'practice' | 'evaluation'
    const message = useMessage();
    const forms = reactive({
      id: null as any,
      uploading: false,
      baseMaxScore: 99,
      type: 'PRACTICE',
      musicId: '',
      musicName: '',
      coursewareKnowledgeDetailId: '', // 章节编号
      minScore: null as any,
      maxScore: null as any,
      subjectId: '',
      coverImg: '',
      containAccompaniment: null, // 是否支持评测
      audioPlayTypeArray: [] as any,
      practiceSpeed: null as any, // 练习速度
      practiceTimes: null as any, // 练习时长
      difficulty: 'BEGINNER', // 评测难度
      evaluationSpeed: null as any, // 评测速度
      evaluationScore: null as any, // 评测分数
      firstMeasureIsZero: false as boolean // 标记xml是否是从0小节开始
    });
    const formsRef = ref();

    const onSubmit = async () => {
      formsRef.value?.validate(async (err: any) => {
        if (err) {
          return;
        }
        forms.uploading = true;
        try {
          const params = {
            trainingType: forms.type,
            musicId: forms.musicId,
            musicName: forms.musicName,
            audioPlayTypeArray: forms.audioPlayTypeArray,
            coursewareKnowledgeDetailId: forms.coursewareKnowledgeDetailId,
            subjectId: forms.subjectId,
            id: forms.id,
            coverImg: forms.coverImg,
            containAccompaniment: forms.containAccompaniment,
            trainingConfigJson: ''
          };
          const configJson: any = {};
          configJson.practiceChapterBegin = forms.minScore;
          configJson.practiceChapterEnd = forms.maxScore;
          if (forms.type === 'PRACTICE') {
            configJson.practiceSpeed = forms.practiceSpeed;
            configJson.trainingTimes = forms.practiceTimes;
          } else {
            configJson.evaluateDifficult = forms.difficulty;
            configJson.evaluateSpeed = forms.evaluationSpeed;
            configJson.trainingTimes = forms.evaluationScore;
          }
          configJson.practiceChapterMax = forms.baseMaxScore;
          // 添加是否从0小节开始的标记
          configJson.firstMeasureIsZero = forms.firstMeasureIsZero;
          params.trainingConfigJson = configJson;
          // if (props.type === 'train') {
          // if (forms.id) {
          //   await lessonPreTrainingUpdate(params);
          //   message.success('修改成功');
          // } else {
          //   await lessonPreTrainingAdd(params);
          //   message.success('添加成功');
          // }
          // }

          emit('close');
          emit('confirm', params);
        } catch {
          //
        }
        forms.uploading = false;
      });
    };

    onMounted(() => {
      const item = props.item;
      const playSpeedFloor = Math.floor(item.playSpeed || 0);
      if (item.trainId) {
        forms.id = item.trainId;
        // forms.practiceSpeed = Number(item.practiceSpeed);
        forms.type = item.trainingType;
        forms.minScore = item.practiceChapterBegin;
        forms.maxScore = item.practiceChapterEnd;
        forms.difficulty = item.evaluateDifficult || 'BEGINNER';
        if (item.trainingType === 'PRACTICE') {
          forms.practiceTimes = item.trainingTimes;

          forms.practiceSpeed = item.practiceSpeed
            ? Number(item.practiceSpeed)
            : playSpeedFloor
            ? playSpeedFloor
            : null;
          forms.evaluationSpeed = item.practiceSpeed
            ? Number(item.practiceSpeed)
            : playSpeedFloor
            ? playSpeedFloor
            : null;
        } else {
          forms.evaluationScore = item.trainingTimes;

          forms.evaluationSpeed = item.evaluateSpeed
            ? Number(item.evaluateSpeed)
            : playSpeedFloor
            ? playSpeedFloor
            : null;
          forms.practiceSpeed = item.evaluateSpeed
            ? Number(item.evaluateSpeed)
            : playSpeedFloor
            ? playSpeedFloor
            : null;
        }

        // forms.evaluationSpeed = item.evaluateSpeed;
      } else {
        // xml小节从0开始，最小为0，否则为1
        forms.minScore = item.firstMeasureIsZero ? 0 : 1;
        forms.maxScore = item.practiceChapterMax ? item.practiceChapterMax : 1;
        forms.evaluationSpeed = playSpeedFloor || null;
        forms.practiceSpeed = playSpeedFloor || null;
      }
      forms.firstMeasureIsZero = item.firstMeasureIsZero;
      forms.audioPlayTypeArray = item.audioPlayTypeArray || [];
      forms.containAccompaniment = item.containAccompaniment || null;
      forms.baseMaxScore = item.practiceChapterMax || 99;
      forms.musicId = item.id;
      forms.musicName = item.musicName;
      forms.coursewareKnowledgeDetailId = item.coursewareKnowledgeDetailId;
      forms.subjectId = item.subjectId;
      forms.coverImg = item.coverImg;
    });
    return () => (
      <div class={styles.trainUpdate}>
        <NForm
          ref={formsRef}
          model={forms}
          labelAlign="right"
          labelPlacement="left">
          <NFormItem
            label="训练方式"
            path="type"
            rule={[{ required: true, message: '请选择训练方式' }]}>
            <NSpace>
              <NButton
                secondary
                class={[
                  styles.switch,
                  forms.type === 'PRACTICE' ? styles.active : ''
                ]}
                onClick={() => (forms.type = 'PRACTICE')}>
                练习
              </NButton>

              {!props.item.containAccompaniment ? (
                <NTooltip showArrow={false}>
                  {{
                    trigger: () => (
                      <NButton disabled secondary class={[styles.switch]}>
                        评测
                      </NButton>
                    ),
                    default: () => '该曲目暂不支持评测'
                  }}
                </NTooltip>
              ) : (
                <NButton
                  secondary
                  class={[
                    styles.switch,
                    forms.type === 'EVALUATION' ? styles.active : ''
                  ]}
                  onClick={() => (forms.type = 'EVALUATION')}>
                  评测
                </NButton>
              )}
            </NSpace>
          </NFormItem>
          <div class={styles.scoreGroup}>
            <NFormItem
              label={forms.type === 'PRACTICE' ? '练习小节' : '评测小节'}
              path="minScore"
              rule={[
                {
                  required: true,
                  message: '请输入最小练习小节',
                  trigger: ['blur', 'change'],
                  type: 'number'
                }
              ]}>
              <NInputNumber
                v-model:value={forms.minScore}
                showButton={false}
                min={forms.firstMeasureIsZero ? 0 : 1}
                max={forms.baseMaxScore}
                precision={0}
                placeholder="最小练习小节"
                onUpdate:value={() => {
                  forms.maxScore = null;
                }}
                clearable
              />
            </NFormItem>
            <div
              style={{
                '--n-feedback-height': '24px',
                display: 'flex',
                alignItems: 'center',
                margin: '-2px 2% 0 2%',
                marginBottom: 'var(--n-feedback-height)'
              }}>
              -
            </div>
            <NFormItem
              path="maxScore"
              rule={[
                {
                  required: true,
                  message: '请输入最大练习小节',
                  trigger: ['blur', 'change'],
                  type: 'number'
                }
              ]}>
              <NInputNumber
                v-model:value={forms.maxScore}
                showButton={false}
                precision={0}
                min={forms.minScore || 0}
                max={forms.baseMaxScore}
                placeholder="最大练习小节"
                clearable
              />
            </NFormItem>
          </div>
          {forms.type === 'PRACTICE' && (
            <Fragment key={'PRACTICE'}>
              <NFormItem
                label="练习速度"
                path="practiceSpeed"
                showFeedback={true}
                feedback="速度范围45-270"
                rule={[
                  {
                    required: true,
                    message: '请输入练习速度',
                    trigger: ['blur', 'change'],
                    type: 'number'
                  }
                ]}>
                <NInputNumber
                  min={45}
                  max={270}
                  precision={0}
                  showButton={false}
                  style={{ width: '100%' }}
                  v-model:value={forms.practiceSpeed}
                  onUpdate:value={(val: any) => {
                    forms.evaluationSpeed = val;
                  }}
                  placeholder="练习速度范围45~270"
                  clearable
                />
              </NFormItem>
              <NFormItem
                label="练习时长"
                path="practiceTimes"
                rule={[
                  {
                    required: true,
                    message: '请输入练习时长',
                    trigger: ['blur', 'change'],
                    type: 'number'
                  }
                ]}>
                <NInputGroup>
                  <NInputNumber
                    min={0}
                    max={1000}
                    showButton={false}
                    precision={0}
                    style={{ width: '100%' }}
                    v-model:value={forms.practiceTimes}
                    placeholder="请输入练习时长"
                    clearable
                  />
                  <NInputGroupLabel>分钟</NInputGroupLabel>
                </NInputGroup>
              </NFormItem>

              {/* 这里用不着，用占位的 */}
              <NFormItem label="empty" style={{ opacity: 0 }}>
                <NSpace class={styles.difficultySpace}>
                  <NButton secondary class={[styles.switch]}>
                    占位元素
                  </NButton>
                </NSpace>
              </NFormItem>
            </Fragment>
          )}

          {forms.type === 'EVALUATION' && (
            <Fragment key={'EVALUATION'}>
              <NFormItem
                label="评测难度"
                path="type"
                rule={[{ required: true, message: '请选择评测难度' }]}>
                <NSpace class={styles.difficultySpace}>
                  <NButton
                    secondary
                    class={[
                      styles.switch,
                      forms.difficulty === 'BEGINNER' ? styles.active : ''
                    ]}
                    onClick={() => (forms.difficulty = 'BEGINNER')}>
                    入门级
                  </NButton>
                  <NButton
                    secondary
                    class={[
                      styles.switch,
                      forms.difficulty === 'ADVANCED' ? styles.active : ''
                    ]}
                    onClick={() => (forms.difficulty = 'ADVANCED')}>
                    进阶级
                  </NButton>
                  <NButton
                    secondary
                    class={[
                      styles.switch,
                      forms.difficulty === 'PERFORMER' ? styles.active : ''
                    ]}
                    onClick={() => (forms.difficulty = 'PERFORMER')}>
                    大师级
                  </NButton>
                </NSpace>
              </NFormItem>
              <NFormItem
                label="评测速度"
                path="evaluationSpeed"
                showFeedback={true}
                feedback="速度范围45-270"
                rule={[
                  {
                    required: true,
                    message: '请输入评测速度',
                    trigger: ['blur', 'change'],
                    type: 'number'
                  }
                ]}>
                <NInputNumber
                  min={45}
                  max={270}
                  showButton={false}
                  style={{ width: '100%' }}
                  v-model:value={forms.evaluationSpeed}
                  onUpdate:value={(val: any) => {
                    forms.practiceSpeed = val;
                  }}
                  placeholder="评测速度范围45~270"
                  clearable
                />
              </NFormItem>
              <NFormItem
                label="达标分数"
                path="evaluationScore"
                rule={[
                  {
                    required: true,
                    message: '请输入达标分数',
                    trigger: ['blur', 'change'],
                    type: 'number'
                  }
                ]}>
                <NInputGroup>
                  <NInputNumber
                    min={0}
                    max={100}
                    precision={0}
                    showButton={false}
                    style={{ width: '100%' }}
                    v-model:value={forms.evaluationScore}
                    placeholder="请输入达标分数"
                    clearable
                  />
                  <NInputGroupLabel>分</NInputGroupLabel>
                </NInputGroup>
              </NFormItem>
            </Fragment>
          )}
        </NForm>

        <NSpace class={styles.updateBtnGroup}>
          <NButton strong type="default" round onClick={() => emit('close')}>
            取消
          </NButton>
          <NButton strong type="primary" round onClick={() => onSubmit()}>
            确认
          </NButton>
        </NSpace>
      </div>
    );
  }
});
