import {  defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NModal,
  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 } 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';
import { modalClickMask } from '/src/state';
// import SearchInput from '/src/components/searchInput';
import CSelect from '/src/components/CSelect';
import { evaluateDifficultArray } from '/src/utils/searchArray';
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
      },
      searchForm: {
        musicSheetName: '',
        heardLevel: null, //
        userMusicFlag: null, // 是否生成作品
        minScore: null,
        maxScore: null,
        musicStartTime: []
      },
      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: 'integrity',
          render(row: any) {
            return <span>{row.userMusicFlag ? '是' : '否'}</span>;
          }
        },
        {
          title: '生成时间',
          key: 'userMusicTime',
          render(row: any) {
            return <span>{row.userMusicTime || '--'}</span>;
          }
        },
        {
          title: '操作',
          key: 'id',
          render(row: any) {
            return (
              <NButton
                text
                type="primary"
                onClick={() => {
                  gotoRecode(row);
                }}>
                评测报告
              </NButton>
            );
          }
        }
      ];
    };
    const getList = async () => {
      const { musicStartTime, ...temp } = state.searchForm;
      const res = await getPracticeRecordList({
        userId: props.studentId,
        ...state.pagination,
        ...temp,
        ...getTimes(
          musicStartTime,
          ['userMusicStartTime', 'userMusicEndTime'],
          'YYYY-MM-DD'
        ),
        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) => {
      const token = userStore.getToken;
      reportSrc.value =
        vaildMusicScoreUrl() +
        `/instrument/?v=${+new Date()}#/evaluat-report?v=${+new Date()}&id=${
          row.id
        }&platform=webTeacher&Authorization=${token}`;
      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())
      ];
      state.searchForm = {
        musicSheetName: '',
        heardLevel: null, //
        userMusicFlag: null, // 是否生成作品
        minScore: null,
        maxScore: null,
        musicStartTime: []
      };
      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();
    });
    return () => (
      <>
        <NForm label-placement="left" inline style="flex-wrap: wrap;">
          <NFormItem>
            <CDatePicker
              v-model:value={timer.value}
              separator={'至'}
              type="daterange"
              class={styles.datePicker}
              startPlaceholder="评测开始时间"
              endPlaceholder="评测结束时间"
              timerValue={timer.value}></CDatePicker>
          </NFormItem>
          <NFormItem>
            <NInput
              placeholder="请输入曲目名称"
              v-model:value={state.searchForm.musicSheetName}
            />
            {/* v-model:value={state.searchForm.keyword} */}
            {/* <SearchInput
              {...{ placeholder: '请输入曲目名称' }}
              class={styles.searchInput}
              style={{ width: '160px' }}
              // searchWord={state.searchForm.keyword}
              // onChangeValue={(val: string) =>
              //   (state.searchForm.keyword = val)
              // }
            ></SearchInput> */}
          </NFormItem>

          <NFormItem>
            <CSelect
              {...({
                options: evaluateDifficultArray,
                placeholder: '请输入评测难度',
                clearable: true,
                inline: true
              } as any)}
              v-model:value={state.searchForm.heardLevel}></CSelect>
          </NFormItem>
          <NFormItem>
            <div class={styles.inputRangeSection}>
              <NInputNumber
                placeholder="最小分值"
                min={0}
                max={state.searchForm.maxScore || 100}
                showButton={false}
                v-model:value={state.searchForm.minScore}></NInputNumber>
              <span class={styles.pair}>-</span>
              <NInputNumber
                placeholder="最大分值"
                min={state.searchForm.minScore || 0}
                max={100}
                showButton={false}
                v-model:value={state.searchForm.maxScore}></NInputNumber>
            </div>
          </NFormItem>

          <NFormItem>
            <CSelect
              {...({
                options: [
                  { label: '是', value: true },
                  { label: '否', value: false }
                ],
                placeholder: '请选择是否生成作品',
                clearable: true,
                inline: true
              } as any)}
              v-model:value={state.searchForm.userMusicFlag}></CSelect>
          </NFormItem>

          <NFormItem>
            <CDatePicker
              v-model:value={state.searchForm.musicStartTime}
              separator={'至'}
              class={styles.datePicker}
              type="daterange"
              startPlaceholder="生成开始时间"
              endPlaceholder="生成结束时间"
              timerValue={state.searchForm.musicStartTime}></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
          maskClosable={modalClickMask}
          v-model:show={payForm.detailVisiable}
          preset="card"
          class={['modalTitle background', styles.reportModel]}
          title={'评测报告'}>
          <div class={styles.reportContainer} style={{ lineHeight: 0 }}>
            <iframe
              width={'100%'}
              ref={iframeRef}
              frameborder="0"
              onLoad={(val: any) => {
                iframeDislableKeyboard(val.target);
              }}
              src={reportSrc.value}></iframe>
          </div>
        </NModal>
      </>
    );
  }
});
