import ColHeader from '@/components/col-header'
import ColResult from '@/components/col-result'
import ColSearch from '@/components/col-search'
import request from '@/helpers/request'
import OrganSearch from '@/student/practice-class/model/organ-search'
import { Button, Checkbox, Icon, List, Popup, Toast } from 'vant'
import { defineComponent } from 'vue'
import Student from '../../components/student'
import styles from './index.module.less'

export default defineComponent({
  name: 'myStudent',
  props: {
    courseId: Number,
    onSubmit: {
      type: Function,
      default: (item: any) => {}
    }
  },
  data() {
    return {
      searchStatus: false,
      openStatus: false,
      subjectList: [],
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      params: {
        userName: '',
        subjectName: '全部声部',
        subjectId: null as any,
        page: 1,
        rows: 20
      },
      interfaceIds: [] as any,
      userIdList: [] as any
    }
  },
  async mounted() {
    try {
      const res = await request.get('/api-teacher/subject/subjectSelect')
      this.subjectList = res.data || []
    } catch {}
    await this.getExistList()
    await this.getList()
  },
  methods: {
    onSort() {
      this.params.page = 1
      this.list = []
      this.dataShow = true // 判断是否有数据
      this.loading = false
      this.finished = false
      this.searchStatus = false
      this.getList()
    },
    onSearch(val: string) {
      this.params.userName = val
      this.onSort()
    },
    async getExistList() {
      try {
        const res = await request.post(
          '/api-teacher/courseSchedule/selectStudent',
          {
            data: {
              courseId: this.courseId,
              page: 1,
              rows: 20
            }
          }
        )
        const rows = res.data.rows || []
        const userIdList = rows.map((item: any) => {
          return item.userId
        })
        this.interfaceIds = [...userIdList]
        this.userIdList = [...userIdList]
      } catch {}
    },
    async getList() {
      try {
        const res = await request.post(
          '/api-teacher/courseSchedule/selectStudent',
          {
            data: this.params
          }
        )
        this.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (this.list.length > 0 && result.pageNo === 1) {
          return
        }
        const rows = result.rows || []
        rows.forEach((n: any) => {
          if (this.userIdList.includes(n.userId)) {
            n.checked = true
          } else {
            n.checked = false
          }
        })
        this.list = this.list.concat(rows || [])
        this.finished = result.pageNo >= result.totalPage
        this.params.page = result.pageNo + 1
        this.dataShow = this.list.length > 0
      } catch {
        this.dataShow = false
        this.finished = true
      }
    },
    equar(a, b) {
      // 判断数组的长度
      if (a.length !== b.length) {
        return false
      } else {
        // 循环遍历数组的值进行比较
        for (let i = 0; i < a.length; i++) {
          if (a[i] !== b[i]) {
            return false
          }
        }
        return true
      }
    },
    nextSubmit() {
      if (this.userIdList.length <= 0) {
        return Toast('请至少选择一个学员')
      }
      if (this.equar(this.interfaceIds, this.userIdList)) {
        return Toast('您未调整学员')
      }
      const addStudentIds = this.userIdList.filter((item: any) => {
        return !this.interfaceIds.includes(item) && item
      })
      const removeStudentIds = this.interfaceIds.filter((item: any) => {
        return !this.userIdList.includes(item) && item
      })
      console.log(addStudentIds, removeStudentIds)
      const addStudents: any = []
      const removeStudents: any = []
      this.list.forEach((item: any) => {
        if (addStudentIds.includes(item.userId)) {
          addStudents.push(item)
        }

        if (removeStudentIds.includes(item.userId)) {
          removeStudents.push(item)
        }
      })
      console.log(addStudents, removeStudents)
      this.onSubmit({
        addStudents,
        removeStudents,
        userIdList: this.userIdList
      })
    },
    onCheckbox(item: any) {
      if (!item.checked && this.userIdList.length >= 7) {
        return Toast('学生已达上限')
      }
      item.checked = !item.checked
      const isExist = this.userIdList.includes(item.userId)
      if (item.checked) {
        !isExist && this.userIdList.push(item.userId)
      } else {
        isExist &&
          this.userIdList.splice(this.userIdList.indexOf(item.userId), 1)
      }
    }
  },
  render() {
    return (
      <>
        <ColSearch
          placeholder="请输入学员名称"
          onSearch={this.onSearch}
          v-slots={{
            left: () => (
              <div
                class={styles.label}
                onClick={() => {
                  this.searchStatus = !this.searchStatus
                  this.openStatus = !this.openStatus
                }}
              >
                {this.params.subjectName}
                <Icon
                  classPrefix="iconfont"
                  name="down"
                  size={12}
                  color="#333"
                />
              </div>
            )
          }}
        />

        <div class={styles.studentList}>
          {this.dataShow ? (
            <List
              v-model:loading={this.loading}
              finished={this.finished}
              finishedText=" "
              class={['mb12']}
              immediateCheck={false}
              onLoad={this.getList}
            >
              {this.list.map((item: any) => (
                <Student
                  item={{
                    userName: item.userName,
                    subjectName: item.subjectName,
                    avatar: item.avatar
                  }}
                  onClick={() => {
                    this.onCheckbox(item)
                  }}
                >
                  <Checkbox
                    v-model={item.checked}
                    name={item.userId}
                    onClick={() => {
                      this.onCheckbox(item)
                    }}
                  ></Checkbox>
                </Student>
              ))}
            </List>
          ) : (
            <ColResult btnStatus={false} classImgSize="SMALL" tips="暂无学员" />
          )}
        </div>
        <Popup
          show={this.searchStatus}
          position="bottom"
          round
          closeable
          safe-area-inset-bottom
          onClose={() => (this.searchStatus = false)}
          onClosed={() => (this.openStatus = false)}
        >
          {this.openStatus && (
            <OrganSearch
              subjectList={this.subjectList}
              onSort={this.onSort}
              isReset
              v-model={this.params.subjectId}
              v-model:subjectName={this.params.subjectName}
            />
          )}
        </Popup>

        <div class={styles.btnGroup}>
          <Button type="primary" round block onClick={this.nextSubmit}>
            下一步
          </Button>
        </div>
      </>
    )
  }
})
