import MHeader from '@/components/m-header';
import MSticky from '@/components/m-sticky';
import {
  ActionBar,
  Button,
  Cell,
  CellGroup,
  DropdownItem,
  DropdownMenu,
  Field,
  Icon,
  Image,
  List,
  Popup,
  showToast
} 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';
import iconEdit from '@/common/images/icon-edit.png';
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: [],
      showAddressPopup: false,
      siteName: '',
      selectSite: {} as any
    });

    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 {
        setTimeout(() => {
          forms.listState.dataShow = forms.list.length > 0;
          forms.listState.refreshing = false;
          forms.listState.loading = false;
          forms.isClick = false;
        }, 500);
      }
    };

    // 红点
    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 onSubmitUpdateSite = async () => {
      try {
        if (!forms.siteName) {
          showToast('请输入场地名称');
          return;
        }
        await request.post('/api-web/classGroup/teachingPointCourseSchedule', {
          hideLoading: false,
          data: {
            courseScheduleId: forms.selectSite.courseId,
            teachingPoint: forms.siteName
          }
        });
        forms.showAddressPopup = false;
        forms.listState.refreshing = true;
        onRefresh();
      } 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', marginBottom: '18px' }}
              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: () =>
                              item.courseStatus === 'OVER' ? (
                                <p
                                  class={[styles.address]}
                                  onClick={() => {
                                    if (item.teachingPoint) return;
                                    forms.selectSite = item;
                                    forms.siteName = item.teachingPoint;
                                    forms.showAddressPopup = true;
                                  }}>
                                  <p
                                    class={[
                                      styles.overhide,
                                      item.teachingPoint ? '' : styles.red
                                    ]}>
                                    {item.teachingPoint || '未设置场地'}
                                  </p>
                                  {item.teachingPoint ? (
                                    ''
                                  ) : (
                                    <Icon
                                      name={iconEdit}
                                      class={styles.iconEdit}
                                    />
                                  )}
                                </p>
                              ) : (
                                <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="cover"
                              />
                            ),
                            title: () => (
                              <div>
                                <div class={styles.classname}>
                                  {item.courseName}
                                </div>
                                <div class={styles.name}>
                                  {item.teacherName}

                                  {item.startClassTime && item.endClassTime ? (
                                    <span
                                      style={{
                                        paddingLeft: '6px'
                                      }}>
                                      {dayjs(item.startClassTime).format(
                                        'MM-DD HH:mm'
                                      ) +
                                        '~' +
                                        dayjs(item.endClassTime).format(
                                          'HH:mm'
                                        )}
                                    </span>
                                  ) : (
                                    ''
                                  )}
                                </div>
                              </div>
                            )
                          }}
                        </Cell>
                      </CellGroup>
                      <CellGroup class={styles.cellGroup} border={false}>
                        <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}
                                          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}
        />

        <Popup
          v-model:show={forms.showAddressPopup}
          round
          onClose={() => {
            forms.siteName = '';
            forms.selectSite = {};
          }}>
          <div class={styles.popupContainer}>
            <h2>设置场地</h2>
            <Field
              placeholder="请输入场地名称"
              v-model={forms.siteName}
              border={false}
              class={styles.field}
              maxlength={15}
              autocomplete="off"
            />
            <div class={['btnGroupPopup']}>
              <Button
                round
                onClick={() => {
                  forms.showAddressPopup = false;
                }}>
                取消
              </Button>
              <Button type="primary" round onClick={onSubmitUpdateSite}>
                确定
              </Button>
            </div>
          </div>
        </Popup>
      </div>
    );
  }
});
