import ColField from '@/components/col-field'
import ColFieldGroup from '@/components/col-field-group'
import SubjectModel from '@/business-components/subject-list'
import ColPopup from '@/components/col-popup'
import request from '@/helpers/request'
import { postMessage } from '@/helpers/native-message'
import {
  Form,
  Tag,
  Sticky,
  Button,
  Field,
  ActionSheet,
  CheckboxGroup,
  Checkbox,
  Dialog,
  Toast,
  Popup
} from 'vant'
import { defineComponent } from 'vue'
import styles from './practice-setting.module.less'
import { verifyNumberIntegerAndFloat } from '@/helpers/toolsValidate'
import ColHeader from '@/components/col-header'
import { state } from '@/state'
import TheSticky from '@/components/the-sticky'
import { moneyFormat } from '@/helpers/utils'
import TipModel from './tip-model'
import iconQuestion from './tip-model/images/icon-question.png'

/** 保留两位小数向上取整 */
export const numberToTwoUp = (num: number | string) => {
  num = Number(num)

  return Math.ceil(num * 100) / 100
}

export default defineComponent({
  name: 'PracticeSetting',
  data() {
    const query = this.$route.query
    return {
      tipStatus: false,
      courseType: query.tabs == 'vip' ? 'VIP' : 'PRACTICE',
      text: query.tabs == 'vip' ? 'VIP定制课' : '趣纠课',
      subjectList: [],
      chargeTypeArr: {
        0: '否',
        1: '是'
      },
      checkStatus: false, // 是否审核版本
      classTimeStatus: false,
      subjectStatus: false,
      form: {
        lowestPrice: 0 as any,
        highestPrice: 0 as any,
        coursePrice: 0 as any,
        courseMinutes: null as any,
        freeMinutes: 0,
        subjectIdTemp: '',
        subjectId: [] as any[],
        subjectPrice: [] as any[]
      },
      minutes: [] as any,
      rate: 0,
      accountPeriod: 0 // 账期
    }
  },
  computed: {
    choiceSubjectId() {
      const form = this.form as any
      const ids = form.subjectIdTemp ? form.subjectIdTemp.split(',') : []
      return ids.map((item: any) => Number(item)) || []
    }
  },
  async mounted() {
    document.title = `${this.text}设置`
    try {
      // 获取手续费和分钟数
      const config = await request.get(
        '/api-teacher/sysConfig/queryByParamNameList',
        {
          params: {
            paramNames:
              'practice_times_setting,practice_service_fee,vip_course_times_setting,vip_course_service_fee,vip_course_account_period,practice_account_period'
          }
        }
      )
      const configData = config.data || []
      configData.forEach((item: any) => {
        if (
          item.paramName ===
          (this.courseType === 'VIP'
            ? 'vip_course_times_setting'
            : 'practice_times_setting')
        ) {
          const mins = item.paramValue ? JSON.parse(item.paramValue) : []
          const tempArr = [] as any
          mins.forEach((item: any) => {
            tempArr.push({
              ...item,
              name: item.courseMinutes
            })
          })
          this.minutes = [...tempArr]
          if (this.minutes.length > 0) {
            const minute = this.minutes[0]
            this.form.coursePrice = minute.price
            this.form.courseMinutes = minute.courseMinutes
            this.form.freeMinutes = minute.freeMinutes
            this.form.lowestPrice = minute.lowestPrice || 0
            this.form.highestPrice = minute.highestPrice || 0
          }
        }
        if (
          item.paramName ===
          (this.courseType === 'VIP'
            ? 'vip_course_service_fee'
            : 'practice_service_fee')
        ) {
          this.rate = item.paramValue
        }
        if (
          item.paramName ===
          (this.courseType === 'VIP'
            ? 'vip_course_account_period'
            : 'practice_account_period')
        ) {
          this.accountPeriod = item.paramValue
        }
      })
      //
      const teacher = await request.post('/api-teacher/teacher/querySubject')
      this.subjectList = teacher.data || []

      // 获取课程设置
      const setting = await request.post(
        '/api-teacher/teacherSubjectPrice/list',
        {
          data: {
            courseType: this.courseType
          }
        }
      )
      const sr = setting.data
      if (Array.isArray(sr)) {
        const tempSubjects: any = []
        sr.forEach((item: any) => {
          this.form.courseMinutes = item.courseMinutes
          this.form.freeMinutes = item.freeMinutes
          this.form.subjectId.push(item.subjectId)
          tempSubjects.push({
            subjectId: item.subjectId,
            subjectName: item.subjectName,
            subjectPrice: item.subjectPrice
          })
        })
        this.form.subjectIdTemp = this.form.subjectId.join(',')
        this.form.subjectPrice = tempSubjects
      }

      // 判断如果是审核的则不显示
      const resVersion = await request.post('/api-teacher/open/appVersion', {
        data: {
          platform:
            state.platformType === 'STUDENT' ? 'ios-student' : 'ios-teacher',
          version: state.version
        }
      })
      this.checkStatus = resVersion.data.check ? true : false
    } catch {}
  },
  methods: {
    onCalcCoursePrice(price: number | string) {
      if (!price) {
        return '-'
      }
      const money = Number(price)
      return moneyFormat(numberToTwoUp(money - (this.rate * money) / 100))
    },
    onSelect(item: any) {
      this.form.courseMinutes = item.courseMinutes
      this.form.freeMinutes = item.freeMinutes
    },
    onChoice(item: any) {
      console.log(item)
      const tempItem = item || []
      this.form.subjectId = tempItem
      this.form.subjectIdTemp = tempItem.join(',') || ''
      const subjectPriceList = [...this.form.subjectPrice]
      tempItem.forEach((item: any) => {
        const index = subjectPriceList.findIndex(
          (subject: any) => subject.subjectId === item
        )
        if (index === -1) {
          console.log(this.form, 'this.orm')
          subjectPriceList.push({
            subjectId: item,
            subjectPrice: this.checkStatus ? 0 : this.form.coursePrice,
            subjectName: ''
          })
        }
      })

      const temp: any = []
      subjectPriceList.forEach((item: any) => {
        const isExist = tempItem.some(
          (subjectId: any) => subjectId === item.subjectId
        )
        isExist && temp.push(item)
      })
      this.form.subjectPrice = temp
      this.subjectStatus = false
    },
    getSubjectName(id: any) {
      const subject: any = this.subjectList.find((item: any) => item.id === id)
      return subject ? subject.name : ''
    },
    validatePrice(rule?: any) {
      if (
        Number(rule) > Number(this.form.highestPrice) ||
        Number(rule) < Number(this.form.lowestPrice)
      ) {
        return false
      } else {
        return true
      }
    },
    onFormatter(val: any) {
      return verifyNumberIntegerAndFloat(val)
    },
    async onSubmit() {
      try {
        const form = this.form
        const params: any = []
        form.subjectPrice.forEach((item: any) => {
          const subjectName = this.getSubjectName(item.subjectId)
          console.log(subjectName, 'subjectName')
          params.push({
            ...item,
            courseMinutes: this.form.courseMinutes,
            courseType: this.courseType,
            freeMinutes: this.form.freeMinutes,
            subjectName
          })
        })
        console.log(params, 'foparamsrm')
        await request.post('/api-teacher/teacherSubjectPrice/saveOrUpdate', {
          data: params
        })
        setTimeout(() => {
          Toast('设置成功')
        }, 100)
        setTimeout(() => {
          postMessage({ api: 'back', content: {} })
        }, 500)
      } catch {}
    }
  },
  render() {
    return (
      <Form style={{ paddingTop: '15px' }} onSubmit={this.onSubmit}>
        <ColHeader title={`${this.text}设置`} v-slots={{
          right: () => <img src={iconQuestion} class={styles.iconQuestion} onClick={() => this.tipStatus = true} />
        }} />
        <ColFieldGroup>
          <ColField title="可教授乐器" required>
            {this.form.subjectPrice && this.form.subjectPrice.length > 0 && (
              <CheckboxGroup
                modelValue={this.form.subjectId}
                class={styles['checkbox-group']}
                disabled
                onClick={() => {
                  this.subjectStatus = true
                }}
              >
                {this.form.subjectPrice.map((item: any) => (
                  <Checkbox class={styles.checkbox}>
                    <Tag
                      plain={true}
                      type={'primary'}
                      round
                      closeable
                      size="large"
                      style={{ backgroundColor: '#E9FFF8' }}
                      onClick={e => {
                        e.stopPropagation()
                        e.preventDefault()
                      }}
                      onClose={e => {
                        e.stopPropagation()
                        e.preventDefault()
                        Dialog.confirm({
                          title: '提示',
                          message: '您是否要删除选择的乐器？',
                          confirmButtonColor: 'var(--van-primary)'
                        }).then(() => {
                          const index = this.form.subjectId.indexOf(
                            item.subjectId
                          )
                          if (index !== -1) {
                            this.form.subjectId.splice(index, 1)
                          }

                          const index2 = this.form.subjectPrice.findIndex(
                            (subject: any) =>
                              subject.subjectId === item.subjectId
                          )
                          if (index2 !== -1) {
                            this.form.subjectPrice.splice(index2, 1)
                          }
                          this.form.subjectIdTemp =
                            this.form.subjectId.join(',')
                        })
                      }}
                    >
                      {this.getSubjectName(item.subjectId)}
                      {/* {item.subjectName} */}
                    </Tag>
                  </Checkbox>
                ))}
              </CheckboxGroup>
            )}
            {!this.form.subjectPrice.length && (
              <Field
                v-model={this.form.subjectIdTemp}
                name="courseMinutes"
                readonly
                onClick={() => {
                  this.subjectStatus = true
                }}
                rules={[{ required: true, message: '请选择可教授乐器' }]}
                placeholder="请选择可教授乐器"
              />
            )}
          </ColField>
          <ColField title="单课时时长" required>
            <Field
              v-model={this.form.courseMinutes}
              name="courseMinutes"
              readonly
              isLink
              onClick={() => {
                this.classTimeStatus = true
              }}
              rules={[{ required: true, message: '请选择单课时时长' }]}
              placeholder="请选择单课时时长"
              v-slots={{
                button: () => <span>分钟</span>
              }}
            />
          </ColField>
        </ColFieldGroup>
        {this.form.subjectPrice &&
          this.form.subjectPrice.length > 0 &&
          !this.checkStatus && (
            <ColFieldGroup>
              {this.form.subjectPrice.map((item: any) => (
                <ColField
                  title={`${this.getSubjectName(item.subjectId)}声部${
                    this.text
                  }价格`}
                  required
                >
                  <Field
                    v-model={item.subjectPrice}
                    name="singleMins"
                    type="number"
                    labelWidth={'auto'}
                    border={false}
                    readonly={this.courseType === 'PRACTICE' ? true : false}
                    label={`${this.form.courseMinutes || 0}分钟 / `}
                    rules={[
                      {
                        required: true,
                        message: `请输入${this.getSubjectName(
                          item.subjectId
                        )}声部${this.text}价格`
                      },
                      this.courseType === 'VIP'
                        ? {
                            validator: this.validatePrice,
                            message: `请输入价格在${this.form.lowestPrice}~${this.form.highestPrice}范围内`
                          }
                        : ({} as any)
                    ]}
                    formatter={this.onFormatter}
                    maxlength={8}
                    placeholder={
                      this.courseType === 'VIP'
                        ? `${this.form.lowestPrice}~${this.form.highestPrice}`
                        : `请选择声部${this.text}价格`
                    }
                    v-slots={{
                      button: () => <span>元</span>
                    }}
                  />
                  <div class={styles.showPrice}>
                    课程预计收入：
                    <span>¥ {this.onCalcCoursePrice(item.subjectPrice)}</span>
                  </div>
                </ColField>
              ))}
            </ColFieldGroup>
          )}

        <div class={styles.tipsAccount}>
          扣除应缴税金和平台服务费后 <br />
          实际课程收入按学生实际付款金额计算
          <br />
          您的课程收入将在课程结束<span>{this.accountPeriod}</span>
          天后结算到您的账户
        </div>

        <TheSticky position="bottom">
          <div class={['btnGroup', styles.PracticeSettingBtns]}>
            <Button block round type="primary" native-type="submit">
              提交
            </Button>
          </div>
        </TheSticky>

        <ColPopup v-model={this.subjectStatus} destroy>
          <ColHeader title={`${this.text}设置`} />
          <SubjectModel
            max={5}
            single
            subjectList={this.subjectList}
            choiceSubjectIds={this.choiceSubjectId}
            onChoice={this.onChoice}
          />
        </ColPopup>

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

        <Popup
          show={this.tipStatus}
          class={styles.tipPopup}
          closeable
          onClose={() => (this.tipStatus = false)}
        >
          <TipModel
            onClose={() => (this.tipStatus = false)}
            title={
              this.courseType === 'VIP' ? '什么是VIP定制课？' : '什么是趣纠课？'
            }
            content={
              this.courseType === 'VIP'
                ? 'VIP定制课采用一对一专属授课模式，每节课时长为45分钟。课程内容根据学生的具体需求量身打造，旨在全面提升学生的个人技能与表现。不论是希望在乐器演奏技巧上取得突破，如提高指法精准度、气息控制能力或节奏掌握等；还是为即将到来的重要活动、比赛或考级做充分准备，我们都能提供高度匹配的教学方案。此外，教学进度将根据每位学员的学习吸收情况灵活调整，确保每个人都能在最适合自己的节奏中稳步前进，扎实提升个人能力。'
                : '趣纠课以一对一专属、高度针对性的形式进行，每次课程时长为25分钟。本课程专为解决学生日常练习中的疑问与误区设计，尤其适合那些在自我练习后感到困惑或不确定自己方法是否正确的学生。不同于传统的教学模式，趣纠课不侧重于新知识或新技能的传授，而是全心全意致力于检查学生现有的练习成果，并及时纠正其中出现的问题。这种方式不仅有助于学生巩固已掌握的知识和技能，还能有效防止错误习惯的形成和发展，为他们今后的学习打下更加坚实的基础。'
            }
          />
        </Popup>
      </Form>
    )
  }
})
