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
} 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'

export default defineComponent({
  name: 'PracticeSetting',
  data() {
    const query = this.$route.query
    return {
      courseType: query.tabs == 'vip' ? 'VIP' : 'PRACTICE',
      text: query.tabs == 'vip' ? 'VIP定制课' : '趣纠课',
      subjectList: [],
      chargeTypeArr: {
        0: '否',
        1: '是'
      },
      checkStatus:false, // 是否审核版本
      classTimeStatus: false,
      subjectStatus: false,
      form: {
        courseMinutes: null as any,
        freeMinutes: 0,
        subjectIdTemp: '',
        subjectId: [] as any[],
        subjectPrice: [] as any[],
      },
      minutes: [] as any,
      rate: 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'
          }
        }
      )
      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) {
            this.form.courseMinutes = this.minutes[0].courseMinutes
            this.form.freeMinutes = this.minutes[0].freeMinutes
          }
        }
        if (item.paramName === 'practice_service_fee') {
          this.rate = 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: {
    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) {
          subjectPriceList.push({
            subjectId: item,
            subjectPrice: this.checkStatus ? 0 : null as any,
            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 : ''
    },
    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}设置`} />
        <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'}
                  label={`${this.form.courseMinutes || 0}分钟 / `}
                  rules={[
                    {
                      required: true,
                      message: `请选择声部${this.text}价格`
                    }
                  ]}
                  formatter={this.onFormatter}
                  maxlength={8}
                  placeholder={`请选择声部${this.text}价格`}
                  v-slots={{
                    button: () => <span>元</span>
                  }}
                />
              </ColField>
            ))}
          </ColFieldGroup>
        )}

        <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 />
          <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}
        />
      </Form>
    )
  }
})
