import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import MSticky from '@/components/m-sticky';
import MHeader from '@/components/m-header';
import MSearch from '@/components/m-search';
import {
  Cell,
  CellGroup,
  DropdownItem,
  DropdownMenu,
  Icon,
  List,
  Tag
} from 'vant';
import DropDownModal from '../site-management/drop-down-modal';
import { activeStatus, activityStatus } from '@/helpers/constant';
import SkeletionIndexModal from './skeletion-index-modal';
import MFullRefresh from '@/components/m-full-refresh';
import MEmpty from '@/components/m-empty';
import request from '@/helpers/request';
import iconAdd from '@/common/images/icon-add.png';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'activtiy-record',
  setup() {
    const router = useRouter();
    const dropDownRef = ref();
    const forms = reactive({
      activeValue: '',
      activeColumns: [{ text: '全部活动', value: '' }], //
      isClick: false,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: true,
        finished: false,
        refreshing: false
      },
      params: {
        type: '',
        keyword: '',
        page: 1,
        rows: 20
      },
      list: []
    });
    const onDropDownClose = (item: any) => {
      item.value && item.value.toggle();
    };
    const formatName = () => {
      let name = '';
      forms.activeColumns.forEach((item: any) => {
        if (forms.params.type === item.value) {
          name = item.text;
        }
      });
      return name;
    };

    const getList = async () => {
      try {
        if (forms.isClick) return;
        forms.isClick = true;
        const { data } = await request.post('/api-web/schoolActivity/page', {
          data: 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 onDetail = (item: any) => {
      router.push({
        path: '/activity-record-detail',
        query: {
          id: item.id
        }
      });
    };

    onMounted(() => {
      for (const key in activityStatus) {
        if (Object.prototype.hasOwnProperty.call(activityStatus, key)) {
          forms.activeColumns.push({
            text: activityStatus[key],
            value: key
          });
        }
      }

      getList();
    });
    return () => (
      <div class={styles['activity-record']}>
        <MSticky position="top">
          <MHeader>
            {{
              right: () => (
                <Icon
                  name={iconAdd}
                  class={styles.iconAdd}
                  onClick={() => {
                    router.push('activity-record-operation');
                  }}
                />
              )
            }}
          </MHeader>
          <MSearch
            placeholder="请输入活动名称"
            disabled={forms.listState.refreshing}
            onSearch={(val: string) => {
              forms.params.keyword = val;
              forms.listState.refreshing = true;
              onRefresh();
            }}>
            {{
              left: () => (
                <DropdownMenu
                  class={styles.patrolDetailDropDown}
                  closeOnClickOutside={false}>
                  <DropdownItem title={formatName()} ref={dropDownRef}>
                    <DropDownModal
                      selectValues={forms.params.type}
                      columns={forms.activeColumns}
                      open={dropDownRef.value.state.showPopup}
                      onDropDownClose={() => onDropDownClose(dropDownRef)}
                      onDropDownConfirm={(values: any) => {
                        forms.params.type = values[0];
                        onDropDownClose(dropDownRef);
                        forms.listState.refreshing = true;
                        onRefresh();
                      }}
                    />
                  </DropdownItem>
                </DropdownMenu>
              )
            }}
          </MSearch>
        </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
                    inset
                    class={styles.cellGroup}
                    onClick={() => onDetail(item)}>
                    <Cell
                      center
                      isLink
                      class={styles.cellTitle}
                      clickable={false}>
                      {{
                        icon: () => (
                          <Tag plain type="primary" class={styles.tag}>
                            {activityStatus[item.type]}
                          </Tag>
                        ),
                        title: () => (
                          <div class={[styles.title, 'van-ellipsis']}>
                            {item.name}
                          </div>
                        )
                      }}
                    </Cell>
                    <Cell
                      class={styles.cellTimer}
                      center
                      title={`活动日期：${dayjs(item.startTime).format(
                        'YYYY年MM月DD日'
                      )}`}
                      value={activeStatus[item.status]}
                      valueClass={[
                        item.status === 'PROCESSING' ? styles.ing : '',
                        item.status === 'END' ? styles.end : ''
                      ]}></Cell>
                  </CellGroup>
                ))
              ) : (
                <MEmpty
                  style={{
                    minHeight: `calc(100vh - var(--header-height))`
                  }}
                  description="暂无数据"
                />
              )}
            </List>
          </MFullRefresh>
        </SkeletionIndexModal>
      </div>
    );
  }
});
