import MHeader from '@/components/m-header';
import MSearch from '@/components/m-search';
import MSticky from '@/components/m-sticky';
import { Cell, DropdownItem, DropdownMenu, Image, List } from 'vant';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import DropDownModal from '../site-management/drop-down-modal';
import iconTeacher from '@/common/images/icon-teacher-default.png';
import SkeletionIndexModal from './skeletion-index-modal';
import { useRouter } from 'vue-router';
import request from '@/helpers/request';
import MFullRefresh from '@/components/m-full-refresh';
import {
  orchestraClassType,
  teacherAttendanceStatus
} from '@/helpers/constant';
import MEmpty from '@/components/m-empty';

export default defineComponent({
  name: 'teacher-attendance',
  setup() {
    const dropDownItemRef = ref();
    const dropDownItemRef1 = ref();
    const router = useRouter();
    const forms = reactive({
      listState: {
        loading: true,
        dataShow: true,
        refreshing: false
      },
      statusColumns: [{ text: '全部状态', value: '' }],
      classColumns: [{ text: '全部班级', value: '' }],
      isClick: false,
      params: {
        teacherAttendanceStatus: '',
        classType: '',
        search: ''
        // page: 1,
        // rows: 20
      },
      list: []
    });

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

    const formatName = (type: string) => {
      if (type === 'orchestra') {
        let name = '';
        forms.classColumns.forEach((item: any) => {
          if (forms.params.classType === 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/schoolTeacherAttendance/queryTeacherAttendance',
          {
            data: {
              ...forms.params
            }
          }
        );
        const result = data || [];
        // 处理重复请求数据
        if (forms.list.length > 0 && result.pageNo === 1) {
          return;
        }
        forms.list = result || [];

        // 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;
      }
    };

    onMounted(() => {
      // 考勤
      for (const key in teacherAttendanceStatus) {
        if (
          Object.prototype.hasOwnProperty.call(teacherAttendanceStatus, key)
        ) {
          const text = teacherAttendanceStatus[key];
          forms.statusColumns.push({
            text,
            value: key
          });
        }
      }

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

      getList();
    });
    return () => (
      <div class={styles.teacherAttendance}>
        <MSticky position="top">
          <MHeader />
          <MSearch
            placeholder="请输入老师姓名"
            onSearch={(val: string) => {
              forms.params.search = val;
              forms.listState.dataShow = true;
              forms.list = [];
              getList();
            }}
          />
          <DropdownMenu>
            <DropdownItem
              ref={dropDownItemRef}
              v-model={forms.params.teacherAttendanceStatus}
              options={forms.statusColumns as any}
              onChange={() => {
                forms.listState.dataShow = true;
                forms.list = [];
                getList();
              }}></DropdownItem>
            <DropdownItem
              ref={dropDownItemRef1}
              title={formatName('orchestra')}>
              <DropDownModal
                selectValues={forms.params.classType}
                columns={forms.classColumns}
                open={dropDownItemRef1.value.state.showPopup}
                onDropDownClose={() => onDropDownClose(dropDownItemRef1)}
                onDropDownConfirm={(values: any) => {
                  forms.params.classType = values[0];
                  onDropDownClose(dropDownItemRef1);
                  forms.listState.dataShow = true;
                  forms.list = [];
                  getList();
                }}
              />
            </DropdownItem>
          </DropdownMenu>
        </MSticky>

        <SkeletionIndexModal v-model:show={forms.listState.loading}>
          <MFullRefresh
            v-model:modelValue={forms.listState.refreshing}
            onRefresh={() => getList()}
            style={{
              minHeight: `calc(100vh - var(--header-height))`
            }}>
            <div class={styles.cellGroup}>
              {forms.listState.dataShow ? (
                forms.list.map((item: any) => (
                  <Cell
                    center
                    isLink
                    clickable={false}
                    class={styles.cell}
                    onClick={() => {
                      router.push({
                        path: '/teacher-attendance-detail',
                        query: {
                          teacherId: item.teacherId,
                          classGroupId: item.classGroupId
                        }
                      });
                    }}>
                    {{
                      icon: () => (
                        <Image
                          src={item.teacherAvatar || iconTeacher}
                          fit="cover"
                          class={styles.iconTeacher}
                        />
                      ),

                      title: () => (
                        <div class={styles.username}>
                          <p class={styles.name}>{item.teacherName}</p>
                          <p class={styles.class}>
                            {/* {orchestraClassType[item.classGroupType]} */}
                            {item.classGroupName}
                          </p>
                        </div>
                      ),
                      value: () => (
                        <div class={styles.attendance}>
                          <div
                            class={[
                              styles.attendanceItem,
                              styles.weekAttendance
                            ]}>
                            <p
                              class={[
                                styles.value,
                                item.teacherAttendanceStatus === 'ERR'
                                  ? styles.error
                                  : '',
                                item.teacherAttendanceStatus === 'NORMAL'
                                  ? styles.success
                                  : ''
                              ]}>
                              {teacherAttendanceStatus[
                                item.teacherAttendanceStatus
                              ] || '--'}
                            </p>
                            <p class={styles.title}>本周考勤</p>
                          </div>
                          <div
                            class={[
                              styles.attendanceItem,
                              styles.classAttendance
                            ]}>
                            <p
                              class={[
                                styles.value,
                                item.errCourseNum > 0
                                  ? styles.error
                                  : styles.success
                              ]}>
                              {item.errCourseNum}
                              <span>课时</span>
                            </p>
                            <p class={styles.title}>学期异常</p>
                          </div>
                        </div>
                      )
                    }}
                  </Cell>
                ))
              ) : (
                <MEmpty
                  style={{
                    minHeight: `calc(100vh - var(--header-height))`
                  }}
                  description="暂无老师考勤"
                />
              )}
            </div>
          </MFullRefresh>
        </SkeletionIndexModal>
      </div>
    );
  }
});
