import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import MSticky from '@/components/m-sticky';
import MHeader from '@/components/m-header';
import { Cell, CellGroup, Grid, GridItem, List } from 'vant';
import MFullRefresh from '@/components/m-full-refresh';
import v3 from './images/v3.png';
import icon_student from '@common/images/icon-student-default.png';
import request from '@/helpers/request';
import TrainModel from './train-model';
import MEmpty from '@/components/m-empty';
import { useRouter } from 'vue-router';
import SkeletionIndexModal from './skeletion-index.modal';

export default defineComponent({
  name: 'train-statistics',
  setup() {
    const trainParams = sessionStorage.getItem('trainParams');
    sessionStorage.removeItem('trainParams');
    let params = null;
    if (trainParams) {
      const tempResult = JSON.parse(trainParams);
      params = {
        ...tempResult,
        page: 1,
        rows: 20
      };
    }
    const router = useRouter();
    const forms = reactive({
      isClick: false,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: true,
        finished: false,
        refreshing: false
      },
      params: params
        ? params
        : {
            page: 1,
            rows: 20
          },
      list: []
    });

    const getList = async () => {
      try {
        if (forms.isClick) return;
        forms.isClick = true;
        const { data } = await request.get(
          '/api-web/schoolCloudStudy/countStudentTrain',
          {
            params: {
              ...forms.params
            }
          }
        );
        const result = data || {};
        // 判断是否有数据
        if (forms.listState.refreshing) {
          forms.list = result.rows || [];
        } else {
          forms.list = forms.list.concat(result.rows || []);
        }

        forms.listState.finished = result.pageNo >= result.totalPage;
        forms.params.page = result.pageNo + 1;
      } catch {
        forms.listState.finished = true;
      } finally {
        setTimeout(() => {
          forms.listState.dataShow = forms.list.length > 0;
          forms.listState.refreshing = false;
          forms.listState.loading = false;
          forms.isClick = false;
        }, 500);
      }
    };

    const onRefresh = () => {
      forms.params.page = 1;
      getList();
    };

    const onLoad = (value: any) => {
      forms.params = Object.assign(forms.params, value);
      onResetList();
    };

    const onHref = (item: any) => {
      sessionStorage.setItem('trainParams', JSON.stringify(forms.params));
      router.push({
        path: '/train-detail',
        query: {
          userId: item.userId,
          username: item.username,
          phone: item.phone,
          musicGroupName: item.musicGroupName,
          avatar: item.avatar,
          visitFlag: item.visitFlag
        }
      });
    };

    const onResetList = () => {
      forms.list = [];
      forms.params.page = 1;

      forms.listState.dataShow = true;
      forms.listState.loading = true;
      forms.listState.finished = false;
      forms.listState.refreshing = true;
      onRefresh();
    };
    onMounted(() => {
      // getList()
    });
    return () => (
      <div class={styles.visitList}>
        <MSticky position="top">
          <MHeader />
          <TrainModel onLoad={onLoad} selectValues={forms.params} />
        </MSticky>

        <SkeletionIndexModal v-model:show={forms.listState.loading}>
          <MFullRefresh
            v-model:modelValue={forms.listState.refreshing}
            onRefresh={() => onRefresh()}
            style={{
              minHeight: `calc(100vh - var(--header-height))`
            }}>
            <List
              finished={forms.listState.finished}
              finishedText=" "
              style={{ overflow: 'hidden', marginBottom: '18px' }}
              onLoad={getList}
              immediateCheck={false}>
              {forms.listState.dataShow ? (
                forms.list.map((item: any) => (
                  <CellGroup
                    class={styles['data-content']}
                    border={false}
                    onClick={() => onHref(item)}>
                    <Cell center>
                      {{
                        title: () => (
                          <div class={styles.teacher_info}>
                            {item.memberFlag && (
                              <img src={v3} class={styles.memberLogo} />
                            )}
                            <img
                              class={styles.logo}
                              src={item.avatar || icon_student}
                              alt=""
                            />
                            <p class={styles.userName}>{item.username}</p>
                          </div>
                        ),
                        default: () => (
                          <p class={styles.orchestraName}>
                            {item.musicGroupName}
                          </p>
                        )
                      }}
                    </Cell>
                    <Cell isLink clickable={false} center>
                      {{
                        title: () => (
                          <Grid border={false} columnNum={4} clickable>
                            <GridItem text="训练时长">
                              {{
                                icon: () => (
                                  <span>{item.totalPlayTime}分钟</span>
                                )
                              }}
                            </GridItem>
                            <GridItem text="训练次数">
                              {{
                                icon: () => (
                                  <span style="color: #01c1b5">
                                    {item.trainNum}次
                                  </span>
                                )
                              }}
                            </GridItem>
                            <GridItem text="训练天数">
                              {{
                                icon: () => (
                                  <span style="color: #ff802c">
                                    {item.trainDay}天
                                  </span>
                                )
                              }}
                            </GridItem>
                            <GridItem text="评测次数">
                              {{
                                icon: () => (
                                  <span style="color: #f79c00">
                                    {item.recordNum}次
                                  </span>
                                )
                              }}
                            </GridItem>
                          </Grid>
                        )
                      }}
                    </Cell>
                  </CellGroup>
                ))
              ) : (
                <MEmpty
                  style={{
                    minHeight: `calc(100vh - var(--header-height))`
                  }}
                  description="暂无数据"
                />
              )}
            </List>
          </MFullRefresh>
        </SkeletionIndexModal>
      </div>
    );
  }
});
