import request from '@/helpers/request'
import { verifyNumberIntegerAndFloat } from '@/helpers/toolsValidate'
import { teacherState } from '@/views/role-auth/teacherAuth/teacherState'
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 {
      // 获取手续费和分钟数
      let config = await request.get(
        '/api-website/sysConfig/queryByParamNameList',
        {
          params: {
            paramNames:
              'practice_times_setting,practice_service_fee,course_start_setting,course_end_setting'
          }
        }
      )
      let configData = config.data || []
      configData.forEach((item: any) => {
        if (item.paramName === 'practice_times_setting') {
          let mins = item.paramValue ? JSON.parse(item.paramValue) : []
          let 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
        }
      })

      let 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) : []
        }

        let tempIds: any = []
        let 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(',') || ''
      let 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) {
      // console.log(verifyNumberIntegerAndFloat(e.target.value))
      e.target.value = verifyNumberIntegerAndFloat(e.target.value)
    },
    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(() => {
            let isError = document.getElementsByClassName('is-error')
            isError[0].scrollIntoView({
              block: 'center',
              behavior: 'smooth'
            })
          })
          return false
        }
      })
    }
  },
  render() {
    return (
      <div class={styles.setting}>
        <div class="text-base text-[#666] leading-none px-6 py-5 border-b border-b-[#E5E5E5]">
          陪练课设置
        </div>

        <ElForm
          labelPosition="left"
          labelWidth={'180px'}
          size="large"
          model={this.form}
          ref="form"
          class="px-44 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}
            >
              {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
                onKeyup={this.onFormatter}
                type="text"
                placeholder="请输入陪练价格"
                v-model={item.subjectPrice}
                v-slots={{
                  append: () => <span class="text-base text-[#333]">元</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="border-t border-t-[#E5E5E5] text-center pt-6 pb-7">
          <ElButton
            class="!w-40 !h-[38px]"
            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-40 !h-[38px]"
            onClick={this.onSubmit}
          >
            保存设置
          </ElButton>
        </div>

        <ElDialog
          modelValue={this.timerStatus}
          onUpdate:modelValue={val => (this.timerStatus = val)}
          showClose
        >
          <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>
    )
  }
})
