import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import SkeletionIndexModal from './skeletion-index-modal';
import { Cell, CellGroup, DropdownItem, DropdownMenu, Icon, Image } from 'vant';
import iconTeacher from '@/common/images/icon-teacher-default.png';
import iconSuccess from '@/common/images/icon-check-active.png';
import iconWarn from '@/common/images/icon-warn.png';
import SkeletionDetailModal from './skeletion-detail-modal';
import MHeader from '@/components/m-header';
import request from '@/helpers/request';
import { useRoute, useRouter } from 'vue-router';
import { coursesType, teacherAttendanceStatus } from '@/helpers/constant';
import dayjs from 'dayjs';
import MEmpty from '@/components/m-empty';
import DropDownModal from '../site-management/drop-down-modal';

export default defineComponent({
  name: 'teacher-attendance-detail',
  setup() {
    const dropDownItemRef1 = ref();
    const route = useRoute();
    const router = useRouter();
    const forms = reactive({
      teacherId: route.query.teacherId,
      classGroupId: route.query.classGroupId,
      listState: {
        loading: true,
        loadingList: true,
        dataShow: true,
        refreshing: false
      },
      classColumns: [
        { text: '全部状态', value: '' },
        { text: '正常', value: '1' },
        { text: '异常', value: '0' }
      ],
      typeColumns: [{ text: '全部类型', value: '' }],
      params: {
        courseType: '',
        signStatus: ''
      },
      teacherInfo: {} as any,
      list: []
    });

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

    const formatName = (type: string) => {
      if (type === 'orchestra') {
        let name = '';
        forms.typeColumns.forEach((item: any) => {
          if (forms.params.courseType === item.value) {
            name = item.text;
          }
        });
        return name;
      }
    };

    // 老师详情
    const getTeacherInfo = async () => {
      try {
        const { data } = await request.post(
          '/api-web/schoolTeacherAttendance/queryTeacherAttendance',
          {
            data: {
              teacherId: forms.teacherId,
              classGroupId: forms.classGroupId
            }
          }
        );
        const result = data || [];
        forms.teacherInfo = result[0] || {};
      } catch {
        //
      }
      forms.listState.loading = false;
    };

    const getList = async () => {
      try {
        const { data } = await request.post(
          '/api-web/schoolTeacherAttendance/getClassTeacherAttendance',
          {
            data: {
              ...forms.params,
              teacherId: forms.teacherId,
              classGroupId: forms.classGroupId
            }
          }
        );
        const result = data || [];
        forms.list = result || [];
      } catch {
        //
      } finally {
        forms.listState.dataShow = forms.list.length > 0;
        forms.listState.refreshing = false;
        forms.listState.loadingList = false;
      }
    };

    const onAddressGps = (item: any) => {
      //
      router.push({
        path: '/amap-gps',
        query: {
          sLngLat: item.schoolLongitudeLatitude, // 教学点
          inLngLat: item.signInLongitudeLatitude, // 签到
          outLngLat: item.signOutLongitudeLatitude // 签退
        }
      });
    };

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

      getTeacherInfo();
      getList();
    });
    return () => (
      <div class={styles.teacherAttendanceDetail}>
        <MHeader />
        <SkeletionIndexModal
          v-model:show={forms.listState.loading}
          isLink={false}
          showCount={[1]}>
          <div class={styles.cellGroup}>
            <Cell center clickable={false} class={styles.cell}>
              {{
                icon: () => (
                  <Image
                    src={forms.teacherInfo.teacherAvatar || iconTeacher}
                    fit="cover"
                    class={styles.iconTeacher}
                  />
                ),

                title: () => (
                  <div class={styles.username}>
                    <p class={styles.name}>{forms.teacherInfo.teacherName}</p>
                    <p class={styles.class}>
                      {forms.teacherInfo.classGroupName}
                    </p>
                  </div>
                ),
                value: () => (
                  <div class={styles.attendance}>
                    <div class={[styles.attendanceItem, styles.weekAttendance]}>
                      <p
                        class={[
                          styles.value,
                          forms.teacherInfo.teacherAttendanceStatus === 'ERR'
                            ? styles.error
                            : '',
                          forms.teacherInfo.teacherAttendanceStatus === 'NORMAL'
                            ? styles.success
                            : ''
                        ]}>
                        {teacherAttendanceStatus[
                          forms.teacherInfo.teacherAttendanceStatus
                        ] || '--'}
                      </p>
                      <p class={styles.title}>本周考勤</p>
                    </div>
                    <div
                      class={[styles.attendanceItem, styles.classAttendance]}>
                      <p
                        class={[
                          styles.value,
                          forms.teacherInfo.errCourseNum > 0
                            ? styles.error
                            : styles.success
                        ]}>
                        {forms.teacherInfo.errCourseNum}
                        <span>课时</span>
                      </p>

                      <p class={styles.title}>学期异常</p>
                    </div>
                  </div>
                )
              }}
            </Cell>
          </div>
        </SkeletionIndexModal>

        <DropdownMenu>
          <DropdownItem
            v-model={forms.params.signStatus}
            options={forms.classColumns as any}
            onChange={() => {
              forms.listState.dataShow = true;
              forms.list = [];
              getList();
            }}></DropdownItem>
          <DropdownItem ref={dropDownItemRef1} title={formatName('orchestra')}>
            <DropDownModal
              selectValues={forms.params.courseType}
              columns={forms.typeColumns}
              open={dropDownItemRef1.value.state.showPopup}
              onDropDownClose={() => onDropDownClose(dropDownItemRef1)}
              onDropDownConfirm={(values: any) => {
                forms.params.courseType = values[0];
                onDropDownClose(dropDownItemRef1);
                forms.listState.dataShow = true;
                forms.list = [];
                getList();
              }}
            />
          </DropdownItem>
        </DropdownMenu>

        <SkeletionDetailModal v-model:show={forms.listState.loadingList}>
          {forms.listState.dataShow ? (
            forms.list.map((item: any) => (
              <CellGroup inset class={styles.detailCellGroup}>
                <Cell center border={false} class={styles.className}>
                  {{
                    title: () => (
                      <div class={styles.class}>
                        {coursesType[item.courseScheduleType]}
                      </div>
                    ),
                    value: () => (
                      <div class={styles.timer}>
                        {/* {dayjs(item.classDate).format('YYYY-MM-DD HH:mm:ss')} */}
                        {item.classDate}
                      </div>
                    )
                  }}
                </Cell>
                <Cell center>
                  <div class={styles.detailGroup}>
                    <div class={styles.detailItem}>
                      <div class={styles.detailStatus}>
                        <span
                          class={[
                            styles.statusName,
                            item.signInStatus ? '' : styles.error
                          ]}>
                          {item.signInStatus ? '正常' : '异常'}
                        </span>
                        <img
                          src={item.signInStatus ? iconSuccess : iconWarn}
                          class={styles.img}
                        />
                      </div>
                      <div class={styles.sign}>
                        <span class={styles.signTime}>
                          签到时间{' '}
                          {item.signInTime
                            ? dayjs(item.signInTime).format('HH:mm:ss')
                            : '--'}
                        </span>
                      </div>
                    </div>
                    {item.teachMode === 'OFFLINE' ? (
                      <div class={styles.detailItem}>
                        <div class={styles.detailStatus}>
                          <span
                            class={[
                              styles.statusName,
                              item.signInAddressStatus ? '' : styles.error
                            ]}>
                            {item.signInAddressStatus ? '正常' : '异常'}
                          </span>
                          <img
                            src={
                              item.signInAddressStatus ? iconSuccess : iconWarn
                            }
                            class={styles.img}
                          />
                        </div>
                        <div class={styles.sign}>
                          <span class={styles.signTime}>签到地点</span>
                          <span
                            class={styles.locate}
                            onClick={() => onAddressGps(item)}>
                            查看定位
                            <Icon name="arrow" class={styles.iconArrow} />
                          </span>
                        </div>
                      </div>
                    ) : (
                      ''
                    )}

                    <div class={styles.detailItem}>
                      <div class={styles.detailStatus}>
                        <span
                          class={[
                            styles.statusName,
                            item.signOutStatus ? '' : styles.error
                          ]}>
                          {item.signOutStatus ? '正常' : '异常'}
                        </span>
                        <img
                          src={item.signOutStatus ? iconSuccess : iconWarn}
                          class={styles.img}
                        />
                      </div>
                      <div class={styles.sign}>
                        <span class={styles.signTime}>
                          签退时间{' '}
                          {item.signOutTime
                            ? dayjs(item.signOutTime).format('HH:mm:ss')
                            : '--'}
                        </span>
                      </div>
                    </div>
                    {item.teachMode === 'OFFLINE' ? (
                      <div class={styles.detailItem}>
                        <div class={styles.detailStatus}>
                          <span
                            class={[
                              styles.statusName,
                              item.signOutAddressStatus ? '' : styles.error
                            ]}>
                            {item.signOutAddressStatus ? '正常' : '异常'}
                          </span>
                          <img
                            src={
                              item.signOutAddressStatus ? iconSuccess : iconWarn
                            }
                            class={styles.img}
                          />
                        </div>
                        <div class={styles.sign}>
                          <span class={styles.signTime}>签退地点</span>
                          <span
                            class={styles.locate}
                            onClick={() => onAddressGps(item)}>
                            查看定位
                            <Icon name="arrow" class={styles.iconArrow} />
                          </span>
                        </div>
                      </div>
                    ) : (
                      ''
                    )}
                  </div>
                </Cell>
              </CellGroup>
            ))
          ) : (
            <MEmpty
              style={{
                minHeight: `calc(60vh)`
              }}
              description="暂无数据"
            />
          )}
        </SkeletionDetailModal>
      </div>
    );
  }
});
