import ColField from '@/components/col-field'
import ColFieldGroup from '@/components/col-field-group'
import ColPopup from '@/components/col-popup'
import SubjectModel from '@/business-components/subject-list'
import { ActionSheet, Button, Field, Form } from 'vant'
import { defineComponent } from 'vue'
import styles from './course.module.less'
import { createState } from './createState'
import {
  verifiyNumberInteger,
  verifyNumberIntegerAndFloat
} from '@/helpers/toolsValidate'
import request from '@/helpers/request'
import { state } from '@/state'
import ColHeader from '@/components/col-header'
import TheSticky from '@/components/the-sticky'

// 校验函数返回 true 表示校验通过，false 表示不通过
export const validator = val => {
  console.log(val)
  if (Number(val) <= 0) {
    return '课程组售价必须大于0'
  } else {
    return true
  }
}

export default defineComponent({
  name: 'course',
  data() {
    return {
      subjectStatus: false,
      classTimeStatus: false,
      checked: false
    }
  },
  computed: {
    choiceSubjectIds() {
      // 选择的科目编号
      const ids = createState.live.subjectId
        ? Number(createState.live.subjectId)
        : null
      return ids ? [ids] : []
    },
    subjectList() {
      // 学科列表
      return createState.subjectList || []
    },
    lessonSubjectName() {
      // 选择的科目
      let tempStr = ''
      this.subjectList.forEach((item: any) => {
        if (this.choiceSubjectIds.includes(item.id)) {
          tempStr = item.name
        }
      })
      return tempStr
    },
    calcSingleRatePrice() {
      const rate = createState.rate || 0
      const nums = createState.live.courseNum
      const price = createState.live.coursePrice || 0
      return nums ? ((price / nums) * (1 - rate / 100)).toFixed(2) : 0
    },
    calcRatePrice() {
      // 计算手续费
      const rate = createState.rate || 0
      const price = createState.live.coursePrice || 0
      return (price - (rate / 100) * price).toFixed(2)
    },
    disabled() {
      return createState.live.courseGroupId ? true : false
    }
  },
  async mounted() {
    try {
      const resVersion = await request.post('/api-teacher/open/appVersion', {
        data: {
          platform:
            state.platformType === 'STUDENT' ? 'ios-student' : 'ios-teacher',
          version: state.version
        }
      })
      this.checked = resVersion.data.check ? true : false
      // 审核版本金额默认为0
      if (this.checked) {
        createState.live.coursePrice = 0
      }
    } catch {
      //
    }
  },
  methods: {
    onChoice(id: number) {
      createState.live.subjectId = id
      this.subjectStatus = false
    },
    onFormatter(val: any) {
      return verifyNumberIntegerAndFloat(val)
    },
    onFormatterInt(val: any) {
      if (val && val >= 1) {
        return verifiyNumberInteger(val)
      } else {
        return ''
      }
    },
    onSelect(action: any) {
      createState.live.singleCourseMinutes =
        Number(action.name || 0) + Number(action.freeMinutes || 0)
      createState.live.singleMins = Number(action.name || 0)
      createState.live.freeMinutes = Number(action.freeMinutes || 0)
    }
  },
  render() {
    return (
      <Form
        class={styles.classInfo}
        onSubmit={() => (createState.active = 2)}
        scrollToError
      >
        <ColFieldGroup>
          <ColField title="课程名称" required>
            <Field
              v-model={createState.live.name}
              name="name"
              maxlength={20}
              placeholder="请输入您的课程名称"
              rules={[{ required: true, message: '请输入您的课程名称' }]}
              disabled={this.disabled}
            />
          </ColField>
          <ColField title="课程声部" required>
            <Field
              modelValue={this.lessonSubjectName}
              name="subjectId"
              readonly
              isLink
              disabled={this.disabled}
              onClick={() => {
                if (createState.live.courseGroupId) {
                  return
                }
                this.subjectStatus = true
              }}
              rules={[{ required: true, message: '请选择课程声部' }]}
              placeholder="请选择课程声部"
            />
          </ColField>

          <ColField title="课程介绍" required border={false}>
            <Field
              v-model={createState.live.courseIntroduce}
              name="courseIntroduce"
              placeholder="请输入课程介绍"
              rows="3"
              maxlength={200}
              showWordLimit
              autosize
              rules={[{ required: true, message: '请输入课程介绍' }]}
              type="textarea"
            />
          </ColField>
        </ColFieldGroup>

        <ColFieldGroup>
          <ColField title="课时数" required>
            <Field
              v-model={createState.live.courseNum}
              name="courseNum"
              placeholder="请输入您的课时数"
              formatter={this.onFormatterInt}
              type="number"
              maxlength={2}
              disabled={this.disabled}
              rules={[{ required: true, message: '请输入您的课时数' }]}
              v-slots={{
                button: () => <span>课时</span>
              }}
            />
          </ColField>
          <ColField title="单课时时长" required>
            <Field
              modelValue={createState.live.singleMins}
              name="singleMins"
              readonly
              disabled={this.disabled}
              isLink
              onClick={() => {
                if (!createState.live.courseGroupId) {
                  this.classTimeStatus = true
                }
              }}
              rules={[{ required: true, message: '请选择单课时时长' }]}
              placeholder="请选择单课时时长"
            />
          </ColField>
          {/* 是审核版本才会显示金额 */}
          {!this.checked && (
            <ColField title="课程组售价" required>
              <Field
                v-model={createState.live.coursePrice}
                name="coursePrice"
                placeholder="请输入您的课程组售价"
                formatter={this.onFormatter}
                type="number"
                maxlength={8}
                disabled={this.disabled}
                rules={[
                  { required: true, validator, message: '请输入您的课程组售价' }
                ]}
                v-slots={{
                  button: () => <span>元</span>
                }}
              />
            </ColField>
          )}
        </ColFieldGroup>

        {/* 是审核版本才会显示金额 */}
        {!this.checked && (
          <div class={styles['class-info-tip']}>
            <p>扣除手续费后您的课程预计收入为：</p>
            <p>
              单课时<span>{this.calcSingleRatePrice}</span>元/人
            </p>
            <p>
              课程组总收入<span>{this.calcRatePrice}</span>元/人
            </p>
            <p>您的课程收入将在课程结束后结算到您的账户中</p>
          </div>
        )}

        <TheSticky position="bottom">
          <div class={'btnGroup'}>
            <Button block round type="primary" native-type="submit">
              下一步
            </Button>
          </div>
        </TheSticky>

        <ColPopup v-model={this.subjectStatus}>
          <ColHeader title="选择声部" />
          <SubjectModel
            selectType="Radio"
            single
            subjectList={createState.subjectList}
            choiceSubjectIds={this.choiceSubjectIds}
            onChoice={this.onChoice}
          />
        </ColPopup>

        <ActionSheet
          v-model:show={this.classTimeStatus}
          actions={createState.minutes}
          cancelText="取消"
          closeOnClickAction
          onSelect={this.onSelect}
        />
      </Form>
    )
  }
})
