import { defineComponent, onMounted, reactive } from 'vue';
import styles from './train-detail.module.less';
import MSticky from '@/components/m-sticky';
import MHeader from '@/components/m-header';
import {
  Cell,
  CellGroup,
  Col,
  DatePicker,
  Grid,
  GridItem,
  Icon,
  List,
  Popup,
  Row,
  showToast
} from 'vant';
import icon_student from '@common/images/icon-student-default.png';
import arrowIcon from './images/arrow_down.png';
import score1 from './images/1.png';
import score2 from './images/2.png';
import score3 from './images/3.png';
import { useRoute } from 'vue-router';
import { formatterDatePicker } from '@/helpers/utils';
import dayjs from 'dayjs';
import MFullRefresh from '@/components/m-full-refresh';
import request from '@/helpers/request';
import MEmpty from '@/components/m-empty';
import SkeletionDetailModal from './skeletion-detail-modal';
import { postMessage } from '@/helpers/native-message';

export default defineComponent({
  name: 'train-detail',
  setup() {
    const route = useRoute();
    const state = reactive({
      headerStatus: true,
      show: true,
      avatar: route.query.avatar as any,
      username: route.query.username as any,
      musicGroupName: route.query.musicGroupName as any,
      visitFlag: Number(route.query.visitFlag) || 0,
      dataForm: {
        // 时间下拉框
        type: null as any,
        status: false,
        minDate: new Date(2000, 0, 1),
        maxDate: new Date(2030, 11, 31),
        currentDate: [
          dayjs().format('YYYY'),
          dayjs().format('MM'),
          dayjs().format('DD')
        ] as any
      },
      dataList: [],
      loading: false,
      finished: false
    });
    const forms = reactive({
      isClick: false,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: true,
        finished: false,
        refreshing: false
      },
      params: {
        startTime: null as any,
        endTime: null as any,
        userId: route.query.userId as any,
        page: 1,
        rows: 20
      },
      list: []
    });

    const onChangeDate = (type: string) => {
      if (type == 'showEnd' && forms.params.startTime) {
        state.dataForm.minDate = new Date(
          dayjs(forms.params.startTime).valueOf()
        );
        state.dataForm.maxDate = new Date(2030, 11, 31);
        setTimeout(() => {
          state.dataForm.currentDate = forms.params.endTime
            ? new Date(dayjs(forms.params.endTime).valueOf())
            : new Date();
        }, 500);
      } else if (type == 'showStart' && forms.params.endTime) {
        state.dataForm.minDate = new Date(2000, 0, 1);
        state.dataForm.maxDate = new Date(
          dayjs(forms.params.endTime).valueOf()
        );
        setTimeout(() => {
          state.dataForm.currentDate = forms.params.startTime
            ? new Date(dayjs(forms.params.startTime).valueOf())
            : new Date();
        }, 500);
      }
      state.dataForm.status = true;
      state.dataForm.type = type;
    };

    const getList = async () => {
      try {
        if (forms.isClick) return;
        forms.isClick = true;
        const { data } = await request.get(
          '/api-web/schoolCloudStudy/queryMusicCompareRecord',
          {
            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 getLevelByScore = (score: number) => {
      let level = 3;
      if (score > 60 && score <= 80) {
        level = 2;
      } else if (score > 80) {
        level = 1;
      }
      return level;
    };
    const onRefresh = () => {
      forms.params.page = 1;
      getList();
    };

    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();
    };

    const showDetail = (item: any) => {
      if (item.notesDataIndex > 0) {
        postMessage({
          api: 'openWebView',
          content: {
            url:
              location.origin + `/accompany-web/?school=1/#/report/${item.id}`,
            orientation: 0,
            isHideTitle: true,
            statusBarTextColor: false,
            isOpenLight: true
          }
        });
      } else {
        showToast('本次评测未生成报告');
      }
    };

    onMounted(() => {
      getList();
    });

    return () => (
      <div class={styles.trainDetail}>
        <MSticky position="top">
          <MHeader />

          <div style={{ backgroundColor: '#f5f5f5', overflow: 'hidden' }}>
            <div class={styles.evaluation}>
              <Cell
                style="padding: 16px 12px; background-color: transparent"
                center>
                {{
                  title: () => (
                    <div class={styles.teacher_info}>
                      <img
                        class={styles.logo}
                        src={state.avatar || icon_student}
                        alt=""
                      />
                      <div class={styles.teacher_content}>
                        <p class={styles.username}>{state.username}</p>
                        <p class={styles.musicGroupName}>
                          {state.musicGroupName}
                        </p>
                      </div>
                    </div>
                  )
                }}
              </Cell>
            </div>

            {!state.visitFlag && (
              <Row class={styles.dataSearch} align="center" justify="center">
                <Col span={9} offset={1}>
                  <Cell isLink onClick={() => onChangeDate('showStart')}>
                    {{
                      'right-icon': () => (
                        <Icon
                          name={arrowIcon}
                          class={styles['search-icon']}
                          size={10}
                        />
                      ),
                      title: () =>
                        forms.params.startTime ? (
                          forms.params.startTime
                        ) : (
                          <span style={{ color: '#adadad' }}>开始日期</span>
                        )
                    }}
                  </Cell>
                </Col>
                <Col span={1} style={{ 'text-align': 'center' }}>
                  -
                </Col>
                <Col span={9}>
                  <Cell onClick={() => onChangeDate('showEnd')}>
                    {{
                      'right-icon': () => (
                        <Icon
                          name={arrowIcon}
                          class={styles['search-icon']}
                          size={10}
                        />
                      ),
                      title: () =>
                        forms.params.endTime ? (
                          forms.params.endTime
                        ) : (
                          <span style={{ color: '#adadad' }}>结束日期</span>
                        )
                    }}
                  </Cell>
                </Col>
                <Col span={4}>
                  {/* onSearch */}
                  <span
                    class={styles['btn-search']}
                    onClick={() => onResetList()}>
                    搜索
                  </span>
                </Col>
              </Row>
            )}
          </div>
        </MSticky>

        <Popup v-model:show={state.dataForm.status} position="bottom" round>
          <DatePicker
            v-model={state.dataForm.currentDate}
            formatter={formatterDatePicker}
            minDate={state.dataForm.minDate}
            maxDate={state.dataForm.maxDate}
            onCancel={() => (state.dataForm.status = false)}
            onConfirm={({ selectedValues }) => {
              let dataForm = state.dataForm;
              if (dataForm.type == 'showStart') {
                forms.params.startTime = selectedValues.join('-');
              } else if (dataForm.type == 'showEnd') {
                forms.params.endTime = selectedValues.join('-');
              }
              state.dataForm.status = false;
            }}
          />
        </Popup>

        <SkeletionDetailModal 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={() => showDetail(item)}>
                    <Cell
                      style={{ padding: '10px 12px 12px' }}
                      border
                      center
                      title-style="flex-basis: 45%;">
                      {{
                        title: () => (
                          <>
                            <span class={styles.scoreName}>
                              {item.sysMusicScoreName}
                            </span>
                            <p style="font-size: 14px; color: #808080;">
                              {item.createTime}
                            </p>
                          </>
                        ),
                        value: () => (
                          <p>
                            {getLevelByScore(item.score) === 1 && (
                              <img
                                class={styles.scoreImg}
                                src={score1}
                                alt=""></img>
                            )}
                            {getLevelByScore(item.score) === 2 && (
                              <img
                                class={styles.scoreImg}
                                src={score2}
                                alt=""></img>
                            )}
                            {getLevelByScore(item.score) === 3 && (
                              <img
                                class={styles.scoreImg}
                                src={score3}
                                alt=""></img>
                            )}
                          </p>
                        )
                      }}
                    </Cell>
                    <Cell
                      isLink
                      clickable={false}
                      center
                      style="padding: 12px 12px 16px">
                      {{
                        title: () => (
                          <Grid border={false} columnNum={4} clickable>
                            <GridItem text="综合得分">
                              {{ icon: () => <span>{item.score}分</span> }}
                            </GridItem>
                            <GridItem text="音准">
                              {{
                                icon: () => (
                                  <span style="color: #01C1B5">
                                    {item.intonation}分
                                  </span>
                                )
                              }}
                            </GridItem>
                            <GridItem text="节奏">
                              {{
                                icon: () => (
                                  <span style="color: #FF802C">
                                    {item.cadence}分
                                  </span>
                                )
                              }}
                            </GridItem>
                            <GridItem text="完成度">
                              {{
                                icon: () => (
                                  <span style="color: #F79C00">
                                    {item.integrity}分
                                  </span>
                                )
                              }}
                            </GridItem>
                          </Grid>
                        )
                      }}
                    </Cell>
                  </CellGroup>
                ))
              ) : (
                <MEmpty
                  style={{
                    minHeight: `calc(100vh - var(--header-height))`
                  }}
                  description="暂无训练详情"
                />
              )}
            </List>
          </MFullRefresh>
        </SkeletionDetailModal>
      </div>
    );
  }
});
