import { Ref, defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NModal,
  NNumberAnimation,
  NSpace,
  NTag
} from 'naive-ui';
import { useECharts } from '@/hooks/web/useECharts';
import Pagination from '/src/components/pagination';
import { getPracticeRecordList } from '../api';
import {
  getNowDateAndMonday,
  getNowDateAndSunday,
  getTimes
} from '/src/utils/dateFormat';
import { vaildMusicScoreUrl, vaildUrl } from '@/utils/urlUtils';
import CDatePicker from '/src/components/CDatePicker';
import { useUserStore } from '/src/store/modules/users';
import TheEmpty from '/src/components/TheEmpty';
import { initCache, setCache } from '/src/hooks/use-async';
import { iframeDislableKeyboard } from '/src/utils';
export default defineComponent({
  name: 'student-practiceData',
  props: {
    studentId: {
      type: String,
      default: ''
    },
    classGroupId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const userStore = useUserStore();
    const chartRef = ref<HTMLDivElement | null>(null);
    const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
    const practiceFlag = ref(true);
    const payForm = reactive({
      height: '360px',
      width: '100%',
      practiceDurationAvg: 0,
      practiceDays: 0,
      practiceDurationTotal: 0,
      dateList: [],
      timeList: [],
      detailVisiable: false
    });
    const reportSrc = ref('');
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 4
      },
      tableList: [] as any,
      goCourseVisiable: false
    });
    const timer = ref<[number, number]>([
      getNowDateAndMonday(new Date().getTime()),
      getNowDateAndSunday(new Date().getTime())
    ]);
    const columns = () => {
      return [
        {
          title: '时间',
          key: 'createTime'
        },
        {
          title: '评测曲目',
          key: 'musicSheetName',
          render(row: any) {
            return <span>{row.musicSheetName}</span>;
          }
        },
        // 入门：BEGINNER/进阶：ADVANCED/大师：PERFORMER"
        {
          title: '评测难度',
          key: 'heardLevel',
          render(row: any) {
            return (
              <>
                {row.heardLevel == null ? <span>--</span> : null}
                {row.heardLevel == 'BEGINNER' ? (
                  <NTag type="info">入门级</NTag>
                ) : null}
                {row.heardLevel == 'ADVANCED' ? (
                  <NTag type="warning">进阶级</NTag>
                ) : null}
                {row.heardLevel == 'PERFORMER' ? (
                  <NTag type="error">大师级</NTag>
                ) : null}
              </>
            );
          }
        },
        {
          title: '评测分数',
          key: 'score',
          render(row: any) {
            return <span>{row.score}</span>;
          }
        },
        {
          title: '音准',
          key: 'intonation',
          render(row: any) {
            return <span>{row.intonation}</span>;
          }
        },
        {
          title: '节奏',
          key: 'cadence',
          render(row: any) {
            return <span>{row.cadence}</span>;
          }
        },
        {
          title: '完整度',
          key: 'integrity',
          render(row: any) {
            return <span>{row.integrity}</span>;
          }
        },
        {
          title: '操作',
          key: 'id',
          render(row: any) {
            return (
              <NButton
                text
                type="primary"
                onClick={() => {
                  gotoRecode(row);
                }}>
                评测报告
              </NButton>
            );
          }
        }
      ];
    };
    const getList = async () => {
      const res = await getPracticeRecordList({
        userId: props.studentId,
        ...state.pagination,
        classGroupId: props.classGroupId,
        feature: 'EVALUATION',
        ...getTimes(timer.value, ['startTime', 'endTime'], 'YYYY-MM-DD')
      });
      state.tableList = res.data.rows;
      state.pagination.pageTotal = res.data.total;
    };
    const gotoRecode = (row: any) => {
      console.log(row.id, 'gotoRecode');
      const tockn = userStore.getToken;
      reportSrc.value =
        vaildMusicScoreUrl() +
        `/instrument/?v=${+new Date()}#/evaluat-report?v=${+new Date()}&id=${
          row.id
        }&platform=webTeacher&Authorization=${tockn}`;
      payForm.detailVisiable = true;
    };
    const search = () => {
      state.pagination.page = 1;
      getList();
      setCache({
        current: { timer: timer.value },
        saveKey: 'classStudentRecordEvaluationRecords'
      });
    };
    const onReset = () => {
      timer.value = [
        getNowDateAndMonday(new Date().getTime()),
        getNowDateAndSunday(new Date().getTime())
      ];
      search();
      setCache({
        current: { timer: timer.value },
        saveKey: 'classStudentRecordEvaluationRecords'
      });
    };
    initCache({
      current: { timer: timer.value },
      saveKey: 'classStudentRecordEvaluationRecords',
      callBack: (active: any) => {
        timer.value = active.timer;
      }
    });
    const iframeRef = ref();
    onMounted(() => {
      getList();
      console.log(props.studentId);
    });
    return () => (
      <>
        <NForm label-placement="left" inline>
          <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 class={styles.tableWrap}>
          <NDataTable
            v-slots={{
              empty: () => <TheEmpty></TheEmpty>
            }}
            class={styles.classTable}
            loading={state.loading}
            columns={columns()}
            data={state.tableList}></NDataTable>
          <Pagination
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          />
        </div>
        <NModal
          v-model:show={payForm.detailVisiable}
          preset="card"
          class={['modalTitle background', styles.reportModel]}
          title={'评测报告'}>
          <div class={styles.reportContainer} style={{ lineHeight: 0 }}>
            <iframe
              width={'100%'}
              height={'450px'}
              ref={iframeRef}
              frameborder="0"
              onLoad={(val: any) => {
                iframeDislableKeyboard(val.target);
              }}
              src={reportSrc.value}></iframe>
          </div>
        </NModal>
      </>
    );
  }
});
