import MHeader from '@/components/m-header';
import MSticky from '@/components/m-sticky';
import {
  CellGroup,
  DropdownItem,
  DropdownMenu,
  List,
  Skeleton,
  Tab,
  Tabs
} from 'vant';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import MFullRefresh from '@/components/m-full-refresh';
import ListItem from './list-item';
import SkeletionItem from './skeletion-item';
import MEmpty from '@/components/m-empty';
import MSearch from '@/components/m-search';
import DropDownModal from '../site-management/drop-down-modal';
import { musicGroupQuitQueryPage } from './api';
import { MusicGroupQuitPageDto } from './schedule';
import { useRouter } from 'vue-router';

export default defineComponent({
  name: 'schedule-manage',
  setup() {
    const key = 'schedule-manage-tab-name';
    const toggleTabName = (type: 'set' | 'get') => {
      if (type === 'set') {
        sessionStorage.setItem(key, todoData.tabActive);
      } else {
        return sessionStorage.getItem(key) || '';
      }
    };
    const router = useRouter();

    const todoData = reactive({
      tabActive: toggleTabName('get') as 'todo' | 'complete',
      examineLoading: true,
      refreshLoading: false,
      examineFinish: false,
      /** 待审批列表 */
      examineList: [] as MusicGroupQuitPageDto[],
      examinePage: {
        page: 1,
        rows: 20
      },
      examineSkelet: true,
      /** 完成列表 */
      completeList: [] as MusicGroupQuitPageDto[],
      completePage: {
        page: 1,
        rows: 20
      },
      completeResh: false,
      completeLoading: false,
      completeSkelet: true,
      completeFinish: false,
      completeActive: '',
      completeColumns: [{ text: '全部活动', value: '' }],

      options: [
        { text: '全部状态', value: '' },
        { text: '已通过', value: 'PASS' },
        { text: '未通过', value: 'REJECT' }
      ],
      optionTitle: '全部状态',
      activeOption: '' as any,
      search: ''
    });
    const getExamine = async () => {
      console.log('请求');
      todoData.examineLoading = true;
      musicGroupQuitQueryPage({
        page: todoData.examinePage.page,
        rows: todoData.examinePage.rows,
        status: 'ING'
      })
        .then(res => {
          if (todoData.refreshLoading) {
            todoData.examineList = [];
          }
          const rows: MusicGroupQuitPageDto[] = Array.isArray(res?.data?.rows)
            ? res.data.rows
            : [];
          todoData.examineList = todoData.examineList.concat(rows);
          if (!rows.length || rows.length < todoData.examinePage.rows) {
            todoData.examineFinish = true;
          }
        })
        .catch(() => {
          todoData.examineFinish = true;
        })
        .finally(() => {
          setTimeout(() => {
            todoData.examineLoading = false;
            todoData.refreshLoading = false;
            todoData.examineSkelet = false;
          }, 500);
        });
    };
    const getComplete = () => {
      if (todoData.completeLoading) return;
      console.log('请求', todoData.completeLoading, todoData.completeResh);
      todoData.completeLoading = true;
      musicGroupQuitQueryPage({
        page: todoData.completePage.page,
        rows: todoData.completePage.rows,
        search: todoData.search,
        status: todoData.activeOption
      })
        .then(res => {
          if (todoData.completeResh) {
            todoData.completeList = [];
          }
          const rows: MusicGroupQuitPageDto[] = Array.isArray(res?.data?.rows)
            ? res.data.rows
            : [];
          todoData.completeList = todoData.completeList.concat(rows);
          if (!rows.length || rows.length < todoData.completePage.rows) {
            todoData.completeFinish = true;
          } else {
            todoData.completeFinish = false;
          }
        })
        .catch(() => {
          todoData.completeFinish = true;
        })
        .finally(() => {
          setTimeout(() => {
            todoData.completeLoading = false;
            todoData.completeResh = false;
            todoData.completeSkelet = false;
          }, 500);
        });
    };

    onMounted(() => {
      getExamine();
      getComplete();
    });

    /** 下载菜单改变 */
    const changeDropTitle = (option: any) => {
      todoData.optionTitle =
        todoData.activeOption === 'PASS'
          ? '已通过'
          : todoData.activeOption === 'REJECT'
          ? '未通过'
          : '全部状态';
      todoData.examinePage.page = 1;
      todoData.completeResh = true;
      getComplete();
    };

    /** 去详情页 */
    const handleGoto = (item: MusicGroupQuitPageDto) => {
      toggleTabName('set');
      router.push({
        path: 'schedule-manage-detail',
        query: {
          musicGroupQuitId: item.musicGroupQuitId
        }
      });
    };

    return () => (
      <div class={styles['schedule-manage']}>
        <MSticky
          class="schedule-manage-top"
          position="top">
          <MHeader></MHeader>
        </MSticky>
        <Tabs
          swipeable
          animated
          v-model:active={todoData.tabActive}>
          <Tab name="todo" title="待审批">
            <MFullRefresh
              v-model:modelValue={todoData.refreshLoading}
              onRefresh={() => {
                todoData.examinePage.page = 1;
                todoData.examineFinish = false;
                getExamine();
              }}>
              <List
                loading={todoData.examineLoading}
                finished={todoData.examineFinish}
                class={[styles.list, styles.todo]}
                onLoad={() => {
                  todoData.examinePage.page++;
                  getExamine();
                }}>
                {todoData.examineSkelet ? (
                  <div class={[styles.list, styles.listHide]}>
                    <Skeleton loading={true}>
                      {{
                        template: () => (
                          <div style={{ width: '100%' }}>
                            {new Array(10).fill(1).map((item: any) => (
                              <SkeletionItem />
                            ))}
                          </div>
                        )
                      }}
                    </Skeleton>
                  </div>
                ) : (
                  <>
                    {todoData.examineList.map((item: MusicGroupQuitPageDto) => {
                      return (
                        <ListItem
                          isLink={true}
                          item={item}
                          onGoto={() => handleGoto(item)}
                        />
                      );
                    })}
                    {!todoData.examineList.length && (
                      <MEmpty
                        description="暂无数据"
                        style={{
                          minHeight: '100%'
                        }}
                      />
                    )}
                  </>
                )}
              </List>
            </MFullRefresh>
          </Tab>
          <Tab name="complete" title="已完成">
            <div class={styles.menubox}>
              <DropdownMenu>
                <DropdownItem
                  teleport="body"
                  title={todoData.optionTitle}
                  v-model={todoData.activeOption}
                  options={todoData.options}
                  onChange={changeDropTitle}
                  class={styles.optionModel}
                />
              </DropdownMenu>
              <MSearch
                placeholder="请输入学员名称"
                disabled={todoData.completeLoading}
                onSearch={value => {
                  todoData.search = value;
                  todoData.completePage.page = 1;
                  todoData.completeResh = true;
                  getComplete();
                }}
              />
            </div>
            <MFullRefresh
              v-model:modelValue={todoData.completeResh}
              onRefresh={() => {
                console.log('下拉');
                todoData.completePage.page = 1;
                todoData.completeFinish = false;
                getComplete();
              }}>
              <List
                loading={todoData.completeLoading}
                finished={todoData.completeFinish}
                class={styles.list}
                onLoad={() => {
                  todoData.completePage.page++;
                  console.log('触底', todoData.completeResh);
                  getComplete();
                }}>
                {todoData.completeSkelet ? (
                  <div class={[styles.list, styles.listHide]}>
                    <Skeleton loading={true}>
                      {{
                        template: () => (
                          <div style={{ width: '100%' }}>
                            {new Array(4).fill(1).map((item: any) => (
                              <SkeletionItem />
                            ))}
                          </div>
                        )
                      }}
                    </Skeleton>
                  </div>
                ) : (
                  <>
                    {todoData.completeList.map(item => (
                      <ListItem
                        item={item}
                        isLink={true}
                        onGoto={() => handleGoto(item)}
                        status={
                          item.status === 'PASS'
                            ? 'success'
                            : item.status === 'REJECT'
                            ? 'error'
                            : ''
                        }
                      />
                    ))}
                    {!todoData.completeList.length && (
                      <MEmpty
                        description="暂无数据"
                        style={{
                          minHeight: '100%'
                        }}
                      />
                    )}
                  </>
                )}
              </List>
            </MFullRefresh>
          </Tab>
        </Tabs>
      </div>
    );
  }
});
