import MHeader from '@/components/m-header';
import MSticky from '@/components/m-sticky';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import { useRoute, useRouter } from 'vue-router';
import {
  Button,
  Cell,
  CellGroup,
  Checkbox,
  CheckboxGroup,
  Image,
  List,
  showToast
} from 'vant';
import iconBook from './images/icon-book.png';
import request from '@/helpers/request';
import MEmpty from '@/components/m-empty';
import { browser } from '@/helpers/utils';
import { postMessage } from '@/helpers/native-message';

export default defineComponent({
  name: 'wroing-book',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const checkboxRefs = ref([] as any);
    const forms = reactive({
      type: route.query.type,
      list: [] as any,
      checked: [] as any,
      isClick: false,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        page: 1,
        rows: 20
      }
    });

    const getList = async () => {
      try {
        if (forms.isClick) return;
        forms.isClick = true;
        const res = await request.post('/edu-app/knowledgePoint/list ', {
          data: {
            ...forms.params
          }
        });
        forms.listState.loading = false;
        const result = res.data || {};
        // 处理重复请求数据
        if (forms.list.length > 0 && result.current === 1) {
          return;
        }
        forms.list = forms.list.concat(result.rows || []);
        forms.listState.finished = result.current >= result.pages;
        forms.params.page = result.current + 1;
        forms.listState.dataShow = forms.list.length > 0;
        forms.isClick = false;
      } catch {
        forms.listState.dataShow = false;
        forms.listState.finished = true;
        forms.isClick = false;
      }
    };

    const checkboxToggle = (index: number) => {
      checkboxRefs.value[index].toggle();
    };

    const onSubmit = () => {
      try {
        if (forms.checked.length <= 0) {
          showToast('请选择知识点');
          return;
        }
        if (forms.type === 'TEST') {
          // 模拟测试
          router.push({
            path: '/examination-mode',
            query: { knowledgePointIds: forms.checked.join(',') }
          });
        } else {
          router.push({
            path: '/practice-mode',
            query: { knowledgePointIds: forms.checked.join(',') }
          });
        }
      } catch {
        //
      }
    };
    onMounted(() => {
      getList();
    });
    return () => (
      <div class={styles.woringBook}>
        <MSticky position="top">
          <MHeader border={false} background="transparent">
            {{
              content: () => (
                <div class={styles.woringHeader}>
                  <i
                    onClick={() => {
                      if (browser().isApp) {
                        postMessage({
                          api: 'goBack'
                        });
                      } else {
                        router.back();
                      }
                    }}
                    class={[
                      'van-badge__wrapper van-icon van-icon-arrow-left van-nav-bar__arrow',
                      styles.leftArrow
                    ]}></i>
                  <span class={styles.title}>
                    <i></i>
                  </span>
                </div>
              )
            }}
          </MHeader>
        </MSticky>

        <div class={styles.woringSecgtion}>
          <div class={styles.title}>请选择知识点</div>
          {forms.listState.dataShow ? (
            <List
              finished={forms.listState.finished}
              finishedText=" "
              class={[styles.container, styles.containerInformation]}
              onLoad={getList}
              immediateCheck={false}>
              <CellGroup border={false}>
                <CheckboxGroup v-model={forms.checked}>
                  {forms.list.map((item: any, index: number) => (
                    <Cell
                      center
                      onClick={() => checkboxToggle(index)}
                      class={styles.cell}>
                      {{
                        icon: () => (
                          <Image src={iconBook} class={styles.iconImg} />
                        ),
                        title: () => (
                          <div class={styles.cellTitle}>{item.name}</div>
                        ),
                        label: () => (
                          <p class={styles.cellContent}>
                            共<span>{item.questionNum}</span>道题
                          </p>
                        ),
                        'right-icon': () => (
                          <Checkbox
                            name={item.id}
                            ref={el => (checkboxRefs.value[index] = el)}
                            onClick={(e: MouseEvent) => e.stopPropagation()}
                          />
                        )
                      }}
                    </Cell>
                  ))}
                </CheckboxGroup>
              </CellGroup>
            </List>
          ) : (
            <MEmpty description="暂无知识点" />
          )}
        </div>

        {/* {forms.list.length <= 0 && !forms.loading && (
                    <div class={styles.emptyContainer}>
                      <MEmpty description="暂无知识点" />
                    </div>
                  )} */}
        <MSticky position="bottom" varName="--bottom-height">
          <div class={'btnGroup'}>
            <Button round block type="primary" onClick={onSubmit}>
              确认
            </Button>
          </div>
        </MSticky>
      </div>
    );
  }
});
