import { useUserStore } from '@/store/modules/user'
import {
  FormItemRule,
  NAlert,
  NButton,
  NDivider,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NInputNumber,
  NSpace,
  NTabPane,
  NTabs,
  useMessage
} from 'naive-ui'
import { defineComponent, reactive } from 'vue'
import { lessonTrainingDetailBatchInsert, lessonTrainingDetailTempBatchUpSet } from '../../api'
import ColVideo from '@/components/col-video'

export default defineComponent({
  name: 'addTrainStandard',
  props: {
    item: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['handleAdd', 'close'],
  setup(props, { emit }) {
    console.log('🚀 ~ props', props.item)
    const userStore = useUserStore()
    const prefix = /(localhost|192)/.test(location.host)
      ? 'https://ponline.colexiu.com'
      : location.origin //
    const src =
      prefix +
      `/orchestra-music-score/?_t=${Date.now()}&id=${
        props.item.content
      }&modelType=practice&Authorization=${userStore.getToken}`
    const message = useMessage()
    const state = reactive({
      current: 1,
      list: [
        {
          id: 1,
          name: '单团学生',
          materialType: props.item?.type,
          practiceTimes: '',
          startSection: '',
          endSection: '',
          speed: '',
          practiceDuration: ''
        },
        {
          id: 2,
          name: '双团学生',
          materialType: props.item?.type,
          practiceTimes: '',
          startSection: '',
          endSection: '',
          speed: '',
          practiceDuration: ''
        },
        {
          id: 3,
          name: '多团学生',
          materialType: props.item?.type,
          practiceTimes: '',
          startSection: '',
          endSection: '',
          speed: '',
          practiceDuration: ''
        }
      ]
    })

    const init = () => {
      if (Array.isArray(props?.item?.standards)) {
        for (let i = 0; i < props.item.standards.length; i++) {
          let trainingConfigJson: any = {}
          try {
            trainingConfigJson = JSON.parse(props.item.standards[i].trainingConfigJson)
          } catch (error) {}
          state.list[i].practiceTimes = trainingConfigJson.practiceTimes
          state.list[i].startSection = trainingConfigJson.startSection
          state.list[i].endSection = trainingConfigJson.endSection
          state.list[i].speed = trainingConfigJson.speed
          state.list[i].practiceDuration = trainingConfigJson.practiceDuration
        }
      }
    }
    init()
    const handleAdd = async () => {
      if (props.item?.type == 'VIDEO') {
        for (let i = 0; i < state.list.length; i++) {
          if (!state.list[i].practiceTimes) {
            message.error(`请完善${state.list[i].name}的观看次数`)
            return
          }
          if (!/^\+?[1-9]\d*$/.test(state.list[i].practiceTimes)) {
            message.error(`请输入${state.list[i].name}正确的数字观看次数`)
            return
          }
        }
      }
      if (props.item?.type == 'SONG') {
        for (let i = 0; i < state.list.length; i++) {
          if (
            !state.list[i].startSection ||
            !state.list[i].endSection ||
            !state.list[i].speed ||
            !state.list[i].practiceDuration
          ) {
            message.error(`请完善${state.list[i].name}的训练要求`)
            return
          }
          if (
            !/^\+?[1-9]\d*$/.test(state.list[i].startSection) ||
            !/^\+?[1-9]\d*$/.test(state.list[i].endSection) ||
            !/^\+?[1-9]\d*$/.test(state.list[i].speed) ||
            !/^\+?[1-9]\d*$/.test(state.list[i].practiceDuration)
          ) {
            message.error(`请输入${state.list[i].name}正确的数字`)
            return
          }
        }
      }
      let list = state.list.map((n: any, i: number) => {
        return {
          studentLevel: i + 1,
          lessonTrainingId: props.item?.lessonTrainingId,
          lessonTrainingDetailId: props.item?.id,
          trainingConfigJson: JSON.stringify({
            materialType: n.materialType,
            practiceTimes: n.practiceTimes,
            startSection: n.startSection,
            endSection: n.endSection,
            speed: n.speed,
            practiceDuration: n.practiceDuration
          })
        }
      })
      console.log('🚀 ~ list', list)
      try {
        const res: any = await lessonTrainingDetailTempBatchUpSet(list)
        message.success('保存成功')
      } catch (error) {}
      emit('handleAdd')
    }

    /** 云教练选段 */
    window.addEventListener('message', (event: MessageEvent) => {
      console.log(event.data)
      const data = event.data
      if (data.api === 'admin-selectMusicMeasure') {
        state.list.forEach((n: any) => {
          n.startSection = n.startSection && !data.change ? n.startSection : data.start + ''
          n.endSection = n.endSection && !data.change ? n.endSection : data.end + ''
          n.speed = n.speed && !data.change ? n.speed : data.speed + ''
        })
      }
    })
    console.log(state.list, 'state.list')
    return () => (
      <div>
        <div>{props.item?.materialName}</div>
        {props.item?.type == 'VIDEO' && (
          <div>
            {/* <video style={{ width: '100%' }} src={props.item.content} controls></video> */}
            <ColVideo styleValue={{ width: '100%', height: '375px' }} src={props.item.content} />

            {state.list.map((item: any) => {
              return (
                <NForm labelPlacement="left">
                  <NAlert
                    title={item.name}
                    showIcon={false}
                    bordered={true}
                    style={{ marginBottom: '12px' }}
                  />
                  <NFormItem required label="观看次数">
                    <NInputNumber
                      placeholder="请输入观看次数"
                      showButton={false}
                      v-model:value={item.practiceTimes}
                      min={0}
                    />
                  </NFormItem>
                </NForm>
              )
            })}
          </div>
        )}
        {props.item?.type === 'SONG' && (
          <div>
            <iframe width={'667px'} height={'375px'} frameborder="0" src={src}></iframe>
            <NForm labelPlacement="left">
              {state.list.map((item: any) => {
                return (
                  <>
                    <NAlert
                      title={item.name}
                      showIcon={false}
                      bordered={true}
                      style={{ marginBottom: '12px' }}
                    />
                    <NFormItem required label="练习小节">
                      <NInputNumber
                        showButton={false}
                        placeholder="开始小节"
                        v-model:value={item.startSection}
                        min={0}
                        style={{ width: '180px' }}
                      />
                      ~
                      <NInputNumber
                        showButton={false}
                        placeholder="结束小节"
                        v-model:value={item.endSection}
                        min={0}
                        style={{ width: '180px' }}
                      />
                    </NFormItem>
                    <NFormItem label="练习速度" required>
                      <NInputNumber
                        showButton={false}
                        placeholder="练习速度"
                        v-model:value={item.speed}
                        min={0}
                        style={{ width: '180px' }}
                      />
                    </NFormItem>
                    <NFormItem label="练习时长" required>
                      <NInputNumber
                        v-slots={{ suffix: () => '分钟' }}
                        v-model:value={item.practiceDuration}
                        showButton={false}
                        min={0}
                        style={{ width: '180px' }}
                      ></NInputNumber>
                    </NFormItem>
                  </>
                )
              })}
            </NForm>
            {/* <NTabs type="segment" v-model:value={state.current}>
              {state.list.map((item: any) => {
                return (
                  <NTabPane name={item.id} tab={item.name}>
                    <NSpace>
                      <NFormItem required label="练习小节">
                        <NInput placeholder="开始小节" v-model:value={item.startSection} />
                        ~
                        <NInput placeholder="结束小节" v-model:value={item.endSection} />
                      </NFormItem>
                      <NFormItem label="练习速度" required>
                        <NInput v-model:value={item.speed}></NInput>
                      </NFormItem>
                    </NSpace>
                    <NFormItem label="练习时长" required>
                      <NInput
                        style={{ width: '50%' }}
                        v-slots={{ suffix: () => '分钟' }}
                        v-model:value={item.practiceDuration}
                      ></NInput>
                    </NFormItem>
                  </NTabPane>
                )
              })}
            </NTabs> */}
          </div>
        )}
        {props.item?.type === 'IMG' && (
          <div>
            <NImage width={200} height={200} src={props?.item?.content} />
          </div>
        )}
        <NSpace justify="end">
          <NButton onClick={() => emit('close')}>取消</NButton>
          <NButton type="primary" onClick={() => handleAdd()}>
            确认
          </NButton>
        </NSpace>
      </div>
    )
  }
})
