import MHeader from '@/components/m-header';
import MSticky from '@/components/m-sticky';
import {
  ActionBar,
  Cell,
  CellGroup,
  DropdownItem,
  DropdownMenu,
  Icon,
  Image,
  List
} from 'vant';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import DropDownModal from './drop-down-modal';
import iconSetting from '@/common/images/icon-setting.png';
import iconMusic from '@/common/images/icon-music.png';
import iconTeacher from '@/common/images/icon-teacher-default.png';
import iconEmpty from './images/icon-empty.png';
import MImagePreview from '@/components/m-image-preview';
import SkeletonModal from './skeleton-modal';
import MEmpty from '@/components/m-empty';
import MFullRefresh from '@/components/m-full-refresh';
import { useRouter } from 'vue-router';
import request from '@/helpers/request';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'site-management',
  setup() {
    const router = useRouter();
    const dropDownItemRef = ref();
    const dropDownItemRef1 = ref();
    const forms = reactive({
      isClick: false,
      titleTimeValue: [],
      titleOrchestraValue: '',
      listState: {
        dataShow: true, // 判断是否有数据
        loading: true,
        finished: false,
        refreshing: false
      },
      params: {
        startTime: null,
        endTime: null,
        musicGroupId: '',
        page: 1,
        rows: 20
      },
      timeColumns: [],
      orchestraColumns: [{ text: '全部乐团', value: '' }], //
      imageShow: false,
      startPosition: 0,
      imagePreview: [] as string[],
      pointCourseStatus: false, // 红点
      list: []
    });

    const getInitTimer = (week = 4) => {
      const tempTimer: any = [];
      for (let i = 0; i < week; i++) {
        const startDay = dayjs()
          .subtract(i, 'week')
          .startOf('week')
          .add(1, 'day');
        const endDay = dayjs().subtract(i, 'week').endOf('week').add(1, 'day');
        tempTimer.push({
          text:
            startDay.format('YYYY/MM/DD') + ' - ' + endDay.format('YYYY/MM/DD'),
          value: [startDay.format('YYYY-MM-DD'), endDay.format('YYYY-MM-DD')]
        });
      }
      // console.log(tempTimer, 'tempTimer');
      forms.timeColumns = tempTimer;
      forms.titleTimeValue = tempTimer[0].value;
    };

    const onDropDownClose = (item: any) => {
      item.value && item.value.toggle();
    };

    const formatName = (type: string) => {
      if (type === 'orchestra') {
        let name = '';
        forms.orchestraColumns.forEach((item: any) => {
          if (forms.titleOrchestraValue === 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/classGroup/teachingPointCourse',
          {
            data: {
              ...forms.params,
              startTime: forms.titleTimeValue[0] || null,
              endTime: forms.titleTimeValue[1] || null
            }
          }
        );
        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 {
        forms.listState.dataShow = forms.list.length > 0;
        forms.listState.refreshing = false;
        forms.listState.loading = false;
        forms.isClick = false;
      }
    };

    // 红点
    const teachingPointCourse = async () => {
      try {
        const { data } = await request.post(
          '/api-web/classGroup/teachingPointRemind'
        );
        forms.pointCourseStatus = data || false;
      } catch {
        //
      }
    };

    // 乐团列表
    const musicGroupPage = async () => {
      try {
        const { data } = await request.get(
          '/api-web/cooperationOrgan/musicGroupPage'
        );
        (data || []).forEach((item: any) => {
          forms.orchestraColumns.push({
            text: item.name,
            value: item.id
          });
        });
      } catch {
        //
      }
    };

    const onRefresh = () => {
      forms.params.page = 1;
      getList();
    };

    onMounted(async () => {
      musicGroupPage();
      getInitTimer();
      await getList();
      teachingPointCourse();
    });
    return () => (
      <div class={styles.siteManagement}>
        <MSticky position="top">
          <MHeader>
            {{
              right: () => (
                <Icon
                  class={styles.iconSetting}
                  name={iconSetting}
                  dot={forms.pointCourseStatus}
                  onClick={() => {
                    router.push('/site-settings');
                  }}
                />
              )
            }}
          </MHeader>

          <DropdownMenu>
            <DropdownItem
              ref={dropDownItemRef}
              v-model={forms.titleTimeValue}
              options={forms.timeColumns as any}
              onChange={() => {
                forms.list = [];
                forms.listState.dataShow = true;
                onRefresh();
              }}></DropdownItem>
            <DropdownItem
              ref={dropDownItemRef1}
              title={formatName('orchestra')}>
              <DropDownModal
                selectValues={forms.titleOrchestraValue}
                columns={forms.orchestraColumns}
                open={dropDownItemRef1.value.state.showPopup}
                onDropDownClose={() => onDropDownClose(dropDownItemRef1)}
                onDropDownConfirm={(values: any) => {
                  forms.titleOrchestraValue = values[0];
                  onDropDownClose(dropDownItemRef1);
                  forms.params.musicGroupId = forms.titleOrchestraValue || '';
                  forms.list = [];
                  forms.listState.dataShow = true;
                  onRefresh();
                }}
              />
            </DropdownItem>
          </DropdownMenu>
        </MSticky>

        <SkeletonModal 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' }}
              onLoad={getList}
              immediateCheck={false}>
              {forms.listState.dataShow ? (
                forms.list.map((item: any) => {
                  const signPhotoList = item.signPhoto
                    ? item.signPhoto.split(',')
                    : [];
                  const signOutPhotoList = item.signOutPhoto
                    ? item.signOutPhoto.split(',')
                    : [];

                  return (
                    <div class={styles.siteItem}>
                      <CellGroup class={styles.cellGroup} border={false}>
                        <Cell border={false} center>
                          {{
                            title: () => (
                              <div class={styles.orchestraName}>
                                <img src={iconMusic} class={styles.iconMusic} />
                                <p class={styles.overhide}>
                                  {item.musicGroupName}
                                </p>
                              </div>
                            ),
                            default: () => (
                              <p class={[styles.address, styles.overhide]}>
                                {item.teachingPoint}
                              </p>
                            )
                          }}
                        </Cell>
                        <Cell center class={styles.username}>
                          {{
                            icon: () => (
                              <Image
                                src={item.teacherAvatar || iconTeacher}
                                class={styles.iconTeacher}
                                fit="contain"
                              />
                            ),
                            title: () => (
                              <div>
                                <div class={styles.classname}>
                                  {item.courseName}
                                </div>
                                <div class={styles.name}>
                                  {item.teacherName}
                                </div>
                              </div>
                            )
                          }}
                        </Cell>
                      </CellGroup>
                      <CellGroup class={styles.cellGroup}>
                        <div class={[styles.photoGroup]}>
                          <div class={styles.photoUp}>
                            <h3>
                              <span class={styles.photoTitle}>课前照片</span>
                            </h3>
                            {item.signPhoto ? (
                              <div class={styles.photoList}>
                                {signPhotoList.map(
                                  (img: string, index: number) =>
                                    index <= 2 && (
                                      <div
                                        class={styles.photo}
                                        onClick={() => {
                                          forms.imagePreview = signPhotoList;
                                          forms.imageShow = true;
                                          forms.startPosition = index;
                                        }}>
                                        <Image src={img} />
                                        {signPhotoList.length > 3 &&
                                        index === 2 ? (
                                          <div class={styles.photoMore}>
                                            +{signPhotoList.length - 3}
                                          </div>
                                        ) : (
                                          ''
                                        )}
                                      </div>
                                    )
                                )}
                              </div>
                            ) : (
                              <div class={styles.photoEmpty}>
                                <img src={iconEmpty} class={styles.iconEmpty} />
                                <p>老师未上传照片～</p>
                              </div>
                            )}
                          </div>
                          <div class={styles.photoDown}>
                            <h3>
                              <span class={styles.photoTitle}>课后照片</span>
                            </h3>
                            {item.signOutPhoto ? (
                              <div class={styles.photoList}>
                                {signOutPhotoList.map(
                                  (img: string, index: number) =>
                                    index <= 2 && (
                                      <div
                                        class={styles.photo}
                                        onClick={() => {
                                          forms.imagePreview = signOutPhotoList;
                                          forms.imageShow = true;
                                          forms.startPosition = index;
                                        }}>
                                        <Image
                                          src={img + '@base@tag=imgScale&w=120'}
                                          fit="cover"
                                        />
                                        {signOutPhotoList.length > 3 &&
                                        index === 2 ? (
                                          <div class={styles.photoMore}>
                                            +{signOutPhotoList.length - 3}
                                          </div>
                                        ) : (
                                          ''
                                        )}
                                      </div>
                                    )
                                )}
                              </div>
                            ) : (
                              <div class={styles.photoEmpty}>
                                <img src={iconEmpty} class={styles.iconEmpty} />
                                <p>老师未上传照片～</p>
                              </div>
                            )}
                          </div>
                        </div>
                      </CellGroup>
                    </div>
                  );
                })
              ) : (
                <MEmpty
                  style={{
                    minHeight: `calc(100vh - var(--header-height))`
                  }}
                  description="暂无数据"
                />
              )}
            </List>
          </MFullRefresh>
        </SkeletonModal>

        <MImagePreview
          v-model:show={forms.imageShow}
          images={forms.imagePreview}
          startPosition={forms.startPosition}
        />
      </div>
    );
  }
});
