import { defineComponent } from 'vue'
import styles from './index.module.less'
import ColHeader from '@/components/col-header'
import {
  Button,
  Icon,
  Popup,
  RadioGroup,
  Sticky,
  Radio,
  Tag,
  List,
  ActionSheet
} from 'vant'
import ColSearch from '@/components/col-search'
import PracticeItem from './practice-item'
import request from '@/helpers/request'
import ColResult from '@/components/col-result'
import AllSearch from './model/all-search'
import OrganSearch from './model/organ-search'
import { state } from '@/state'
import { useElementSize } from '@vueuse/core'

// {"subjectId":null,"search":"","sort":"starGrade ASC,expTime DESC,subjectPrice DESC"}
const actions = [
  {
    name: '不限制',
    value: '',
    color: 'var(--van-primary)'
  },
  {
    name: '单价最高',
    value: 'subjectPrice DESC',
    color: '#333'
  },
  {
    name: '单价最低',
    value: 'subjectPrice ASC',
    color: '#333'
  },
  {
    name: '课时数最多',
    value: 'expTime DESC',
    color: '#333'
  },
  {
    name: '评分最高',
    value: 'starGrade DESC',
    color: '#333'
  }
]

export default defineComponent({
  name: 'practiceClass',
  data() {
    return {
      openStatus: false,
      searchStatus: false,
      subjectList: [],
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      searchType: 'organ' as 'organ' | 'all',
      tempSort: {
        starGrade: 'ALL',
        expTime: 'ALL',
        subjectPrice: 'ALL'
      },
      dataLoading: false,
      params: {
        search: '',
        sort: '',
        subjectName: '',
        subjectId: null as any,
        page: 1,
        rows: 20
      },
      show: false,
      height: 'auto' as any
    }
  },
  async mounted() {
    this.params.subjectId = state.user.data?.subjectId || null
    this.params.subjectName = state.user.data?.subjectName || ''
    try {
      const res = await request.get('/api-student/subject/subjectSelect')
      this.subjectList = res.data || []
    } catch {}
    this.getList()

    // this.$nextTick(() => {
    const { width, height } = useElementSize((this as any).$refs.headers)
    console.log(width.value, height.value, width, height)
    this.height = height
    // })
  },
  methods: {
    onSearch(_search?: any) {
      this.params.search = _search
      this.onSort()
    },
    onSort() {
      this.params.page = 1
      this.list = []
      this.dataShow = true // 判断是否有数据
      this.loading = false
      this.finished = false
      this.searchStatus = false
      this.getList()
    },
    onSheetSelect(item: any) {
      actions.forEach((v: any) => {
        v.color = '#333'
        if (v.value === item.value) {
          v.color = 'var(--van-primary)'
        }
      })
      this.params.sort = item.value
      this.show = false
      this.onSort()
    },
    async getList() {
      try {
        if (this.dataLoading) {
          return
        }
        this.dataLoading = true
        const res = await request.post(
          '/api-student/courseSchedule/teacherList',
          {
            data: {
              ...this.params
            }
          }
        )
        this.dataLoading = false
        this.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (this.list.length > 0 && result.pageNo === 1) {
          return
        }
        this.list = this.list.concat(result.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
      }
    }
  },
  render() {
    return (
      <div style={{ overflow: 'hidden' }}>
        <Sticky
          class={'sticky'}
          style={{
            background: 'var(--van-primary)',
            height: this.height + 'px !important',
            width: '100%'
          }}
        >
          <div ref="headers">
            <ColHeader
              title="陪练课"
              isFixed={false}
              border={false}
              backIconColor="white"
              background="var(--van-primary)"
              color="#fff"
            />
            <ColSearch
              placeholder="请输入老师名称"
              inputBackground="white"
              background="var(--van-primary)"
              onSearch={this.onSearch}
            />
            <div class={styles.filterSection}>
              <div>
                <Button
                  class={[styles.btn]}
                  type="primary"
                  size="small"
                  round
                  plain
                  onClick={() => {
                    this.searchStatus = !this.searchStatus
                    this.openStatus = !this.openStatus
                    this.searchType = 'organ'
                  }}
                >
                  {this.params.subjectName}
                  <Icon
                    classPrefix="iconfont"
                    name="down"
                    size={8}
                    style={{ marginLeft: '4px' }}
                    color="var(--van-primary)"
                  />
                </Button>
                <Button class={[styles.btn]} size="small" round plain>
                  30天内未约满
                </Button>
              </div>
              <div>
                <div
                  class={styles.dataItem}
                  onClick={() => {
                    this.show = true
                  }}
                >
                  筛选
                  <Icon
                    classPrefix="iconfont"
                    name="down"
                    size={8}
                    style={{ marginLeft: '4px' }}
                    color="var(--van-primary)"
                  />
                </div>
              </div>
            </div>
          </div>
        </Sticky>

        {this.dataShow ? (
          <List
            v-model:loading={this.loading}
            finished={this.finished}
            finishedText=" "
            immediateCheck={false}
            class={[styles.practiceList, 'mb12']}
            onLoad={this.getList}
          >
            {this.list.map((item: any) => (
              <PracticeItem
                item={item}
                onClick={() => {
                  this.$router.push({
                    path: '/teacherHome',
                    query: {
                      teacherId: item.teacherId,
                      tabs: 'practice',
                      subjectId: this.params.subjectId
                    }
                  })
                }}
              />
            ))}
          </List>
        ) : (
          <ColResult
            btnStatus={false}
            classImgSize="SMALL"
            tips="暂无陪练老师"
          />
        )}

        <ActionSheet
          show={this.show}
          actions={actions}
          cancelText="取消"
          onSelect={this.onSheetSelect}
          onCancel={() => (this.show = false)}
        />

        <Popup
          show={this.searchStatus}
          position="bottom"
          round
          closeable
          safe-area-inset-bottom
          onClose={() => (this.searchStatus = false)}
          onClosed={() => (this.openStatus = false)}
        >
          {/* {this.searchType === 'all' && <AllSearch onSort={this.onSort} />} */}
          {this.searchType === 'organ' && this.openStatus && (
            <OrganSearch
              subjectList={this.subjectList}
              onSort={this.onSort}
              v-model={this.params.subjectId}
              v-model:subjectName={this.params.subjectName}
            />
          )}
        </Popup>
      </div>
    )
  }
})
