import OHeader from '@/components/o-header'
import { Cell, CellGroup, Grid, GridItem, Image, List, Picker, Popup, Tag } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import styles from './index.module.less'
import iconStudent from '@/common/images/icon_student.png'
import request from '@/helpers/request'
import OFullRefresh from '@/components/o-full-refresh'
import OEmpty from '@/components/o-empty'
import { useRoute } from 'vue-router'
import { moneyFormat } from '@/helpers/utils'

export default defineComponent({
  name: 'practice-detail',
  setup() {
    const route = useRoute()
    const state = reactive({
      subjectStatus: false,
      subjectList: [] as any,
      isClick: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false,
        refreshing: false,
        height: 0 // 页面头部高度，为了处理下拉刷新用的
      },
      subjectName: '全部声部',
      params: {
        type: null,
        subjectId: null,
        page: 1,
        rows: 20
      },
      statistics: {
        standardSalary: 0,
        targetNum: 0,
        actualSalary: 0
      }
    })

    const getTrainingStatistics = async () => {
      try {
        const { data } = await request.post(
          '/api-school/schoolWeekSalaryRecord/detailInfo/trainingTitle',
          {
            data: {
              id: route.query.id
            }
          }
        )
        state.statistics = {
          standardSalary: data.standardSalary || 0,
          targetNum: data.targetNum || 0,
          actualSalary: data.actualSalary || 0
        }
        console.log(data)
      } catch {
        //
      }
    }

    // 获取声部
    const getSubjects = async () => {
      try {
        const { data } = await request.post('/api-school/subjectBasicConfig/page', {
          data: {
            page: 1,
            rows: 50
          }
        })

        state.subjectList = data.rows || []
        state.subjectList.unshift({
          subjectId: '',
          subjectName: '全部声部'
        })
      } catch {
        //
      }
    }

    // api-school/schoolWeekSalaryRecord/detailInfo/trainingPage
    const getList = async () => {
      try {
        if (state.isClick) return
        state.isClick = true
        const res = await request.post(
          '/api-school/schoolWeekSalaryRecord/detailInfo/trainingPage',
          {
            data: {
              ...state.params,
              id: route.query.id
            }
          }
        )
        state.listState.loading = false
        state.listState.refreshing = false
        const result = res.data || {}
        console.log(result)
        // 处理重复请求数据
        if (state.list.length > 0 && result.current === 1) {
          return
        }

        const rows = result.rows || []
        rows.forEach((item: any) => {
          item.subjectNameList = item.subjectNames ? item.subjectNames.split(',') : []
        })

        state.list = state.list.concat(rows || [])
        state.listState.finished = result.current >= result.pages
        state.params.page = result.current + 1
        state.listState.dataShow = state.list.length > 0
        state.isClick = false
      } catch {
        state.listState.dataShow = false
        state.listState.finished = true
        state.listState.refreshing = false
        state.isClick = false
      }
    }

    const onRefresh = () => {
      state.params.page = 1
      state.list = []
      state.listState.dataShow = true // 判断是否有数据
      state.listState.loading = false
      state.listState.finished = false
      getList()
    }

    onMounted(() => {
      getTrainingStatistics()
      getSubjects()
      getList()
    })
    return () => (
      <>
        <OHeader />

        <div class={styles.item}>
          <Cell center>
            {{
              title: () => (
                <div class={styles.itemTitle}>
                  <div class={styles.titleLine}></div>
                  <span>练习奖励</span>
                </div>
              )
            }}
          </Cell>
          <Grid class={styles.grid} columnNum={3} border={false}>
            <GridItem class={styles.gridBorderRight}>
              <div class={styles.gridItem}>
                <div class={styles.gridItemTop}>
                  <span class={styles.topNum} style={{ color: '#333' }}>
                    {moneyFormat(state.statistics.standardSalary || 0)}
                  </span>
                  元/人
                </div>
                <div>奖励标准</div>
              </div>
            </GridItem>
            <GridItem class={styles.gridBorderRight}>
              <div class={styles.gridItem}>
                <div class={styles.gridItemTop}>
                  <span class={styles.topNum} style={{ color: '#333' }}>
                    {state.statistics.targetNum}
                  </span>
                  人
                </div>
                <div>练习达标人数</div>
              </div>
            </GridItem>
            <GridItem>
              <div class={styles.gridItem}>
                <div class={styles.gridItemTop}>
                  <span class={styles.topNum}>
                    {moneyFormat(state.statistics.actualSalary || 0)}
                  </span>
                  元
                </div>
                <div>奖励金额</div>
              </div>
            </GridItem>
          </Grid>
        </div>

        <div class={'searchGroup-single'} style="padding-top: 0 !important;">
          <div
            class={['searchItem', state.subjectStatus && 'searchItem-active']}
            onClick={() => {
              state.subjectStatus = !state.subjectStatus
            }}
          >
            {state.subjectName}
          </div>
        </div>
        {state.listState.dataShow ? (
          // <OFullRefresh
          //   v-model:modelValue={state.listState.refreshing}
          //   onRefresh={onRefresh}
          //   style={{
          //     minHeight: 'auto' //`calc(100vh - ${state.listState.height}px)`
          //   }}
          // >
          <List
            // v-model:loading={state.listState.loading}
            finished={state.listState.finished}
            finishedText=" "
            class={[styles.liveList]}
            onLoad={getList}
            immediateCheck={false}
          >
            <CellGroup inset class={styles.cellGroup}>
              {state.list.map((item: any) => (
                <Cell center>
                  {{
                    icon: () => <Image src={item.avatar || iconStudent} class={styles.img} />,
                    title: () => (
                      <div class={styles.userInfo}>
                        <div class={styles.userName}>{item.nickname}</div>
                        <div class={styles.subjectNames}>
                          {item.subjectNameList.map((item: any) => (
                            <Tag textColor="#F67146" color="#FFE7DA">
                              {item}
                            </Tag>
                          ))}
                        </div>
                      </div>
                    ),
                    value: () => (
                      <div class={styles.mins}>
                        <div class={styles.nums}>
                          <span>{item.practiceTimes}</span> 分钟
                        </div>
                        <div class={styles.text}>练习时长</div>
                      </div>
                    )
                  }}
                </Cell>
              ))}
            </CellGroup>
          </List>
        ) : (
          // </OFullRefresh>
          <OEmpty btnStatus={false} tips="暂无数据" />
        )}

        <Popup
          v-model:show={state.subjectStatus}
          position="bottom"
          round
          class={'popupBottomSearch'}
        >
          <Picker
            columns={state.subjectList}
            onCancel={() => (state.subjectStatus = false)}
            onConfirm={(val: any) => {
              console.log(val)
              const selectOptions = val.selectedOptions[0]
              state.subjectName = selectOptions.subjectName
              state.params.subjectId = selectOptions.subjectId
              onRefresh()
              state.subjectStatus = false
            }}
            columnsFieldNames={{ text: 'subjectName', value: 'subjectId' }}
          />
        </Popup>
      </>
    )
  }
})
