import { Button, Field, Form, Sticky } from 'vant'
import { defineComponent } from 'vue'
import { basePlan, createState } from './createState'
import styles from './course-plan.module.less'
import ColField from '@/components/col-field'
import ColFieldGroup from '@/components/col-field-group'

export default defineComponent({
  name: 'course-plan',
  data() {
    return {}
  },
  async mounted() {
    let list = createState.live.coursePlanList
    let listLength = list.length || 0
    console.log(list)
    if (createState.live.courseNum > listLength) {
      for (let i = 0; i < createState.live.courseNum - listLength; i++) {
        await this.addPlan()
      }
    } else if (createState.live.courseNum < listLength) {
      for (let i = 0; i < listLength - createState.live.courseNum; i++) {
        await this.delPlan()
      }
    }
  },
  methods: {
    async addPlan() {
      let list = createState.live.coursePlanList || []
      list.push({
        plan: '',
        startTime: '',
        endTime: '',
        classNum: list.length + 1
      })
      createState.live.coursePlanList = list
    },
    async delPlan(index?: number) {
      let list = createState.live.coursePlanList || []
      list.splice(index || list.length - 1, 1)
      createState.live.coursePlanList = list
    }
  },
  render() {
    return (
      <Form class={styles.coursePlan} onSubmit={() => (createState.active = 3)}>
        {/* scrollToError */}
        {createState.live.coursePlanList &&
          createState.live.coursePlanList.map((item: any) => (
            <ColFieldGroup>
              <ColField title={`第${item.classNum}课`} required border={false}>
                <Field
                  v-model={item.plan}
                  name="plan"
                  placeholder="请输入课程计划"
                  rows="3"
                  maxlength={200}
                  showWordLimit
                  autosize
                  rules={[{ required: true, message: '请输入课程计划' }]}
                  type="textarea"
                />
              </ColField>
            </ColFieldGroup>
          ))}

        <Sticky offsetBottom={0} position="bottom">
          <div class={['btnGroup', 'btnMore']}>
            <Button
              block
              round
              type="primary"
              plain
              onClick={() => {
                createState.active = 1
                if (!createState.live.courseGroupId){ // 修改时不重置
                  createState.live.coursePlanList = [{ ...basePlan }]
                }
              }}
            >
              上一步
            </Button>
            <Button block round type="primary" native-type="submit">
              下一步
            </Button>
          </div>
        </Sticky>
      </Form>
    )
  }
})
