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 { useRect } from '@vant/use'

// {"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: '',
        isScreen: false,
        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 {}

    const { height } = useRect((this as any).$refs.headers)
    this.height = height

    this.getList()
  },
  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', minHeight: '100vh' }}>
        <Sticky
          class={'sticky'}
          offsetTop={0}
          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"
                  type={this.params.isScreen ? 'primary' : 'default'}
                  round
                  plain
                  onClick={() => {
                    this.params.isScreen = !this.params.isScreen
                    this.onSort()
                  }}
                >
                  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
          v-model:show={this.show}
          actions={actions}
          cancelText="取消"
          onSelect={this.onSheetSelect}
          closeOnClickAction
          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>
    )
  }
})
