import ColUpload from '@/components/col-upload'
import request from '@/helpers/request'
import { verifyNumberIntegerAndFloat } from '@/helpers/toolsValidate'
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElOption,
  ElOptionGroup,
  ElRadioButton,
  ElRadioGroup,
  ElSelect,
  ElDialog,
  ElMessage
} from 'element-plus'
import { defineComponent } from 'vue'
import styles from './index.module.less'

export type BackgroundMp3 = {
  url?: string
  track?: string
}

export default defineComponent({
  name: 'music-operation',
  data() {
    const query = this.$route.query
    return {
      type: query.type || 'create',
      subjectList: [],
      tagList: [],
      submitLoading: false,
      reason: '',
      form: {
        audioType: 'MP3',
        xmlFileUrl: '',
        hasBeat: 0,
        mp3Url: '',
        bgmp3Url: '',
        midiUrl: '',
        musicSheetName: '',
        composer: '',
        musicSubject: null as any,
        tags: [] as string[],
        notation: 0,
        canEvaluate: 1,
        showFingering: 1,
        chargeType: 0,
        musicPrice: '',
        backgroundMp3s: [
          {
            url: '',
            track: ''
          }
        ] as BackgroundMp3[]
      },
      radioList: [], // 选中的人数
      tagStatus: false,
      music_sheet_service_fee: 0
    }
  },
  async mounted() {
    document.title = this.type === 'create' ? '新建曲谱' : '编辑曲谱'
    try {
      await request
        .get('/api-website/sysConfig/queryByParamName', {
          params: {
            paramName: 'music_sheet_service_fee'
          }
        })
        .then(res => (this.music_sheet_service_fee = res.data.paramValue))
      await request.get('/api-website/open/subject/subjectSelect').then(res => {
        this.subjectList = res.data || []
      })

      await request.get('/api-website/open/MusicTag/tree').then(res => {
        this.tagList = res.data || []
      })

      if (this.$route.query.id) {
        this.setDetail(this.$route.query.id as string)
      }
    } catch {}
  },
  methods: {
    async setDetail(id: string) {
      try {
        const res = await request.get(
          '/api-website/open/music/sheet/detail/' + id
        )
        this.form.chargeType = res.data.chargeType === 'FREE' ? 0 : 2
        this.form.showFingering = res.data.showFingering
        this.form.notation = res.data.notation
        this.form.canEvaluate = res.data.canEvaluate
        if (this.form.chargeType) {
          this.form.musicPrice = res.data.musicPrice
        }

        this.form.composer = res.data.composer
        this.form.musicSheetName = res.data.musicSheetName
        this.form.audioType = res.data.audioType
        this.form.musicSubject = Number(res.data.musicSubject)

        const musicTag = res.data.musicTag.split(',')
        this.form.tags = musicTag.map((item: any) => {
          return Number(item)
        })
        this.radioList = this.form.tags as any

        this.form.xmlFileUrl = res.data.xmlFileUrl

        this.form.audioType = res.data.mp3Type

        if (this.form.audioType === 'MP3') {
          this.form.hasBeat = res.data.hasBeat || 0
          this.form.mp3Url = res.data.metronomeUrl || res.data.url
        } else {
          this.form.midiUrl = res.data.midiUrl
        }

        this.form.backgroundMp3s = (res.data.background || []).map(
          (item: any, index: any) => {
            if (index === 0) {
              this.form.bgmp3Url = item.metronomeUrl || item.audioFileUrl
            }
            return {
              url: this.form.hasBeat ? item.metronomeUrl : item.audioFileUrl,
              track: item.track
            }
          }
        )
        this.reason = res.data.reason

        console.log(this.form.bgmp3Url)
      } catch (error) {
        console.log(error)
      }
    },
    createSubmitData() {
      const { form } = this
      const beatType = form.hasBeat ? 'MP3_METRONOME' : 'MP3'
      const mp3Type = form.audioType === 'MP3' ? beatType : 'MIDI'
      return {
        audioType: form.audioType,
        sourceType: 'TEACHER',
        mp3Type,
        hasBeat: form.hasBeat,
        url: form.hasBeat ? '' : form.mp3Url,
        metronomeUrl: form.hasBeat ? form.mp3Url : '',
        showFingering: Number(form.showFingering),
        notation: Number(form.notation),
        musicTag: form.tags.join(','),
        musicSubject: form.musicSubject || undefined,
        musicSheetName: form.musicSheetName,
        midiUrl: form.midiUrl,
        xmlFileUrl: form.xmlFileUrl,
        canEvaluate: Number(form.canEvaluate),
        chargeType: form.chargeType === 0 ? 'FREE' : 'CHARGE',
        composer: form.composer,
        musicPrice: form.musicPrice,
        background: form.backgroundMp3s.map(item => ({
          audioFileUrl: form.hasBeat ? '' : form.bgmp3Url,
          track: item.track,
          metronomeUrl: form.hasBeat ? form.bgmp3Url : ''
        }))
      }
    },
    onFormatter(e: any) {
      e.target.value = verifyNumberIntegerAndFloat(e.target.value)
    },
    onSubmit() {
      ;(this as any).$refs.form.validate(async (valid: any) => {
        if (valid) {
          this.submitLoading = true
          console.log(this.createSubmitData(), 'createSubmitData')
          try {
            if (this.$route.query.id) {
              await request.post('/api-website/music/sheet/update', {
                data: {
                  ...this.createSubmitData(),
                  id: this.$route.query.id
                }
              })
            } else {
              await request.post('/api-website/music/sheet/create', {
                data: this.createSubmitData()
              })
            }
            this.submitLoading = false
            ElMessage.success('上传成功')
            sessionStorage.setItem('musicActiveName', 'DOING')
            this.$router.back()
          } catch (error) {
            this.submitLoading = false
          }
        } else {
          this.$nextTick(() => {
            const isError = document.getElementsByClassName('is-error')
            isError[0].scrollIntoView({
              block: 'center',
              behavior: 'smooth'
            })
          })
          return false
        }
      })
    }
  },
  render() {
    return (
      <div class={styles.form}>
        <div class="text-2xl font-semibold text-black leading-none px-6 py-5 ">
          {this.type === 'create' ? '新建曲谱' : '编辑曲谱'}
        </div>

        <ElForm
          size="large"
          labelPosition="left"
          labelWidth={'150px'}
          model={this.form}
          ref="form"
          class="px-7 py-5"
        >
          <ElFormItem
            label="上传XML"
            prop="xmlFileUrl"
            rules={[{ required: true, message: '请选择MusicXML文件' }]}
          >
            <ColUpload
              v-model:modelValue={this.form.xmlFileUrl}
              bucket={'cloud-coach'}
              accept={'application/xml'}
              uploadType={'file'}
              extraTips="文件最大不能超过5MB"
            />
          </ElFormItem>
          <ElFormItem
            label="是否带节拍器"
            prop="hasBeat"
            rules={[{ required: true, message: '请选择是否带节拍器' }]}
          >
            <ElRadioGroup v-model={this.form.hasBeat}>
              <ElRadioButton label={0} class="mr-3 w-24">
                否
              </ElRadioButton>
              <ElRadioButton label={1} class="w-24">
                是
              </ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem label="伴奏文件" prop="mp3Url">
            <ColUpload
              v-model:modelValue={this.form.mp3Url}
              bucket={'cloud-coach'}
              accept={'.mp3'}
              uploadType={'file'}
              extraTips="文件最大不能超过5MB"
            />
          </ElFormItem>
          <ElFormItem
            label="原音文件"
            prop="bgmp3Url"
            rules={[{ required: true, message: '请选择原音文件' }]}
          >
            <ColUpload
              v-model:modelValue={this.form.bgmp3Url}
              bucket={'cloud-coach'}
              accept={'.mp3'}
              uploadType={'file'}
              extraTips="文件最大不能超过5MB"
            />
          </ElFormItem>
          <ElFormItem
            label="曲目名称"
            prop="musicSheetName"
            rules={[{ required: true, message: '请输入曲目名称' }]}
          >
            <ElInput
              v-model={this.form.musicSheetName}
              placeholder="请选择曲目名称"
            />
          </ElFormItem>
          <ElFormItem
            label="作曲人"
            prop="composer"
            rules={[{ required: true, message: '请输入作曲人' }]}
          >
            <ElInput v-model={this.form.composer} placeholder="请输入作曲人" />
          </ElFormItem>
          <ElFormItem
            label="曲目声部"
            prop="musicSubject"
            rules={[
              { required: true, message: '请选择曲目声部', trigger: 'change' }
            ]}
          >
            <ElSelect
              filterable
              v-model={this.form.musicSubject}
              placeholder="请选择曲目声部"
              class="w-full"
            >
              {this.subjectList.map((group: any) => (
                <ElOptionGroup key={group.id} label={group.name}>
                  {group.subjects &&
                    group.subjects.map((item: any) => (
                      <ElOption
                        key={item.id}
                        value={item.id}
                        label={item.name}
                      />
                    ))}
                </ElOptionGroup>
              ))}
            </ElSelect>
          </ElFormItem>
          <ElFormItem
            label="曲目标签"
            prop="tags"
            rules={[{ required: true, message: '请选择曲目标签' }]}
          >
            <div class="w-full relative">
              <div
                class=" w-full block h-[42px] absolute top-0 left-0 z-10"
                onClick={() => {
                  console.log(111)
                  this.tagStatus = true
                }}
              ></div>
              <ElSelect
                multiple
                v-model={this.form.tags}
                placeholder="请选择曲目标签"
                class="w-full"
              >
                {this.tagList.map((group: any) => (
                  <ElOptionGroup key={group.id} label={group.name}>
                    {group.children &&
                      group.children.map((item: any) => (
                        <ElOption
                          key={item.id}
                          value={item.id}
                          label={item.name}
                        />
                      ))}
                  </ElOptionGroup>
                ))}
              </ElSelect>
            </div>
          </ElFormItem>
          <ElFormItem
            label="是否可以转简谱"
            prop="notation"
            rules={[{ required: true, message: '请选择是否可以转简谱' }]}
          >
            <ElRadioGroup v-model={this.form.notation}>
              <ElRadioButton label={0} class="mr-3 w-24">
                否
              </ElRadioButton>
              <ElRadioButton label={1} class="w-24">
                是
              </ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem
            label="是否评测"
            prop="canEvaluate"
            rules={[{ required: true, message: '请选择是否评测' }]}
          >
            <ElRadioGroup v-model={this.form.canEvaluate}>
              <ElRadioButton label={0} class="mr-3 w-24">
                否
              </ElRadioButton>
              <ElRadioButton label={1} class="w-24">
                是
              </ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem
            label="指法展示"
            prop="showFingering"
            rules={[{ required: true, message: '请选择指法展示' }]}
          >
            <ElRadioGroup v-model={this.form.showFingering}>
              <ElRadioButton label={0} class="mr-3 w-24">
                否
              </ElRadioButton>
              <ElRadioButton label={1} class="w-24">
                是
              </ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem
            label="是否收费"
            prop="chargeType"
            rules={[{ required: true, message: '请选择是否收费' }]}
          >
            <ElRadioGroup v-model={this.form.chargeType}>
              <ElRadioButton label={0} class="mr-3 w-24">
                否
              </ElRadioButton>
              <ElRadioButton label={2} class="w-24">
                是
              </ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
          {this.form.chargeType === 2 && (
            <>
              <ElFormItem
                label="收费价格"
                prop="musicPrice"
                rules={[{ required: true, message: '请输入收费价格' }]}
              >
                <ElInput
                  v-model={this.form.musicPrice}
                  placeholder="请输入收费价格"
                  // @ts-ignore
                  maxlength={5}
                  onKeyup={this.onFormatter}
                  v-slots={{
                    append: () => <span>元</span>
                  }}
                />
              </ElFormItem>

              <ElFormItem>
                <div class={styles.rule}>
                  <p>扣除手续费后该曲目预计收入为：</p>
                  <p>
                    每人：
                    <span>
                      {((parseFloat(this.form.musicPrice || '0') || 0) *
                        (100 - this.music_sheet_service_fee)) /
                        100}
                    </span>
                    元/人
                  </p>
                  <p>您的乐谱收入将在学员购买后结算到您的账户中</p>
                </div>
              </ElFormItem>
            </>
          )}
        </ElForm>
        <div class="text-center pt-6 pb-7">
          <ElButton
            class="!w-44 !h-[48px]"
            round
            onClick={() => {
              this.$router.back()
            }}
          >
            取消
          </ElButton>
          <ElButton
            type="primary"
            class="!w-44 !h-[48px]"
            round
            onClick={this.onSubmit}
            loading={this.submitLoading}
          >
            提交审核
          </ElButton>
        </div>

        <ElDialog
          modelValue={this.tagStatus}
          onUpdate:modelValue={val => (this.tagStatus = val)}
          width="35%"
          title="全部标签"
        >
          {this.tagList.map((item: any, index: number) => (
            <div class={[styles.tags, 'py-2']}>
              <div class="text-sm pb-2">{item.name}</div>
              {item.children.map((child: any) => (
                <ElRadioGroup v-model={this.radioList[index]} class="pb-2">
                  <ElRadioButton label={child.id} class="mr-3 w-24">
                    {child.name}
                  </ElRadioButton>
                </ElRadioGroup>
              ))}
            </div>
          ))}
          <div class="text-center pt-2">
            <ElButton
              class="!w-36 !h-[48px]"
              round
              size="large"
              onClick={() => {
                this.radioList = []
              }}
            >
              重置
            </ElButton>
            <ElButton
              class="!w-36 !h-[48px]"
              round
              size="large"
              type="primary"
              onClick={() => {
                this.form.tags = this.radioList
                this.tagStatus = false
                ;(this as any).$refs.form.clearValidate('tags')
              }}
            >
              确认
            </ElButton>
          </div>
        </ElDialog>
      </div>
    )
  }
})
