import { PropType, defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NForm,
  NFormItem,
  NInputGroup,
  NInputGroupLabel,
  NInputNumber,
  NSpace,
  useMessage
} from 'naive-ui';
import {
  lessonPreTrainingAdd,
  lessonPreTrainingUpdate
} from '/src/views/prepare-lessons/api';

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: '',
      practiceSpeed: null as any, // 练习速度
      practiceTimes: null as any, // 练习时长
      difficulty: 'BEGINNER', // 评测难度
      evaluationSpeed: null as any, // 评测速度
      evaluationScore: null as any // 评测分数
    });
    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,
            coursewareKnowledgeDetailId: forms.coursewareKnowledgeDetailId,
            subjectId: forms.subjectId,
            id: forms.id,
            coverImg: forms.coverImg,
            trainingConfigJson: ''
          };
          const configJson: any = {};
          if (forms.type === 'PRACTICE') {
            configJson.practiceChapterBegin = forms.minScore;
            configJson.practiceChapterEnd = forms.maxScore;
            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;
          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;
      if (item.trainId) {
        forms.id = item.trainId;
        forms.minScore = item.practiceChapterBegin;
        forms.maxScore = item.practiceChapterEnd;
        forms.practiceSpeed = item.practiceSpeed;
        forms.type = item.trainingType;
        if (item.trainingType === 'PRACTICE') {
          forms.practiceTimes = item.trainingTimes;
        } else {
          forms.evaluationScore = item.trainingTimes;
        }
        forms.difficulty = item.evaluateDifficult || 'BEGINNER';
        forms.evaluationSpeed = item.evaluateSpeed;
      } else {
        forms.minScore = 1;
        forms.maxScore = item.practiceChapterMax ? item.practiceChapterMax : 1;
      }
      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>
              <NButton
                secondary
                class={[
                  styles.switch,
                  forms.type === 'EVALUATION' ? styles.active : ''
                ]}
                onClick={() => (forms.type = 'EVALUATION')}>
                评测
              </NButton>
            </NSpace>
          </NFormItem>
          {forms.type === 'PRACTICE' && (
            <>
              <div class={styles.scoreGroup}>
                <NFormItem
                  label="练习小节"
                  path="minScore"
                  rule={[
                    {
                      required: true,
                      message: '请输入最小练习小节',
                      trigger: ['blur', 'change'],
                      type: 'number'
                    }
                  ]}>
                  <NInputNumber
                    v-model:value={forms.minScore}
                    showButton={false}
                    min={1}
                    max={forms.baseMaxScore}
                    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}
                    min={forms.minScore || 1}
                    max={forms.baseMaxScore}
                    placeholder="最大练习小节"
                    clearable
                  />
                </NFormItem>
              </div>
              <NFormItem
                label="练习速度"
                path="practiceSpeed"
                rule={[
                  {
                    required: true,
                    message: '请输入练习速度',
                    trigger: ['blur', 'change'],
                    type: 'number'
                  }
                ]}>
                <NInputNumber
                  min={60}
                  max={270}
                  showButton={false}
                  style={{ width: '100%' }}
                  v-model:value={forms.practiceSpeed}
                  placeholder="练习速度范围60~270"
                  clearable
                />
              </NFormItem>
              <NFormItem
                label="练习时长"
                path="practiceTimes"
                rule={[
                  {
                    required: true,
                    message: '请输入练习时长',
                    trigger: ['blur', 'change'],
                    type: 'number'
                  }
                ]}>
                <NInputGroup>
                  <NInputNumber
                    min={0}
                    showButton={false}
                    style={{ width: '100%' }}
                    v-model:value={forms.practiceTimes}
                    placeholder="请输入练习时长"
                    clearable
                  />
                  <NInputGroupLabel>分钟</NInputGroupLabel>
                </NInputGroup>
              </NFormItem>
            </>
          )}

          {forms.type === 'EVALUATION' && (
            <>
              <NFormItem
                label="评测难度"
                path="type"
                rule={[{ required: true, message: '请选择评测难度' }]}>
                <NSpace>
                  <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"
                rule={[
                  {
                    required: true,
                    message: '请输入评测速度',
                    trigger: ['blur', 'change'],
                    type: 'number'
                  }
                ]}>
                <NInputNumber
                  min={60}
                  max={270}
                  showButton={false}
                  style={{ width: '100%' }}
                  v-model:value={forms.evaluationSpeed}
                  placeholder="评测速度范围60~270"
                  clearable
                />
              </NFormItem> */}
              <NFormItem
                label="合格分数"
                path="evaluationScore"
                rule={[
                  {
                    required: true,
                    message: '请输入合格分数',
                    trigger: ['blur', 'change'],
                    type: 'number'
                  }
                ]}>
                <NInputGroup>
                  <NInputNumber
                    min={0}
                    showButton={false}
                    style={{ width: '100%' }}
                    v-model:value={forms.evaluationScore}
                    placeholder="请输入合格分数"
                    clearable
                  />
                  <NInputGroupLabel>分</NInputGroupLabel>
                </NInputGroup>
              </NFormItem>
            </>
          )}

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