import ColEmpty from '@/components/col-empty'
import request from '@/helpers/request'
import { verifyNumberIntegerAndFloat } from '@/helpers/toolsValidate'
import { state } from '@/state'
import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElOption,
  ElOptionGroup,
  ElRadio,
  ElRadioButton,
  ElRadioGroup,
  ElSelect
} from 'element-plus'
import { defineComponent } from 'vue'
import PracticeTimer from '../model/practice-timer'
import styles from './index.module.less'

export default defineComponent({
  name: 'practice-setting',
  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
    }
  },
  async mounted() {
    try {
      // 获取手续费和分钟数
      const config = await request.get(
        '/api-website/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-website/teacher/querySubject')
      this.subjectList = teacher.data || []

      // 获取课程设置
      const setting = await request.post(
        '/api-website/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 ? 1 : 0,
          courseMinutes: sr.courseMinutes,
          freeMinutes: sr.freeMinutes,
          subjectIdTemp: tempIds.join(','),
          subjectId: tempIds,
          subjectPrice: tempPrices,
          skipHolidayFlag: sr.skipHolidayFlag ? 1 : 0,
          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('请选择单课时时长')
          ElMessage.error('请选择单课时时长')
          return
        }
        this.timeSetting.courseMinutes = Number(form.courseMinutes)
        this.timeSetting.freeMinutes = Number(form.freeMinutes)
        this.timerStatus = true
      } catch {
        //
      }
    },
    onChoiceTimer(item: any, status: boolean) {
      // console.log(item, 'item')
      this.form.setting = status ? '已设置' : ''
      this.timerObject = item
      this.timerStatus = false
    },
    onChoice(item: any) {
      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(e: any, item: any) {
      // console.log(verifyNumberIntegerAndFloat(e.target.value), e)
      // e.target.value = verifyNumberIntegerAndFloat(e.target.value)
      item = verifyNumberIntegerAndFloat(e)
    },
    async onSubmit() {
      ;(this as any).$refs.form.validate(async (_: boolean) => {
        if (_) {
          try {
            const form = this.form
            form.subjectPrice.forEach((item: any) => {
              item.subjectName = this.getSubjectName(item.subjectId)
            })
            form.setting = form.setting === '未设置' ? '' : form.setting
            await request.post('/api-website/teacherFreeTime/upSet', {
              data: {
                ...form,
                ...this.timerObject
              }
            })
            ElMessage.success('设置成功')
            setTimeout(() => {
              postMessage({ api: 'back', content: {} })
            }, 500)
          } catch {
            //
          }
        } else {
          this.$nextTick(() => {
            const isError = document.getElementsByClassName('is-error')
            isError[0].scrollIntoView({
              block: 'center',
              behavior: 'smooth'
            })
          })
          return false
        }
      })
    }
  },
  render() {
    return (
      <div class={styles.setting}>
        <div class="text-2xl font-semibold text-black leading-none px-6 py-5 ">
          陪练课设置
        </div>
        {state.user.data?.entryFlag ? (
          <>
            <ElForm
              labelPosition="left"
              labelWidth={'188px'}
              size="large"
              model={this.form}
              ref="form"
              class="px-6 py-5"
            >
              <ElFormItem
                label="是否开启陪练"
                prop="enableFlag"
                rules={[
                  {
                    required: true,
                    message: '请选择是否开启陪练'
                  }
                ]}
              >
                <ElSelect class="w-full" v-model={this.form.enableFlag}>
                  <ElSelect.Option value={1} label={'是'}>
                    是
                  </ElSelect.Option>
                  <ElSelect.Option value={0} label={'否'}>
                    否
                  </ElSelect.Option>
                </ElSelect>
              </ElFormItem>
              <ElFormItem
                label="可教授声部"
                prop={'subjectId'}
                rules={[
                  {
                    required: true,
                    message: '请选择可教授声部',
                    trigger: 'change'
                  }
                ]}
              >
                <ElSelect
                  multiple
                  filterable
                  placeholder="请选择可教授声部"
                  class="w-full"
                  multipleLimit={5}
                  v-model={this.form.subjectId}
                  onChange={this.onChoice}
                >
                  {this.subjectList.map((item: any) => (
                    <ElOption key={item.id} value={item.id} label={item.name} />
                  ))}
                </ElSelect>
              </ElFormItem>
              <ElFormItem
                label="单课时长"
                prop="courseMinutes"
                rules={[
                  {
                    required: true,
                    message: '请选择单课时长',
                    trigger: 'change'
                  }
                ]}
              >
                <ElSelect
                  class="w-full"
                  placeholder="请选择单课时时长"
                  v-model={this.form.courseMinutes}
                  onChange={(item: any) => {
                    // 如果分钟数不同,则清空
                    this.timerObject = {}
                    this.form.setting = '未设置'
                    // 设置空余时间
                    this.minutes.forEach((mins: any) => {
                      if (mins.courseMinutes === item) {
                        this.form.freeMinutes = mins.freeMinutes
                      }
                    })
                  }}
                >
                  {this.minutes.map((item: any) => (
                    <ElOption
                      key={item.courseMinutes}
                      value={item.courseMinutes}
                    >
                      {item.name}
                    </ElOption>
                  ))}
                </ElSelect>
              </ElFormItem>
              {this.form.subjectPrice.map((item: any, index: number) => (
                <ElFormItem
                  label={`${this.getSubjectName(item.subjectId)}陪练价格`}
                  prop={`subjectPrice.${index}.subjectPrice`}
                  rules={[
                    {
                      required: true,
                      message: `请选择声部陪练价格`
                    }
                  ]}
                >
                  <ElInput
                    // @ts-ignore
                    onInput={(value: any) => {
                      item.subjectPrice = verifyNumberIntegerAndFloat(value)
                    }}
                    type="text"
                    placeholder="请输入陪练价格"
                    v-model={item.subjectPrice}
                    maxlength={8}
                    v-slots={{
                      suffix: () => (
                        <span class="text-base text-[#999]">元</span>
                      )
                    }}
                  />
                </ElFormItem>
              ))}
              <ElFormItem label="是否跳过节假日">
                <ElRadioGroup v-model={this.form.skipHolidayFlag}>
                  <ElRadioButton label={1} class="mr-3 w-24">
                    是
                  </ElRadioButton>
                  <ElRadioButton label={0} class="w-24">
                    否
                  </ElRadioButton>
                </ElRadioGroup>
              </ElFormItem>
              <ElFormItem label="陪练时间段">
                <div onClick={this.onTimer} class="w-full">
                  <ElInput
                    readonly
                    class="cursor-pointer"
                    v-model={this.form.setting}
                    placeholder="请选择陪练时间段"
                    suffixIcon={'ArrowDown'}
                  />
                </div>
              </ElFormItem>
            </ElForm>

            <div class="text-center pt-6 pb-7">
              <ElButton
                class="!w-44 !h-[48px] !text-base"
                round
                onClick={() => {
                  // 重置数据
                  this.form = {
                    enableFlag: 1,
                    courseMinutes: null as any,
                    freeMinutes: 0,
                    subjectIdTemp: '',
                    subjectId: [] as any[],
                    subjectPrice: [] as any[],
                    skipHolidayFlag: 1,
                    setting: '未设置'
                  }
                  ;(this as any).$refs.form.resetFields()
                }}
              >
                重置
              </ElButton>
              <ElButton
                type="primary"
                class="!w-44 !h-[48px] !text-base"
                round
                onClick={this.onSubmit}
              >
                保存设置
              </ElButton>
            </div>
          </>
        ) : (
          <ColEmpty
            type="teacherCert"
            message="您还未完成达人认证，认证后才可设置陪练课哦~"
            buttonVisibility
            buttonText="去认证"
            onDetail={() => {
              this.$router.push('/teacherAuth')
            }}
          />
        )}

        <ElDialog
          modelValue={this.timerStatus}
          onUpdate:modelValue={val => (this.timerStatus = val)}
          showClose
          width={'488px'}
        >
          {this.timerStatus && (
            <PracticeTimer
              onChoice={this.onChoiceTimer}
              onClose={() => {
                this.timerStatus = false
              }}
              timerObject={this.timerObject}
              courseMinutes={Number(this.timeSetting.courseMinutes)}
              freeMinutes={Number(this.timeSetting.freeMinutes)}
              startSetting={this.timeSetting.startSetting}
              endSetting={this.timeSetting.endSetting}
            />
          )}
        </ElDialog>
      </div>
    )
  }
})
