import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NGi,
  NGrid,
  NNumberAnimation,
  NSpace,
  NTooltip,
  useMessage
} from 'naive-ui';
import SearchInput from '@/components/searchInput';
import CSelect from '@/components/CSelect';
import Pagination from '@/components/pagination';
// import add from './images/add.png';
import {
  getNowDateAndMonday,
  getNowDateAndSunday,
  getTimes,
  getSecend,
  formateSeconds,
  getHours,
  getLastMinutes
} from '/src/utils/dateFormat';
import CDatePicker from '/src/components/CDatePicker';
import { useRoute, useRouter } from 'vue-router';
import TheEmpty from '/src/components/TheEmpty';
import { initCache, setCache } from '/src/hooks/use-async';
import iconSortDefault from '@/common/images/icon-sort-default.png';
import iconSortDesc from '@/common/images/icon-sort-desc.png';
import iconSortAsc from '@/common/images/icon-sort-asc.png';
// import { convertToChineseNumeral } from '/src/utils';
import iconQuestion from '/src/common/images/icon-question.png';
import { getPracticePageStat } from '../../data-module/api';
import { api_practiceStatPage } from '../api';

export default defineComponent({
  name: 'student-studentList',
  setup() {
    const message = useMessage();
    const state = reactive({
      searchForm: {
        orderBy: null as any,
        sort: null as any,
        keyword: '',
        vipFlag: '' as any
      },
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 4
      },
      tableList: [] as any
    });

    const payForm = reactive({
      practiceDuration: 0,
      evaluateUserCount: 0,
      evaluateFrequency: 0,
      publishUserCount: 0,
      publishCount: 0,
      practiceUserCount: 0,
      paymentAmount: 0,
      practiceDurationAvg: 0,
      practiceDays: 0,
      practiceDurationTotal: 0
    });
    const route = useRoute();
    const router = useRouter();
    const search = () => {
      state.pagination.page = 1;
      getInfo();
      getList();
      setCache({
        current: { ...state.searchForm, timer: timer.value },
        saveKey: 'classDetailTestRecord'
      });
    };
    const timer = ref<[number, number]>([
      getNowDateAndMonday(new Date().getTime()),
      getNowDateAndSunday(new Date().getTime())
    ]);
    const searchTimer = ref<[number, number]>([
      getNowDateAndMonday(new Date().getTime()),
      getNowDateAndSunday(new Date().getTime())
    ]);
    const onReset = () => {
      timer.value = [
        getNowDateAndMonday(new Date().getTime()),
        getNowDateAndSunday(new Date().getTime())
      ];
      state.searchForm = {
        orderBy: null as any,
        sort: null as any,
        keyword: '',
        vipFlag: '' as any
      };
      search();
      setCache({
        current: { ...state.searchForm, timer: timer.value },
        saveKey: 'classDetailTestRecord'
      });
    };

    initCache({
      current: { ...state.searchForm, timer: timer.value },
      saveKey: 'classDetailTestRecord',
      callBack: (active: any) => {
        state.searchForm = active;
        timer.value = active.timer;
      }
    });
    const getList = async () => {
      state.loading = true;
      try {
        const searchForm = state.searchForm;
        const res = await api_practiceStatPage({
          classGroupId: route.query.id,
          studentName: searchForm.keyword,
          vipFlag: searchForm.vipFlag,
          orderBy: searchForm.orderBy,
          sort: searchForm.sort,
          ...state.pagination,
          ...getTimes(timer.value, ['startTime', 'endTime'], 'YYYY-MM-DD')
        });
        searchTimer.value = timer.value

        state.tableList = res.data.rows;

        state.pagination.pageTotal = res.data.total;
        state.loading = false;
      } catch (e) {
        state.loading = false;
        console.log(e);
      }
    };

    const getInfo = async () => {
      try {
        const searchForm = state.searchForm;
        const { data } = await getPracticePageStat({
          page: 1,
          rows: 999,
          studentName: searchForm.keyword,
          vipFlag: searchForm.vipFlag,
          orderBy: searchForm.orderBy,
          sort: searchForm.sort,
          classGroupId: route.query.id,
          ...getTimes(timer.value, ['startTime', 'endTime'], 'YYYY-MM-DD')
        });
        payForm.practiceDuration = data.practiceDuration;
        payForm.practiceDurationAvg = data.practiceDurationAvg;
        payForm.practiceUserCount = data.practiceUserCount;
        payForm.evaluateUserCount = data.evaluateUserCount;
        payForm.evaluateFrequency = data.evaluateFrequency;
        payForm.publishUserCount = data.publishUserCount;
        payForm.publishCount = data.publishCount;
      } catch (e) {
        console.log(e);
      }
    };
    onMounted(() => {
      getInfo();
      getList();
    });
    const gotoStudentDetail = (row: any) => {
      router.push({
        path: '/classStudentRecode',
        query: {
          ...route.query,
          studentId: row.studentId,
          studentName: row.studentName,
          times: JSON.stringify(searchTimer.value)
        }
      });
    };
    const toolTitleTips = (title: string, item: any) => {
      return (
        <NTooltip showArrow={false} placement="top-start">
          {{
            trigger: () => (
              <div class={styles.cell}>
                {title}
                <img
                  class={styles.sortIcon}
                  src={
                    item.sortOrder === 'descend'
                      ? iconSortDesc
                      : item.sortOrder === 'ascend'
                      ? iconSortAsc
                      : iconSortDefault
                  }
                />
              </div>
            ),
            default:
              item.sortOrder === 'descend'
                ? '点击升序'
                : item.sortOrder === 'ascend'
                ? '取消排序'
                : '点击降序'
          }}
        </NTooltip>
      );
    };

    const practiceDurationRef = reactive({
      title() {
        return toolTitleTips('练习总时长', practiceDurationRef);
      },
      key: 'practiceDuration',
      sorter: true,
      sortOrder: false as any,
      render(row: any) {
        return formateSeconds((row.practiceDuration as any) || 0);
      }
    });

    const practiceDaysRef = reactive({
      title() {
        return toolTitleTips('练习天数', practiceDaysRef);
      },
      key: 'practiceDays',
      sorter: true,
      sortOrder: false as any
    });

    const practiceDurationAvgRef = reactive({
      title() {
        return toolTitleTips('平均练习时长', practiceDurationAvgRef);
      },
      key: 'practiceDurationAvg',
      sorter: true,
      sortOrder: false as any,
      render(row: any) {
        return formateSeconds((row.practiceDurationAvg as any) || 0);
      }
    });

    const evaluateFrequencyRef = reactive({
      title() {
        return toolTitleTips('评测次数', evaluateFrequencyRef);
      },
      key: 'evaluateFrequency',
      sorter: true,
      sortOrder: false as any
    });

    const publishCountRef = reactive({
      title() {
        return toolTitleTips('作品数量', publishCountRef);
      },
      key: 'publishCount',
      sorter: true,
      sortOrder: false as any,
      render(row: any) {
        return row.publishCount || 0;
      }
    });

    const publishScoreRef = reactive({
      title() {
        return toolTitleTips('最新作品分数', publishScoreRef);
      },
      key: 'publishScore',
      sorter: true,
      sortOrder: false as any,
      render(row: any) {
        return row.publishScore === null ? '--' : row.publishScore;
      }
    });

    const publishTimeRef = reactive({
      title() {
        return toolTitleTips('最新作品时间', publishTimeRef);
      },
      key: 'publishTime',
      sorter: true,
      sortOrder: false as any,
      render(row: any) {
        return row.publishTime || '--';
      }
    });

    const copyTo = (text: string) => {
      const input = document.createElement('input');
      input.value = text;
      document.body.appendChild(input);
      input.select();
      input.setSelectionRange(0, input.value.length);
      document.execCommand('Copy');
      document.body.removeChild(input);
      message.success('复制成功');
    };
    const columns = () => {
      return [
        {
          title: '学生姓名',
          key: 'studentName',
          render: (row: any) => {
            return (
              <NTooltip showArrow={false} placement="top-start">
                {{
                  trigger: () => (
                    <div
                      style={{ userSelect: 'all', cursor: 'pointer' }}
                      onClick={() => copyTo(row.studentName)}>
                      {row.studentName}
                    </div>
                  ),
                  default: '点击复制'
                }}
              </NTooltip>
            );
          }
        },
        {
          title: '性别',
          key: 'sex',
          render(row: any) {
            return row.gender + '' != 'null'
              ? row.gender == '0'
                ? '女'
                : '男'
              : '--';
          }
        },
        {
          title: '学生类型',
          key: 'vipFlag',
          render(row: any) {
            return row.vipFlag ? '会员' : '普通';
          }
        },
        {
          title: '乐器',
          key: 'instrumentName',
          render(row: any) {
            return row.instrumentName || '--';
          }
        },
        practiceDurationRef,
        practiceDaysRef,
        practiceDurationAvgRef,
        evaluateFrequencyRef,
        {
          title: () => (
            <span style={{ display: 'flex', alignItems: 'center' }}>
              发布作品{' '}
              <NTooltip showArrow={false}>
                {{
                  trigger: () => (
                    <img src={iconQuestion} class={styles.tipImg} />
                  ),
                  default: () => '筛选时间段内评测是否发布作品'
                }}
              </NTooltip>
            </span>
          ),
          key: 'publishFlag',
          render: (row: any) => (row.publishFlag ? '是' : '否')
        },
        publishCountRef,
        publishScoreRef,
        publishTimeRef,
        {
          title: '操作',
          key: 'titleImg',
          render: (row: any) => (
            <NButton
              type="primary"
              text
              onClick={() => {
                gotoStudentDetail(row);
                // setTabsCaches('evaluatingRcode', 'tabName', {
                //   path: '/studentDetail'
                // });
                // router.push({
                //   path: '/studentDetail',
                //   query: {
                //     studentId: row.studentId,
                //     studentName: row.studentName,
                //     times: JSON.stringify(currentTimer.value)
                //   }
                // });
              }}>
              详情
            </NButton>
          )
        }
      ];
    };

    // 统计排序
    const handleSorterChange = (sorter: any) => {
      if (!sorter.order) {
        state.searchForm.orderBy = '' as string;
        state.searchForm.sort = '' as string;
        practiceDurationRef.sortOrder = false;
        practiceDaysRef.sortOrder = false;
        practiceDurationAvgRef.sortOrder = false;
        evaluateFrequencyRef.sortOrder = false;
        publishCountRef.sortOrder = false;
        publishScoreRef.sortOrder = false;
        publishTimeRef.sortOrder = false;
      } else {
        state.searchForm.orderBy = sorter.columnKey;
        practiceDurationRef.sortOrder = false;
        practiceDaysRef.sortOrder = false;
        practiceDurationAvgRef.sortOrder = false;
        evaluateFrequencyRef.sortOrder = false;
        publishCountRef.sortOrder = false;
        publishScoreRef.sortOrder = false;
        publishTimeRef.sortOrder = false;
        if (sorter.columnKey == 'practiceDuration') {
          practiceDurationRef.sortOrder = sorter.order;
        }
        if (sorter.columnKey == 'practiceDays') {
          practiceDaysRef.sortOrder = sorter.order;
        }

        if (sorter.columnKey == 'practiceDurationAvg') {
          practiceDurationAvgRef.sortOrder = sorter.order;
        }

        if (sorter.columnKey == 'evaluateFrequency') {
          evaluateFrequencyRef.sortOrder = sorter.order;
        }

        if (sorter.columnKey == 'publishCount') {
          publishCountRef.sortOrder = sorter.order;
        }

        if (sorter.columnKey == 'publishScore') {
          publishScoreRef.sortOrder = sorter.order;
        }

        if (sorter.columnKey == 'publishTime') {
          publishTimeRef.sortOrder = sorter.order;
        }

        state.searchForm.sort = sorter.order == 'ascend' ? 'asc' : 'desc';
      }
      getList();
    };
    return () => (
      <div>
        <div class={styles.searchList}>
          <NForm label-placement="left" inline>
            <NFormItem>
              <SearchInput
                {...{ placeholder: '请输入学生姓名' }}
                class={styles.searchInput}
                searchWord={state.searchForm.keyword}
                onChangeValue={(val: string) =>
                  (state.searchForm.keyword = val)
                }></SearchInput>
            </NFormItem>

            <NFormItem>
              <CSelect
                {...({
                  options: [
                    {
                      label: '全部类型',
                      value: ''
                    },
                    {
                      label: '会员',
                      value: true
                    },
                    {
                      label: '普通',
                      value: false
                    }
                  ],
                  placeholder: '学生类型',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.vipFlag}></CSelect>
            </NFormItem>
            <NFormItem>
              <CDatePicker
                v-model:value={timer.value}
                separator={'至'}
                type="daterange"
                timerValue={timer.value}></CDatePicker>
            </NFormItem>
            <NFormItem>
              <NSpace justify="end">
                <NButton type="primary" class="searchBtn" onClick={search}>
                  搜索
                </NButton>
                <NButton
                  type="primary"
                  ghost
                  class="resetBtn"
                  onClick={onReset}>
                  重置
                </NButton>
              </NSpace>
            </NFormItem>
          </NForm>
        </div>
        <div class={['section-container']}>
          <div class={styles.TrainDataTop}>
            <div class={styles.TrainDataTopLeft}>
              <div class={styles.TrainDataItem}>
                <p class={styles.TrainDataItemTitle}>
                  <div>
                    <span>
                      <NNumberAnimation
                        from={0}
                        to={payForm.practiceUserCount}></NNumberAnimation>
                    </span>
                    人
                  </div>
                </p>
                <p class={styles.TrainDataItemsubTitle}>练习人数</p>
              </div>
              <div class={styles.TrainDataItem}>
                <p class={styles.TrainDataItemTitle}>
                  {getHours(payForm.practiceDurationAvg) > 0 ? (
                    <div>
                      <span>
                        <NNumberAnimation
                          from={0}
                          to={getHours(
                            payForm.practiceDurationAvg
                          )}></NNumberAnimation>
                      </span>
                      时
                    </div>
                  ) : null}

                  {getHours(payForm.practiceDurationAvg) > 0 ||
                  getLastMinutes(payForm.practiceDurationAvg) > 0 ? (
                    <div>
                      <span>
                        <NNumberAnimation
                          from={0}
                          to={getLastMinutes(
                            payForm.practiceDurationAvg
                          )}></NNumberAnimation>
                      </span>
                      分
                    </div>
                  ) : null}
                  <div>
                    <span>
                      <NNumberAnimation
                        from={0}
                        to={getSecend(
                          payForm.practiceDurationAvg
                        )}></NNumberAnimation>
                    </span>
                    秒
                  </div>
                </p>
                <p class={styles.TrainDataItemsubTitle}>平均每天练习时长</p>
              </div>

              <div class={styles.TrainDataItem}>
                <p class={styles.TrainDataItemTitle}>
                  {getHours(payForm.practiceDuration) > 0 ? (
                    <div>
                      <span>
                        <NNumberAnimation
                          from={0}
                          to={getHours(
                            payForm.practiceDuration
                          )}></NNumberAnimation>
                      </span>
                      时
                    </div>
                  ) : null}
                  {getHours(payForm.practiceDuration) > 0 ||
                  getLastMinutes(payForm.practiceDuration) > 0 ? (
                    <div>
                      <span>
                        <NNumberAnimation
                          from={0}
                          to={getLastMinutes(
                            payForm.practiceDuration
                          )}></NNumberAnimation>
                      </span>
                      分
                    </div>
                  ) : null}
                  <div>
                    <span>
                      <NNumberAnimation
                        from={0}
                        to={getSecend(
                          payForm.practiceDuration
                        )}></NNumberAnimation>
                    </span>
                    秒
                  </div>
                </p>
                <p class={styles.TrainDataItemsubTitle}>练习总时长</p>
              </div>

              <div class={styles.TrainDataItem}>
                <p class={styles.TrainDataItemTitle}>
                  <div>
                    <span>
                      <NNumberAnimation
                        from={0}
                        to={payForm.evaluateUserCount}></NNumberAnimation>
                      /
                      <NNumberAnimation
                        from={0}
                        to={payForm.evaluateFrequency}></NNumberAnimation>
                    </span>
                  </div>
                </p>
                <p class={styles.TrainDataItemsubTitle}>评测人数/次数</p>
              </div>

              <div class={styles.TrainDataItem}>
                <p class={styles.TrainDataItemTitle}>
                  <div>
                    <span>
                      <NNumberAnimation
                        from={0}
                        to={payForm.publishUserCount}></NNumberAnimation>
                      /
                      <NNumberAnimation
                        from={0}
                        to={payForm.publishCount}></NNumberAnimation>
                    </span>
                  </div>
                </p>
                <p class={styles.TrainDataItemsubTitle}>作品人数/数量</p>
              </div>
            </div>
            <div class={styles.TrainDataTopRight}></div>
          </div>
        </div>
        <div class={[styles.tableWrap, styles.noSort]}>
          <NDataTable
            v-slots={{
              empty: () => <TheEmpty></TheEmpty>
            }}
            class={styles.classTable}
            loading={state.loading}
            columns={columns()}
            data={state.tableList}
            onUpdate:sorter={handleSorterChange}></NDataTable>
          <Pagination
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          />
        </div>
      </div>
    );
  }
});
