import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  Cell,
  CellGroup,
  Col,
  List,
  Picker,
  Popup,
  Row,
  Tab,
  Tabs
} from 'vant';
import MSticky from '@/components/m-sticky';
import icon1 from './images/icon1.png';
import icon2 from './images/icon2.png';
import icon3 from './images/icon3.png';
import icon4 from './images/icon4.png';
import iconTimer from './images/icon-timer.png';
import request from '@/helpers/request';
import { useRoute } from 'vue-router';
import { moneyFormat, numberFormat } from '@/helpers/utils';
import OFullRefresh from '@/components/m-full-refresh';
import OEmpty from '@/components/m-empty';

export default defineComponent({
  name: 'tenant-apply-data',
  setup() {
    const route = useRoute();
    const tabName = ref('all');
    const forms = reactive({
      id: route.query.id,
      classStatus: false,
      schoolId: null,
      schoolName: '全部学校',
      classList: [] as any,
      statObj: {} as any,
      classStatus1: false,
      schoolId1: null,
      schoolName1: '全部学校',
      classList1: [] as any,
      page: 1,
      rows: 20,
      isClick: false
    });

    const refreshing = ref(false);
    const loading = ref(true);
    const finished = ref(false);
    const showContact = ref(false);
    const list = ref([]);

    const getSchoolList = async () => {
      try {
        const { data } = await request.get('/edu-app/open/school/list', {
          params: {
            tenantId: forms.id
          }
        });
        const temp = [
          {
            value: '',
            text: '全部学校'
          }
        ];
        if (Array.isArray(data)) {
          data.forEach((item: any) => {
            temp.push({
              value: item.id,
              text: item.name
            });
          });
          forms.classList = temp;
          forms.classList1 = temp;
        }
      } catch {
        //
      }
    };

    const getStat = async () => {
      try {
        const { data } = await request.post(
          '/edu-app/open/school/registerStat',
          {
            data: {
              tenantId: forms.id,
              schoolId: forms.schoolId
            }
          }
        );
        forms.statObj = data;
      } catch {
        //
      }
    };

    const getOrderPage = async () => {
      if (forms.isClick) {
        return;
      }
      forms.isClick = true;
      if (refreshing.value) {
        list.value = [];
        forms.page = 1;
        refreshing.value = false;
      }
      try {
        const res = await request.post('/edu-app/open/school/orderPage', {
          data: {
            tenantId: forms.id,
            schoolId: forms.schoolId1,
            page: forms.page,
            rows: forms.rows
          }
        });

        if (list.value.length > 0 && res.data.current === 1) {
          return;
        }

        list.value = list.value.concat(res.data.rows || []);
        forms.page = res.data.current + 1;
        showContact.value = list.value.length > 0;
        loading.value = false;
        finished.value = res.data.current >= res.data.pages;
      } catch {
        showContact.value = false;
        finished.value = true;
      } finally {
        loading.value = false;
      }
      forms.isClick = false;
    };
    const onRefresh = () => {
      finished.value = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      loading.value = true;
      getOrderPage();
    };

    onMounted(async () => {
      document.title = '学生报名统计';
      await getSchoolList();
      await getStat();
      await getOrderPage();
    });
    return () => (
      <div class={styles.tenantApplyData}>
        <Tabs v-model:active={tabName.value} swipeable animated>
          <Tab title="数据总览" name={'all'}>
            <Cell
              class={styles.searchSchool}
              title={forms.schoolName}
              isLink
              arrowDirection="down"
              onClick={() => (forms.classStatus = true)}></Cell>

            <div class={styles.statisticsGroup}>
              <Row gutter={12}>
                <Col span={12}>
                  <div class={[styles.item, styles.item1]}>
                    <p class={styles.price}>
                      {moneyFormat(forms.statObj.totalAmount)}
                    </p>
                    <p class={styles.text}>
                      <img src={icon4} class={styles.icon} />
                      缴费总金额
                    </p>
                  </div>
                </Col>
                <Col span={12}>
                  <div class={[styles.item, styles.item1]}>
                    <p class={styles.price}>
                      {numberFormat(forms.statObj.totalNum)}
                    </p>
                    <p class={styles.text}>
                      <img src={icon1} class={styles.icon} />
                      缴费总人数
                    </p>
                  </div>
                </Col>
                <Col span={12}>
                  <div class={[styles.item, styles.item4]}>
                    <p class={styles.price}>
                      {moneyFormat(forms.statObj.vipAmount)}
                    </p>
                    <p class={styles.text}>
                      <img src={icon4} class={styles.icon} />
                      学练工具缴费金额
                    </p>
                  </div>
                </Col>
                <Col span={12}>
                  <div class={[styles.item, styles.item4]}>
                    <p class={styles.price}>
                      {numberFormat(forms.statObj.vipNum)}
                    </p>
                    <p class={styles.text}>
                      <img src={icon3} class={styles.icon} />
                      学练工具购买人数
                    </p>
                  </div>
                </Col>
                <Col span={12}>
                  <div class={[styles.item, styles.item3]}>
                    <p class={styles.price}>
                      {moneyFormat(forms.statObj.instrumentAmount)}
                    </p>
                    <p class={styles.text}>
                      <img src={icon4} class={styles.icon} />
                      乐器缴费金额
                    </p>
                  </div>
                </Col>
                <Col span={12}>
                  <div class={[styles.item, styles.item3]}>
                    <p class={styles.price}>
                      {numberFormat(forms.statObj.instrumentNum)}
                    </p>
                    <p class={styles.text}>
                      <img src={icon2} class={styles.icon} />
                      乐器购买人数
                    </p>
                  </div>
                </Col>
              </Row>
            </div>
          </Tab>
          <Tab title="购买详情" name={'detail'}>
            <Cell
              class={styles.searchSchool}
              title={forms.schoolName1}
              isLink
              arrowDirection="down"
              onClick={() => (forms.classStatus1 = true)}></Cell>
            <div class={styles.buyContainer}>
              <div class={styles.buyList}>
                {showContact.value ? (
                  <OFullRefresh
                    v-model:modelValue={refreshing.value}
                    onRefresh={onRefresh}
                    class={styles.refreshC}>
                    <List
                      loading-text=" "
                      finished={finished.value}
                      finished-text=" "
                      onLoad={getOrderPage}>
                      {list.value.map((item: any) => (
                        <CellGroup class={styles.buyItem} border={false}>
                          <Cell>
                            {{
                              title: () => (
                                <div class={styles.buyHeader}>
                                  <span class={styles.buyTimer}>
                                    <img
                                      src={iconTimer}
                                      class={styles.iconTimer}
                                    />
                                    {item.payTime}
                                  </span>
                                  <span class={styles.buyPrice}>
                                    <i>¥</i>{' '}
                                    {moneyFormat(item.paymentCashAmount)}
                                  </span>
                                </div>
                              )
                            }}
                          </Cell>
                          <Cell>
                            {{
                              title: () => (
                                <div class={styles.contact}>
                                  <span class={styles.b}>{item.userName}</span>
                                  <span class={styles.b}>
                                    {item.schoolName}
                                  </span>
                                </div>
                              ),
                              label: () => (
                                <div class={styles.buyContent}>
                                  <span>购买内容</span>
                                  {item.goodsName}
                                </div>
                              )
                            }}
                          </Cell>
                        </CellGroup>
                      ))}
                    </List>
                  </OFullRefresh>
                ) : (
                  ''
                )}

                {!showContact.value && !loading.value && (
                  <OEmpty description="暂无购买详情" class={styles.emptyC} />
                )}
              </div>
            </div>
          </Tab>
        </Tabs>

        <Popup
          v-model:show={forms.classStatus}
          position="bottom"
          round
          class={'popupBottomSearch'}>
          <Picker
            showToolbar
            columns={forms.classList}
            onCancel={() => (forms.classStatus = false)}
            onConfirm={(val: any) => {
              const selectedOption = val.selectedOptions[0];
              console.log(selectedOption, 'selectedOption');
              forms.schoolId = selectedOption.value;
              forms.schoolName = selectedOption.text;
              getStat();
              forms.classStatus = false;
            }}
          />
        </Popup>

        <Popup
          v-model:show={forms.classStatus1}
          position="bottom"
          round
          class={'popupBottomSearch'}>
          <Picker
            showToolbar
            columns={forms.classList1}
            onCancel={() => (forms.classStatus1 = false)}
            onConfirm={(val: any) => {
              const selectedOption = val.selectedOptions[0];
              forms.schoolId1 = selectedOption.value;
              forms.schoolName1 = selectedOption.text;
              refreshing.value = true;
              getOrderPage();
              forms.classStatus1 = false;
            }}
          />
        </Popup>
      </div>
    );
  }
});
