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,
  Radio,
  RadioGroup,
  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 Timer from './model/timer'
import ColHeader from '@/components/col-header'

export default defineComponent({
  name: 'PracticeSetting',
  data() {
    return {
      subjectList: [],
      chargeTypeArr: {
        0: '否',
        1: '是'
      },
      classTimeStatus: false,
      subjectStatus: false,
      timerStatus: false,
      timeSetting: {
        courseMinutes: 25,
        freeMinutes: 5,
        startSetting: '08:00',
        endSetting: '18:00'
      },
      timerObject: {} as any,
      form: {
        enableFlag: 1,
        courseMinutes: null as any,
        freeMinutes: 0,
        subjectIdTemp: '',
        subjectId: [] as any[],
        subjectPrice: [] as any[],
        skipHolidayFlag: 1,
        setting: ''
      },
      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() {
    try {
      // 获取手续费和分钟数
      const config = await request.get(
        '/api-teacher/sysConfig/queryByParamNameList',
        {
          params: {
            paramNames:
              'practice_times_setting,practice_service_fee,course_start_setting,course_end_setting'
          }
        }
      )
      const configData = config.data || []
      configData.forEach((item: any) => {
        if (item.paramName === '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 (item.paramName === 'practice_service_fee') {
          this.rate = item.paramValue
        }
        if (item.paramName === 'course_start_setting') {
          this.timeSetting.startSetting = item.paramValue
        }
        if (item.paramName === 'course_end_setting') {
          this.timeSetting.endSetting = item.paramValue
        }
      })
      //
      const teacher = await request.post('/api-teacher/teacher/querySubject')
      this.subjectList = teacher.data || []

      // 获取课程设置
      const setting = await request.post(
        '/api-teacher/teacherFreeTime/getDetail',
        {
          data: {
            defaultFlag: 1
          }
        }
      )
      const sr = setting.data
      if (sr) {
        this.timeSetting.courseMinutes = sr.courseMinutes
        this.timeSetting.freeMinutes = sr.freeMinutes

        this.timerObject = {
          monday: sr.monday ? JSON.parse(sr.monday) : [],
          tuesday: sr.tuesday ? JSON.parse(sr.tuesday) : [],
          wednesday: sr.wednesday ? JSON.parse(sr.wednesday) : [],
          thursday: sr.thursday ? JSON.parse(sr.thursday) : [],
          friday: sr.friday ? JSON.parse(sr.friday) : [],
          saturday: sr.saturday ? JSON.parse(sr.saturday) : [],
          sunday: sr.sunday ? JSON.parse(sr.sunday) : []
        }

        const tempIds: any = []
        const tempPrices: any = []
        const subjectPrice = sr.subjectPrice || []
        subjectPrice.forEach((item: any) => {
          tempIds.push(item.subjectId)
          tempPrices.push({
            subjectId: item.subjectId,
            subjectPrice: item.subjectPrice,
            subjectName: item.subjectName
          })
        })
        const to = this.timerObject
        this.form = {
          enableFlag: sr.enableFlag,
          courseMinutes: sr.courseMinutes,
          freeMinutes: sr.freeMinutes,
          subjectIdTemp: tempIds.join(','),
          subjectId: tempIds,
          subjectPrice: tempPrices,
          skipHolidayFlag: sr.skipHolidayFlag,
          setting:
            to.monday.length > 0 ||
            to.tuesday.length > 0 ||
            to.wednesday.length > 0 ||
            to.thursday.length > 0 ||
            to.friday.length > 0 ||
            to.saturday.length > 0 ||
            to.sunday.length > 0
              ? '已设置'
              : ''
        }
      }
    } catch {}
  },
  methods: {
    onSelect(item: any) {
      // 如果分钟数不同,则清空
      if (this.form.courseMinutes !== item.courseMinutes) {
        this.timerObject = {}
        this.form.setting = ''
      }
      this.form.courseMinutes = item.courseMinutes
      this.form.freeMinutes = item.freeMinutes
    },
    async onTimer() {
      try {
        const form = this.form
        if (!form.courseMinutes) {
          Toast('请选择单课时时长')
          return
        }
        this.timeSetting.courseMinutes = Number(form.courseMinutes)
        this.timeSetting.freeMinutes = Number(form.freeMinutes)
        this.timerStatus = true
      } catch {}
    },
    onChoiceTimer(item: any, status: boolean) {
      this.form.setting = status ? '已设置' : ''
      this.timerObject = item
      this.timerStatus = false
    },
    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: 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
        form.subjectPrice.forEach((item: any) => {
          item.subjectName = this.getSubjectName(item.subjectId)
        })
        await request.post('/api-teacher/teacherFreeTime/upSet', {
          data: {
            ...form,
            ...this.timerObject
          }
        })
        Toast('设置成功')
        setTimeout(() => {
          postMessage({ api: 'back', content: {} })
        }, 500)
      } catch {}
    }
  },
  render() {
    return (
      <Form style={{ paddingTop: '15px' }} onSubmit={this.onSubmit}>
        <ColHeader />
        <ColFieldGroup>
          <ColField title="是否开启陪练课" required border={false}>
            <RadioGroup
              class={styles['radio-group']}
              modelValue={this.form.enableFlag}
              onUpdate:modelValue={val => (this.form.enableFlag = val)}
            >
              {['1', '0'].map((item: string) => {
                const isActive = Number(item) === Number(this.form.enableFlag)
                const type = isActive ? 'primary' : 'default'
                return (
                  <Radio class={styles.radio} name={item}>
                    <Tag size="large" plain={isActive} type={type}>
                      {this.chargeTypeArr[item]}
                    </Tag>
                  </Radio>
                )
              })}
            </RadioGroup>
          </ColField>
          <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 && (
          <ColFieldGroup>
            {this.form.subjectPrice.map((item: any) => (
              <ColField
                title={`${this.getSubjectName(item.subjectId)}声部陪练价格`}
                required
              >
                <Field
                  v-model={item.subjectPrice}
                  name="singleMins"
                  type="number"
                  labelWidth={'auto'}
                  label={`${this.form.courseMinutes || 0}分钟 / `}
                  rules={[
                    {
                      required: true,
                      message: `请选择声部陪练价格`
                    }
                  ]}
                  formatter={this.onFormatter}
                  maxlength={8}
                  placeholder={`请选择声部陪练价格`}
                  v-slots={{
                    button: () => <span>元</span>
                  }}
                />
              </ColField>
            ))}
          </ColFieldGroup>
        )}

        <ColFieldGroup>
          <ColField title="可陪练时间段">
            <Field
              modelValue={this.form.setting}
              name="singleMins"
              readonly
              isLink
              onClick={this.onTimer}
              placeholder="未设置"
            />
          </ColField>
        </ColFieldGroup>

        <ColFieldGroup>
          <ColField required title="是否跳过节假日" border={false}>
            <RadioGroup
              class={styles['radio-group']}
              modelValue={this.form.skipHolidayFlag}
              onUpdate:modelValue={val => (this.form.skipHolidayFlag = val)}
            >
              {['1', '0'].map((item: string) => {
                const isActive =
                  Number(item) === Number(this.form.skipHolidayFlag)
                const type = isActive ? 'primary' : 'default'
                return (
                  <Radio class={styles.radio} name={item}>
                    <Tag size="large" plain={isActive} type={type}>
                      {this.chargeTypeArr[item]}
                    </Tag>
                  </Radio>
                )
              })}
            </RadioGroup>
          </ColField>
        </ColFieldGroup>

        <Sticky offsetBottom={0} position="bottom">
          <div class={'btnGroup'}>
            <Button block round type="primary" native-type="submit">
              提交
            </Button>
          </div>
        </Sticky>

        <ColPopup v-model={this.subjectStatus} destroy>
          <ColHeader />
          <SubjectModel
            max={5}
            single
            subjectList={this.subjectList}
            choiceSubjectIds={this.choiceSubjectId}
            onChoice={this.onChoice}
          />
        </ColPopup>

        <ColPopup v-model={this.timerStatus} destroy>
          <ColHeader title="设置陪练时间段" />
          <Timer
            onChoice={this.onChoiceTimer}
            timerObject={this.timerObject}
            courseMinutes={Number(this.timeSetting.courseMinutes)}
            freeMinutes={Number(this.timeSetting.freeMinutes)}
            startSetting={this.timeSetting.startSetting}
            endSetting={this.timeSetting.endSetting}
          />
        </ColPopup>

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