import ColCropper from '@/components/col-cropper'
import styles from './index.module.less'
import request from '@/helpers/request'
import {
  verifiyNumberInteger,
  verifyNumberIntegerAndFloat
} from '@/helpers/toolsValidate'
import {
  ElButton,
  ElCol,
  ElForm,
  ElFormItem,
  ElImage,
  ElInput,
  ElOption,
  ElRadio,
  ElRadioGroup,
  ElRow,
  ElSelect,
  ElTabPane,
  ElTabs
} from 'element-plus'
import { defineComponent } from 'vue'
import { createState } from '../createState'
import { scrollAnimation } from '@/util/scroll'

export default defineComponent({
  name: 'course-info',
  data() {
    return {
      url: '',
      calcRatePrice: 0 as any,
      calcSingleRatePrice: 0 as any
    }
  },
  computed: {
    subjectList() {
      // 学科列表
      return createState.subjectList || []
    }
  },
  async mounted() {
    try {
      // 获取手续费和分钟数
      let config = await request.get(
        '/api-website/sysConfig/queryByParamNameList',
        {
          params: {
            paramNames: 'live_service_rate,live_time_setting'
          }
        }
      )
      let configData = config.data || []
      configData.forEach((item: any) => {
        if (item.paramName === 'live_time_setting') {
          let mins = item.paramValue ? JSON.parse(item.paramValue) : []
          let tempArr = [] as any
          mins.forEach((item: any) => {
            tempArr.push({
              ...item,
              name: item.courseMinutes
            })
          })
          createState.minutes = [...tempArr]
        }
        if (item.paramName === 'live_service_rate') {
          createState.rate = item.paramValue
        }
      })

      let teacher = await request.post('/api-website/teacher/querySubject')
      createState.subjectList = teacher.data || []
    } catch (err: any) {
      console.log(err)
    }
  },
  methods: {
    // onChoice(id: number) {
    //   createState.live.subjectId = id
    //   this.subjectStatus = false
    // },
    onFormaterCourse(e: any) {
      e.target.value = verifiyNumberInteger(e.target.value)
      let rate = createState.rate || 0
      let nums = createState.live.courseNum
      let tempPrice = createState.live.coursePrice || 0
      this.calcSingleRatePrice = nums
        ? ((tempPrice / nums) * (1 - rate / 100)).toFixed(2)
        : 0
    },
    onFormatter(e: any) {
      e.target.value = verifyNumberIntegerAndFloat(e.target.value)

      // 计算手续费
      let rate = createState.rate || 0
      let price = e.target.value || 0
      this.calcRatePrice = (price - (rate / 100) * price).toFixed(2)

      let nums = createState.live.courseNum
      // let tempPrice = createState.live.coursePrice || 0
      this.calcSingleRatePrice = nums
        ? ((price / nums) * (1 - rate / 100)).toFixed(2)
        : 0
    },
    tabChange(name: number) {
      ;(this as any).$refs.form.clearValidate('lessonCoverTemplateUrl')
      ;(this as any).$refs.form.clearValidate('lessonCoverUrl')
      createState.tabIndex = name
    },
    selectImg(val: string) {
      // createState.live.lessonCoverUrl = ''
      // createState.live.lessonCoverTemplateUrl = val
    }
  },
  render() {
    return (
      <>
        <ElForm
          class="px-[200px] pb-10 pt-7"
          size="large"
          ref="form"
          labelWidth={'100px'}
          labelPosition="left"
          model={createState.live}
        >
          <ElFormItem
            label="课程名称"
            prop="name"
            rules={[
              {
                required: true,
                message: '请输入课程名称'
              }
            ]}
          >
            <ElInput
              v-model={createState.live.name}
              placeholder="请输入课程名称"
            />
          </ElFormItem>
          <ElFormItem
            label="课程声部"
            prop="subjectId"
            rules={[
              {
                required: true,
                message: '请选择课程声部'
              }
            ]}
          >
            <ElSelect
              class="w-full"
              v-model={createState.live.subjectId}
              placeholder="请选择课程声部"
            >
              {createState.subjectList.map((item: any) => (
                <ElOption key={item.id} value={item.id} label={item.name} />
              ))}
            </ElSelect>
          </ElFormItem>
          <ElFormItem
            label="课程介绍"
            prop="courseIntroduce"
            rules={[
              {
                required: true,
                message: '请输入课程介绍'
              }
            ]}
          >
            <ElInput
              placeholder="请输入课程介绍"
              v-model={createState.live.courseIntroduce}
              type="textarea"
              // @ts-ignore
              maxlength={200}
              rows={4}
              showWordLimit
            />
          </ElFormItem>

          <ElFormItem
            label="课时数"
            prop="courseNum"
            rules={[
              {
                required: true,
                message: '请输入课时数'
              }
            ]}
          >
            <ElInput
              placeholder="请输入课时数"
              v-model={createState.live.courseNum}
              // @ts-ignore
              onKeyup={this.onFormaterCourse}
              maxlength={3}
              v-slots={{
                append: () => <span class="text-base text-[#333]">课时</span>
              }}
            />
          </ElFormItem>
          <ElFormItem
            label="单课时长"
            prop="singleMins"
            rules={[
              {
                required: true,
                message: '请选择单课时长'
              }
            ]}
          >
            <ElSelect
              class="w-full"
              v-model={createState.live.singleMins}
              placeholder="请选择单课时长"
            >
              {createState.minutes.map((item: any) => (
                <ElOption
                  key={item.courseMinutes}
                  value={item.courseMinutes}
                  label={item.name}
                />
              ))}
            </ElSelect>
          </ElFormItem>

          <ElFormItem
            label="课程组售价"
            prop="coursePrice"
            rules={[
              {
                required: true,
                message: '请输入课程组售价'
              }
            ]}
          >
            <ElInput
              placeholder="请输入课程组售价"
              v-model={createState.live.coursePrice}
              // @ts-ignore
              onKeyup={this.onFormatter}
              maxlength={9}
              v-slots={{
                append: () => <span class="text-base text-[#333]">元</span>
              }}
            />
          </ElFormItem>
          <div class="text-sm text-[#999] pl-[100px] leading-relaxed pb-2">
            <p>扣除手续费后您的课程预计收入为：</p>
            <p>
              单课时
              <span class="px-1 text-[#FF4E19]">
                {this.calcSingleRatePrice}
              </span>
              元/人
            </p>
            <p>
              课程组总收入
              <span class="px-1 text-[#FF4E19]">{this.calcRatePrice}</span>元/人
            </p>
            <p>您的课程收入将在课程结束后结算到您的账户中</p>
          </div>
          {/* <ElFormItem label="课程封面" class="!mb-0">
            <ElTabs
              v-model={createState.tabIndex}
              class={styles.tabs}
              onTab-change={(name: any) => {
                this.tabChange(name)
              }}
            >
              <ElTabPane label="图片模板" name={1}></ElTabPane>
              <ElTabPane label="自定义模板" name={2}></ElTabPane>
            </ElTabs>
          </ElFormItem>

          {createState.tabIndex === 1 && (
            <ElFormItem
              prop="lessonCoverTemplateUrl"
              rules={[
                {
                  required: true,
                  message: '请上传课程封面'
                }
              ]}
            >
              <ElRadioGroup v-model={createState.live.lessonCoverTemplateUrl}>
                <ElRow>
                  {createState.templateList.map((item: any) => (
                    <ElCol span={10} class="mb-3 cursor-pointer">
                      <div
                        class="w-40 relative rounded-xl overflow-hidden border"
                        onClick={() => {
                          this.selectImg(item)
                        }}
                      >
                        <ElImage src={item} class="align-middle" />
                        <ElRadio
                          label={item}
                          class="!absolute bottom-2 right-0 !h-auto z-10"
                        >
                          {''}
                        </ElRadio>
                      </div>
                    </ElCol>
                  ))}
                </ElRow>
              </ElRadioGroup>
            </ElFormItem>
          )}

          {createState.tabIndex === 2 && (
            <ElFormItem
              prop="lessonCoverUrl"
              rules={[
                {
                  required: true,
                  message: '请上传课程封面',
                  trigger: 'change'
                }
              ]}
            >
              <ColCropper
                modelValue={createState.live.lessonCoverUrl}
                bucket="video-course"
                cropUploadSuccess={(data: any) => {
                  createState.live.lessonCoverUrl = data
                  createState.live.lessonCoverTemplateUrl = ''
                }}
                options={{
                  fixedNumber: [3, 2],
                  autoCropWidth: 300,
                  autoCropHeight: 200
                }}
              />
            </ElFormItem>
          )} */}
        </ElForm>
        <div class="border-t border-t-[#E5E5E5] text-center pt-6 pb-7">
          <ElButton
            type="primary"
            class="!w-40 !h-[38px]"
            onClick={() => {
              ;(this as any).$refs.form.validate(async (valid: boolean) => {
                if (valid) {
                  createState.active = 1
                  const currentY =
                    document.documentElement.scrollTop ||
                    document.body.scrollTop
                  scrollAnimation(currentY, 0)
                } else {
                  this.$nextTick(() => {
                    let isError = document.getElementsByClassName('is-error')
                    isError[0].scrollIntoView({
                      block: 'center',
                      behavior: 'smooth'
                    })
                  })
                  return false
                }
              })
            }}
          >
            下一步
          </ElButton>
        </div>
      </>
    )
  }
})
