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 { browser } 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,
  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 getOrchestra = async () => {
      try {
        const { data } = await request.post('/api-school/orchestra/page', {
          data: {
            page: 1,
            rows: 100,
            schoolId: state.user.data.school.id
          }
        })
        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 {
        const { data } = await request.post('/api-school/courseSchedule/batchAdjust', {
          data: {
            adjustDay: forms.changeType ? '-' + forms.adjustDay : forms.adjustDay,
            classGroupIdList: forms.classGroupIdList,
            startTime: forms.startTime.join('-'),
            endTime: forms.endTime.join('-')
          }
        })
        router.push({
          path: '/course-preview',
          query: {
            cacheId: data
          }
        })
      } catch {
        //
      }
    }

    onMounted(() => {
      getOrchestra()
    })
    return () => (
      <div class={styles.batchAdjust}>
        <OHeader />

        <CellGroup inset>
          <Cell isLink onClick={() => (forms.orchestraStatus = true)}>
            {{ 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="请输入调整天数"
            v-slots={{ extra: () => <span style={{ paddingLeft: '6px' }}>天</span> }}
          />
        </CellGroup>

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

        {/* 乐团列表 */}
        <Popup v-model:show={forms.orchestraStatus} position="bottom" round>
          <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>
          <DatePicker
            // v-model={forms.startTime}
            minDate={new Date()}
            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>
          <DatePicker
            // v-model={forms.endTime}
            minDate={forms.endTimeMinDate}
            onCancel={() => (forms.endTimeStatus = false)}
            onConfirm={(val: any) => {
              forms.endTime = val.selectedValues
              forms.endTimeStatus = false
            }}
          />
        </Popup>
      </div>
    )
  }
})
