import {NButton, NCascader, NForm, NFormItem, NInput, NSpace, useMessage} from 'naive-ui'
import {defineComponent, onMounted, reactive, ref} from 'vue'
import {filterPointCategory} from '@/views/teaching-manage/unit-test'
import {musicSheetCategoriesSave, musicSheetCategoriesUpdate} from "@views/music-library/api";
import UploadFile from '@/components/upload-file';
import styles from './save-categroy-dialog.module.less'

export default defineComponent({
  emits: ['close', 'getList'],
  props: ['activeRow', 'saveMode', 'list'],
  name: 'save-categroy-dialog',
  setup(props, {emit}) {
    const message = useMessage()
    const formRef = ref()
    const parentList = ref([
      {name: '顶级分类', id: 0},
      ...filterPointCategory(props.list, 'musicSheetCategoriesList')
    ] as any)
    const state = reactive({
      loading: false,
      dataList: [] as any,
      btnLoading: false,
      options: {
        enlarge: 2,
        autoCropWidth: 350, //默认生成截图框宽度
        autoCropHeight: 140 //默认生成截图框高度
      },
      messageTip: '请上传尺寸为700*280大小5M以内的JPG、PNG图片'
    })
    const forms = reactive({
      id: '',
      name: '',
      coverImg: '',
      enable: true,
      parentId: '0'
    } as any)

    const onSubmit = async () => {
      formRef.value?.validate(async (errors: any) => {
        if (errors) {
          return;
        }
        state.btnLoading = true
        try {
          if(props.saveMode==='add'){
            const {data} = await musicSheetCategoriesSave({...forms})
            emit('getList')
            message.success('添加成功')
          }else {
            const {data} = await musicSheetCategoriesUpdate({...forms})
            emit('getList')
            message.success('修改成功')
          }
        } catch (error) {
        }
        state.btnLoading = false
      })
    }

    onMounted(() => {
      if (props.saveMode === 'add') {
        // 添加子分类
        if (props.activeRow && props.activeRow.id) {
          forms.parentId = props?.activeRow.id + ''
        }
      } else {
        for (let key in props?.activeRow) {
          forms[key] = props?.activeRow[key]
        }
        if(props?.activeRow.currentLevel > 1) {
          state.options.autoCropWidth = 210
          state.options.autoCropHeight = 268
          state.messageTip = '请上传尺寸为210*268大小5M以内的JPG、PNG图片'
        }
      }
    })
    return () => (
        <div>
          <NForm ref={formRef} model={forms}>
            {props.saveMode === 'add' && props.activeRow && (
                <NFormItem label="父级分类" path="parentId">
                  <NCascader
                      placeholder="请选择父级分类"
                      v-model:value={forms.parentId}
                      options={parentList.value}
                      checkStrategy="all"
                      expandTrigger="hover"
                      childrenField="musicSheetCategoriesList"
                      valueField="id"
                      labelField="name"
                      disabled={true}
                  />
                </NFormItem>
            )}

            <NFormItem
                label="分类名称"
                rule={[
                  {
                    required: true,
                    message: '请输入分类名称',
                    trigger: ['blur', 'input']
                  }
                ]}
                path="name"
            >
              <NInput
                  v-model:value={forms.name}
                  placeholder="请输入分类名称"
                  maxlength={25}
                  showCount
                  clearable
              ></NInput>
            </NFormItem>

            <NFormItem
            label="封面图"
            path="coverImg"
            rule={[
              {
                required: true,
                message: '请上传封面图',
                trigger: ['input', 'blur']
              }
            ]}
          >
            <UploadFile
              v-model:fileList={forms.coverImg}
              accept=".jpg,.jpeg,.png"
              cropper
              size={5}
              class={styles.updateFile}
              bucketName="news-info"
              options={state.options}
              tips={state.messageTip}
            />
          </NFormItem>
          </NForm>
          <NSpace justify="end">
            <NButton type="default" onClick={() => emit('close')}>
              取消
            </NButton>
            <NButton
                type="primary"
                onClick={() => onSubmit()}
                loading={state.btnLoading}
                disabled={state.btnLoading}
            >
              确认
            </NButton>
          </NSpace>
        </div>
    )
  }
})
