import ODialog from '@/components/o-dialog'
import OHeader from '@/components/o-header'
import OPopup from '@/components/o-popup'
import OSticky from '@/components/o-sticky'
import { postMessage } from '@/helpers/native-message'
import request from '@/helpers/request'
import { verifiyNumberInteger } from '@/helpers/toolsValidate'
import { browser, formatterDatePicker } from '@/helpers/utils'
import router from '@/router'
import { state } from '@/state'
import dayjs from 'dayjs'
import {
  Button,
  Cell,
  CellGroup,
  DatePicker,
  Field,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  showToast,
  Tag
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import PracticeClass from '../train-planning/modal/practice-class'
import { forms } from './batch'
import styles from './batch-adjust.module.less'

export default defineComponent({
  name: 'batch-adjust',
  setup() {
    const router = useRouter()
    const form = reactive({
      submitLoading: false,
      dialogStatus: false,
      dialogMessage: ''
    })

    // 获取乐团列表
    const getOrchestra = async () => {
      try {
        const { data } = await request.post('/api-school/orchestra/page', {
          data: {
            page: 1,
            rows: 100,
            schoolId: state.user.data.school.id,
            status: 'DONE'
          }
        })
        forms.orchestraList = data.rows || []
        // 初始化显示选中第一个乐团
        if (forms.orchestraList.length > 0) {
          const temp = forms.orchestraList[0]
          forms.orchestraId = temp.id
          forms.orchestraName = temp.name
        }
      } catch {
        //
      }
    }

    const onSubmit = async () => {
      try {
        if (forms.classGroupIdList.length <= 0) {
          showToast('请选择班级')
          return
        }
        if (!forms.startTime.join('-')) {
          showToast('请选择课程开始日期')
          return
        }
        if (!forms.endTime.join('-')) {
          showToast('请选择课程结束日期')
          return
        }
        if (!forms.adjustDay) {
          showToast('请输入调整天数')
          return
        }
        form.submitLoading = true
        const res = await request.post('/api-school/courseSchedule/batchAdjust', {
          hideLoading: true,
          data: {
            adjustDay: forms.changeType ? '-' + forms.adjustDay : forms.adjustDay,
            classGroupIdList: forms.classGroupIdList,
            startTime: forms.startTime.join('-'),
            endTime: forms.endTime.join('-')
          }
        })
        form.submitLoading = false
        if (res.code === 999) {
          form.dialogStatus = true
          form.dialogMessage = res.message
        } else {
          router.push({
            path: '/course-preview',
            query: {
              cacheId: res.data
            }
          })
        }
      } catch {
        //
        form.submitLoading = false
      }
    }

    const onFormatterInt = (val: any) => {
      if (val && val >= 1) {
        return verifiyNumberInteger(val)
      } else {
        return ''
      }
    }
    onMounted(() => {
      getOrchestra()
    })
    return () => (
      <div class={styles.batchAdjust}>
        <OHeader />

        <CellGroup inset>
          <Cell isLink onClick={() => (forms.orchestraStatus = true)} valueClass={['van-ellipsis']}>
            {{ title: () => '乐团名称', value: () => forms.orchestraName }}
          </Cell>
          <Cell
            isLink
            onClick={() => {
              forms.classStatus = true
            }}
          >
            {{
              title: () => '班级',
              value: () => (
                <div class={styles.value}>
                  {forms.classGroupIdList.length <= 0 ? (
                    <div class={styles.tips}>请选择班级</div>
                  ) : (
                    <div>
                      已选<span style={{ padding: '0 4px' }}>{forms.classGroupIdList.length}</span>
                      个班级
                    </div>
                  )}
                </div>
              )
            }}
          </Cell>
          <Field
            isLink
            label="课程开始日期"
            placeholder="请选择课程开始日期"
            readonly
            inputAlign="right"
            modelValue={forms.startTime.join('-')}
            onClick={() => {
              forms.startTimeStatus = true
            }}
          />
          <Field
            isLink
            label="课程结束日期"
            placeholder="请选择课程结束日期"
            readonly
            inputAlign="right"
            modelValue={forms.endTime.join('-')}
            onClick={() => {
              forms.endTimeStatus = true
            }}
          />
          <Cell title="调整方式">
            {{
              value: () => (
                <RadioGroup
                  checked-color="#FF8057"
                  v-model={forms.changeType}
                  direction="horizontal"
                >
                  <Tag
                    size="large"
                    type="primary"
                    color={!(forms.changeType === 1) ? '#EAEAEA' : '#FF8057'}
                    textColor={!(forms.changeType === 1) ? '#AAA' : '#FFF'}
                    class={styles.radioSection}
                    round
                  >
                    <Radio class={styles.radioItem} name={1}></Radio>提前
                  </Tag>
                  <Tag
                    size="large"
                    type="primary"
                    color={!(forms.changeType === 0) ? '#EAEAEA' : '#FF8057'}
                    textColor={!(forms.changeType === 0) ? '#AAA' : '#FFF'}
                    class={styles.radioSection}
                    round
                  >
                    <Radio class={styles.radioItem} name={0}></Radio>延后
                  </Tag>
                </RadioGroup>
              )
            }}
          </Cell>
          <Field
            class={styles.adjustDay}
            label="调整天数"
            inputAlign="right"
            type="number"
            v-model={forms.adjustDay}
            placeholder="请输入调整天数"
            formatter={onFormatterInt}
            v-slots={{ extra: () => <span style={{ paddingLeft: '6px' }}>天</span> }}
          />
        </CellGroup>

        <OSticky position="bottom">
          <div class={['btnGroup btnMore']}>
            <Button
              color="#ccc"
              round
              onClick={() => {
                if (browser().isApp) {
                  postMessage({ api: 'back' })
                } else {
                  router.back()
                }
              }}
            >
              取消
            </Button>
            <Button
              color="#FF8057"
              round
              onClick={onSubmit}
              disabled={form.submitLoading}
              loading={form.submitLoading}
            >
              下一步
            </Button>
          </div>
        </OSticky>

        {/* 乐团列表 */}
        <Popup
          v-model:show={forms.orchestraStatus}
          position="bottom"
          round
          class={'popupBottomSearch'}
        >
          <Picker
            columns={forms.orchestraList}
            columnsFieldNames={{ text: 'name', value: 'id' }}
            onCancel={() => (forms.orchestraStatus = false)}
            onConfirm={(val: any) => {
              const selectedOption = val.selectedOptions[0]
              if (forms.orchestraId !== selectedOption.id) {
                forms.orchestraId = selectedOption.id
                forms.orchestraName = selectedOption.name
                forms.classGroupIdList = []
              }
              forms.orchestraStatus = false
            }}
          />
        </Popup>

        {/* 班级 */}
        <OPopup
          v-model:modelValue={forms.classStatus}
          position="bottom"
          style={{ background: '#f6f6f6' }}
          destroy
        >
          <PracticeClass
            onClose={() => (forms.classStatus = false)}
            orchestraId={forms.orchestraId}
            selectItem={forms.classGroupIdList}
            onConfirm={(val: any) => {
              forms.classGroupIdList = val
            }}
          />
        </OPopup>

        {/* 开始日期 */}
        <Popup
          v-model:show={forms.startTimeStatus}
          position="bottom"
          round
          class={'popupBottomSearch'}
        >
          <DatePicker
            // v-model={forms.startTime}
            minDate={new Date()}
            formatter={(type, option) => {
              if (type === 'year') {
                option.text += '年'
              }
              if (type === 'month') {
                option.text += '月'
              }
              if (type === 'day') {
                option.text += '日'
              }
              return option
            }}
            onCancel={() => (forms.startTimeStatus = false)}
            onConfirm={(val: any) => {
              forms.startTime = val.selectedValues
              forms.startTimeStatus = false
              forms.endTime = []
              forms.endTimeMinDate = dayjs(forms.startTime.join('-') || new Date()).toDate()
            }}
          />
        </Popup>
        {/* 结束日期 */}
        <Popup
          v-model:show={forms.endTimeStatus}
          position="bottom"
          round
          class={'popupBottomSearch'}
        >
          <DatePicker
            // v-model={forms.endTime}
            minDate={forms.endTimeMinDate}
            formatter={formatterDatePicker}
            onCancel={() => (forms.endTimeStatus = false)}
            onConfirm={(val: any) => {
              forms.endTime = val.selectedValues
              forms.endTimeStatus = false
            }}
          />
        </Popup>

        <ODialog
          title="提示"
          v-model:show={form.dialogStatus}
          message={form.dialogMessage}
          confirmButtonText="确定"
          onConfirm={() => {
            router.back()
          }}
        />
      </div>
    )
  }
})
