import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NScrollbar,
  NSelect,
  NSpace,
  useMessage
} from 'naive-ui';
import { TransitionGroup, defineComponent, reactive, ref } from 'vue';
import styles from './index.module.less';
import UploadFile from '@/components/upload-file';
import { nextTick } from 'vue';
import { scrollToErrorForm } from '@/utils';
import { api_lessonCoursewareSave } from '../../api';
import iconUpload from '../../images/icon-upload.png';
import iconAdd from '../../images/icon-add.svg';
import iconMenu from '../../images/icon-menu.png';
import btnAdd from '../../images/btn-add.svg';
import btnDelete from '../../images/btn-delete.svg';
import btnUp from '../../images/btn-up.svg';
import btnDown from '../../images/btn-down.svg';
import btnRemove from '../../images/btn-remove.svg';
export const BOOK_DATA = {
  grades: [
    { label: '一年级', value: 1 },
    { label: '二年级', value: 2 },
    { label: '三年级', value: 3 },
    { label: '四年级', value: 4 },
    { label: '五年级', value: 5 },
    { label: '六年级', value: 6 },
    { label: '七年级', value: 7 },
    { label: '八年级', value: 8 },
    { label: '九年级', value: 9 }
  ],
  bookTypes: [
    { label: '上册', value: 'LAST' },
    { label: '下册', value: 'NEXT' }
  ]
};

/** 添加单元 */
const createLesson = () => {
  return {
    key: 'item' + Date.now(),
    name: '', // 单元名称
    lessonTargetDesc: '', // 课时目标描述
    knowledgeList: [
      {
        key: Date.now() + '' + 0,
        name: '' // 章节名称
      }
    ] // 章节信息
  };
};
const initState = () => ({
  id: null, // 教材id
  name: '',
  currentGradeNum: null,
  bookType: null, // 上下册
  coverImg: '', // 封面
  enableFlag: true, // 状态
  type: 'COURSEWARE', // 教材类型：COURSEWARE,THEORY,可用值:COURSEWARE,THEORY
  lessonList: [createLesson()] // 单元列表
});

export default defineComponent({
  name: 'addNatural',
  emits: ['close'],
  setup(props, { emit }) {
    const message = useMessage();
    const data = reactive({
      uploading: false
    });
    const formRef = ref();
    const form = reactive(initState());
    const handleSave = () => {
      formRef.value?.validate((err: any) => {
        if (err) {
          nextTick(scrollToErrorForm);
          return;
        }
        handleSubmit();
      });
    };
    const handleSubmit = async () => {
      data.uploading = true;
      try {
        await api_lessonCoursewareSave(form);
        Object.assign(form, initState());
        message.success('添加成功');
        emit('close', true);
      } catch {
        //
      }
      data.uploading = false;
    };
    return () => (
      <div class={styles.container}>
        <NScrollbar style={{ 'max-height': '55vh' }}>
          <NForm
            ref={formRef}
            labelPlacement="left"
            labelWidth={120}
            model={form}>
            <div class={styles.topForms}>
              <NFormItem
                path="coverImg"
                rule={[
                  {
                    required: true,
                    message: '请上传教材封面',
                    trigger: ['change']
                  }
                ]}>
                <UploadFile
                  cropper
                  // tips="建议尺寸：210*297, 文件大小: 5MB以内;"
                  v-model:fileList={form.coverImg}
                  showType="custom"
                  size={2}
                  accept=".jpg,jpeg,.png"
                  options={{
                    autoCropWidth: 210,
                    autoCropHeight: 297,
                    fixedBox: true
                  }}>
                  {{
                    custom: () => (
                      <div class={styles.uploadContent}>
                        <img src={iconUpload} class={styles.iconUpload} />
                        <p>请上传教材封面</p>
                      </div>
                    )
                  }}
                </UploadFile>
              </NFormItem>
              <div class={styles.topFormInput}>
                <NFormItem
                  style={{ minWidth: '360px' }}
                  path="name"
                  rule={[
                    {
                      required: true,
                      message: '请输入教材名称',
                      trigger: ['blur', 'change']
                    }
                  ]}>
                  <NInput
                    placeholder="请输入教材名称"
                    maxlength={25}
                    v-model:value={form.name}
                    clearable></NInput>
                </NFormItem>
                <NFormItem
                  path="currentGradeNum"
                  rule={{
                    required: true,
                    message: '请选择年级',
                    trigger: 'change',
                    type: 'number'
                  }}>
                  <NSelect
                    style={{ minWidth: '360px' }}
                    placeholder="请选择年级"
                    options={BOOK_DATA.grades}
                    v-model:value={form.currentGradeNum}
                    clearable
                    filterable
                  />
                </NFormItem>
                <NFormItem
                  path="bookType"
                  style={{ width: '360px' }}
                  rule={{
                    required: true,
                    message: '请选择册别',
                    trigger: 'change'
                  }}>
                  <NSelect
                    placeholder="请选择册别"
                    options={BOOK_DATA.bookTypes}
                    v-model:value={form.bookType}
                    clearable
                  />
                </NFormItem>
              </div>
            </div>

            <div class={styles.menuTitle}>
              <img src={iconMenu} class={styles.iconMenu} />
              目录
            </div>
            <TransitionGroup name="list" tag="div">
              {form.lessonList.map((item, index) => {
                return (
                  <NSpace
                    class={styles.lessonItem}
                    wrap={false}
                    wrapItem={false}
                    align="start"
                    key={item.key}>
                    <NFormItem
                      label="单元名称"
                      labelPlacement="top"
                      path={`lessonList[${index}].name`}
                      rule={{
                        required: true,
                        message: '填写单元名称',
                        trigger: ['blur', 'change']
                      }}>
                      <NInput
                        placeholder="填写单元名称"
                        maxlength={25}
                        v-model:value={item.name}
                        clearable></NInput>
                    </NFormItem>
                    <TransitionGroup name="list" tag="div">
                      {item.knowledgeList.map((know, knowIndex) => {
                        return (
                          <NFormItem
                            style={{
                              '--n-label-height': knowIndex === 0 ? '26px' : '0'
                            }}
                            labelPlacement="top"
                            label={knowIndex === 0 ? '章节名称' : ''}
                            key={know.key}
                            path={`lessonList[${index}].knowledgeList[${knowIndex}].name`}
                            rule={{
                              required: true,
                              message: '填写章节名称',
                              trigger: ['blur', 'change']
                            }}>
                            <NSpace
                              wrap={false}
                              align="center"
                              class={styles.btnGroupAll}
                              wrapItem={false}>
                              <NInput
                                maxlength={25}
                                placeholder="填写章节名称"
                                v-model:value={know.name}
                                clearable></NInput>
                              <NButton
                                quaternary
                                circle
                                onClick={() => {
                                  item.knowledgeList.splice(knowIndex + 1, 0, {
                                    name: '',
                                    key: Date.now() + '' + knowIndex
                                  });
                                }}>
                                {{
                                  icon: () => (
                                    <img src={btnAdd} class={styles.btnImg} />
                                  )
                                }}
                              </NButton>
                              <NButton
                                quaternary
                                circle
                                disabled={item.knowledgeList.length < 2}
                                onClick={() => {
                                  item.knowledgeList.splice(knowIndex, 1);
                                }}>
                                {{
                                  icon: () => (
                                    <img
                                      src={btnDelete}
                                      class={styles.btnImg}
                                    />
                                  )
                                }}
                              </NButton>
                              <NButton
                                quaternary
                                circle
                                disabled={knowIndex === 0}
                                onClick={() => {
                                  if (knowIndex === 0) return;
                                  const tmp = item.knowledgeList[knowIndex - 1];
                                  item.knowledgeList[knowIndex - 1] =
                                    item.knowledgeList[knowIndex];
                                  item.knowledgeList[knowIndex] = tmp;
                                }}>
                                {{
                                  icon: () => (
                                    <img src={btnUp} class={styles.btnImg} />
                                  )
                                }}
                              </NButton>
                              <NButton
                                quaternary
                                circle
                                disabled={
                                  knowIndex === item.knowledgeList.length - 1
                                }
                                onClick={() => {
                                  if (
                                    knowIndex ===
                                    item.knowledgeList.length - 1
                                  )
                                    return;
                                  const tmp = item.knowledgeList[knowIndex + 1];
                                  item.knowledgeList[knowIndex + 1] =
                                    item.knowledgeList[knowIndex];
                                  item.knowledgeList[knowIndex] = tmp;
                                }}>
                                {{
                                  icon: () => (
                                    <img src={btnDown} class={styles.btnImg} />
                                  )
                                }}
                              </NButton>
                            </NSpace>
                          </NFormItem>
                        );
                      })}
                    </TransitionGroup>
                    <NButton
                      class={styles.closeBtn}
                      secondary
                      circle
                      size="small"
                      disabled={form.lessonList.length < 2}
                      onClick={() => {
                        form.lessonList.splice(index, 1);
                      }}>
                      <img src={btnRemove} />
                    </NButton>
                  </NSpace>
                );
              })}
            </TransitionGroup>
            <div class={styles.line}></div>
            <NButton
              block
              class={styles.addUnitBtn}
              ghost
              color="#198CFE"
              onClick={() => {
                form.lessonList.push(createLesson());
              }}>
              {{
                icon: () => <img src={iconAdd} />,
                default: () => '新增单元'
              }}
            </NButton>
          </NForm>
        </NScrollbar>
        <NSpace class={styles.btnGroup} justify="center">
          <NButton round onClick={() => emit('close')}>
            取消
          </NButton>
          <NButton
            round
            loading={data.uploading}
            type="primary"
            onClick={() => handleSave()}>
            保存
          </NButton>
        </NSpace>
      </div>
    );
  }
});
