import {  defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import {
  NButton,
  NCascader,
  NDataTable,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NModal,
  NNumberAnimation,
  NSpace,
  NTag,
  NTooltip,
  useMessage
} from 'naive-ui';
// import { useECharts } from '@/hooks/web/useECharts';
import Pagination from '/src/components/pagination';
import { api_musicPracticeRecordPageStat, 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 { checkUrlType, 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';
import { useCatchStore } from '/src/store/modules/catchData';
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 TheTooltip from '/src/components/TheTooltip';
import CardPreview from '/src/components/card-preview';
import { saveAs } from 'file-saver';
import { useRoute } from 'vue-router';
import dayjs from 'dayjs';
export default defineComponent({
  name: 'student-practiceData',
  props: {
    studentId: {
      type: String,
      default: ''
    },
    classGroupId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const route = useRoute()
    const userStore = useUserStore();
    const catchData = useCatchStore()
    const message = useMessage()
    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
      },
      asc: null as any,
      sortType: null as any,
      searchForm: {
        musicSheetName: '',
        instrumentId: null,
        heardLevel: null, //
        userMusicFlag: null, // 是否生成作品
        minScore: null,
        maxScore: null,
        musicStartTime: []
      },
      stat: {} as any,
      tableList: [] as any,
      goCourseVisiable: false
    });
    const timer = ref<[number, number]>([
      getNowDateAndMonday(new Date().getTime()),
      getNowDateAndSunday(new Date().getTime())
    ]);
    const previewShow = ref(false);
    const previewItem = ref({
      type: '',
      content: '',
      title: ''
    });


    const toolTitleTips = (title: string, item: any) => {
      return <NTooltip showArrow={false} placement="top-start">
      {{
        trigger: () => (
          <div class={styles.cell}>
            <span>{title}</span>
            <img
              class={styles.sortIcon}
              src={
                item.sortOrder === 'descend'
                  ? iconSortDesc
                  : item.sortOrder === 'ascend'
                  ? iconSortAsc
                  : iconSortDefault
              }
            />
          </div>
        ),
        default:
          item.sortOrder === 'descend'
            ? '点击升序'
            : item.sortOrder === 'ascend'
            ? '取消排序'
            : '点击降序'
      }}
    </NTooltip>
    }

    const createTimeRef = reactive({
      title() {
        return (
          toolTitleTips('评测时间', createTimeRef)
        );
      },
      key: 'createTime',
      sorter: true,
      sortOrder: false as any
    });

    const evaluationProgressRef = reactive({
      title() {
        return (
          toolTitleTips('评测进度', evaluationProgressRef)
        );
      },
      key: 'evaluationProgress',
      sorter: true,
      sortOrder: false as any
    });

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

    const intonationRef = reactive({
      title() {
        return (
          toolTitleTips('音准', intonationRef)
        );
      },
      key: 'intonation',
      sorter: true,
      sortOrder: false as any,
      render(row: any) {
        return row.rhythmFlag ? '--' : row.intonation
      }
    });

    const cadenceRef = reactive({
      title() {
        return (
          toolTitleTips('节奏', cadenceRef)
        );
      },
      key: 'cadence',
      sorter: true,
      sortOrder: false as any
    });

    const integrityRef = reactive({
      title() {
        return (
          toolTitleTips('完整度', integrityRef)
        );
      },
      key: 'integrity',
      sorter: true,
      sortOrder: false as any,
      render(row: any) {
        return row.rhythmFlag ? '--' : row.integrity
      }
    });

    const userMusicTimeRef = reactive({
      title() {
        return (
          toolTitleTips('发布时间', userMusicTimeRef)
        );
      },
      key: 'userMusicTime',
      sorter: true,
      sortOrder: false as any,
      render(row: any) {
        return row.userMusicTime || '--'
      }
    });

    const columns = () => {
      return [
        createTimeRef,
        {
          // title: '评测曲目',
          title() {
            return (
              <div class={styles.minWidth}>评测曲目</div>
            );
          },
          key: 'musicSheetName',
          render(row: any) {
            return <TheTooltip
            maxWidth={120}
            showContentWidth={300}
            content={row.musicSheetName}
          />;
          }
        },
        // 入门：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: '乐器',
          title() {
            return (
              <div class={styles.minWidth}>乐器</div>
            );
          },
          key: 'instrumentName',
          render(row: any) {
            return row.instrumentName || '--'
          }
        },
        evaluationProgressRef,
        scoreRef,
        intonationRef,
        cadenceRef,
        integrityRef,
        {
          // title: '发布作品',
          title() {
            return (
              <div class={styles.minWidth}>发布作品</div>
            );
          },
          key: 'userMusicFlag',
          render(row: any) {
            return <span>{row.userMusicFlag ? '是' : '否'}</span>;
          }
        },
        userMusicTimeRef,
        {
          title: '操作',
          fixed: 'right',
          key: 'id',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  text
                  type="primary"
                  onClick={() => {
                    gotoRecode(row);
                  }}>
                  评测报告
                </NButton>
                {row.userMusicFlag ? <>
                  {row.videoFilePath || row.recordFilePath ? <><NButton
                    text
                    type="primary"
                    onClick={() => {
                      gotoPreview(row);
                    }}>
                    预览作品
                  </NButton>
                  <NButton
                    text
                    type="primary"
                    onClick={() => {
                      gotoDownload(row);
                    }}>
                    下载作品
                  </NButton></> : ''}</> 
                  : ''}
                
                
              </NSpace>
            );
          }
        }
      ];
    };

    // 统计排序
    const handleSorterChange = (sroter: any) => {
      if (!sroter.order) {
        state.asc = null
        state.sortType = null
        evaluationProgressRef.sortOrder = false
        scoreRef.sortOrder = false
        createTimeRef.sortOrder = false
        intonationRef.sortOrder = false
        cadenceRef.sortOrder = false
        integrityRef.sortOrder = false
        userMusicTimeRef.sortOrder = false
      } else {
        // 1：综合得分，2：音准，3：节奏：4：完整度，5：评测时间  6:生成时间，7:评测进度
        const template = {
          score: 1,
          intonation: 2,
          cadence: 3,
          integrity: 4,
          createTime: 5,
          userMusicTime: 6,
          evaluationProgress: 7
        } as any

        state.sortType = template[sroter.columnKey]

        evaluationProgressRef.sortOrder = false
        scoreRef.sortOrder = false
        createTimeRef.sortOrder = false
        intonationRef.sortOrder = false
        cadenceRef.sortOrder = false
        integrityRef.sortOrder = false
        userMusicTimeRef.sortOrder = false

        if (sroter.columnKey == 'score') {
          scoreRef.sortOrder = sroter.order
        }
        if (sroter.columnKey == 'createTime') {
          createTimeRef.sortOrder = sroter.order
        }
        if (sroter.columnKey == 'intonation') {
          intonationRef.sortOrder = sroter.order
        }
        if (sroter.columnKey == 'cadence') {
          cadenceRef.sortOrder = sroter.order
        }
        if(sroter.columnKey === 'integrity') {
          integrityRef.sortOrder = sroter.order
        }
        if (sroter.columnKey == 'userMusicTime') {
          userMusicTimeRef.sortOrder = sroter.order
        }
        if (sroter.columnKey == 'evaluationProgress') {
          evaluationProgressRef.sortOrder = sroter.order
        }

        state.asc = sroter.order == 'ascend' ? true : false
      }
      getList()
    }

    const getList = async () => {
      state.loading = true;
      try {
        const { musicStartTime, ...temp } = state.searchForm;
        const res = await getPracticeRecordList({
          userId: props.studentId,
          ...state.pagination,
          sortType: state.sortType,
          asc: state.asc,
          ...temp,
          ...getTimes(
            musicStartTime,
            ['userMusicStartTime', 'userMusicEndTime'],
            'YYYY-MM-DD'
          ),
          ...getTimes(
            timer.value,
            ['startTime', 'endTime'],
            'YYYY-MM-DD'
          ),
          classGroupId: props.classGroupId,
          ...getTimes(timer.value, ['startTime', 'endTime'], 'YYYY-MM-DD')
        });
        state.tableList = res.data.rows;
        state.pagination.pageTotal = res.data.total;
      } catch {

      }
      state.loading = false
    };

    const getTrainingStat = async () => {
      state.loading = true;
      try {
        const { musicStartTime, ...more } = state.searchForm
        const { data } = await api_musicPracticeRecordPageStat({
          userId: props.studentId,
          page: state.pagination.page,
          rows: state.pagination.rows,
          sortType: state.sortType,
          asc: state.asc,
          ...more,
          ...getTimes(timer.value, ['startTime', 'endTime'], 'YYYY-MM-DD')
        })

        state.stat = {
          evaluateFrequency: data.evaluateFrequency || 0,
          publishCount: data.publishCount || 0
        }
      } catch {}
      state.loading = false
    }


    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 gotoPreview = (row: any) => {
      let lookTitle = '';
      if (row.videoFilePath) {
        lookTitle = checkUrlType(row.videoFilePath);
      } else {
        lookTitle = checkUrlType(row.recordFilePath);
      }
      const lookUrl = row.videoFilePath || row.recordFilePath;
      previewItem.value.content = lookUrl;
      previewItem.value.title = row.musicSheetName;
      if (lookTitle === 'video') {
        previewItem.value.type = 'VIDEO';
      } else if (lookTitle === 'audio') {
        previewItem.value.type = 'SONG';
      }
      previewShow.value = true;
    }
    const gotoDownload = (row: any) => {
      // 下载资源
      const fileUrl = row.videoFilePath || row.recordFilePath;
      const filename =
        row.musicSheetName + '-' + route.query.studentName + '-' + ( row.userMusicTime ? dayjs(row.userMusicTime).format('YYYYMMDDHHmmss') : '');
      const sfixx = fileUrl.substring(fileUrl.lastIndexOf('.'));
      // 发起Fetch请求
      fetch(fileUrl)
        .then(response => response.blob())
        .then(blob => {
          saveAs(blob, (filename || new Date().getTime()) + sfixx);
        })
        .catch(() => {
          message.error('下载失败');
        });
    
    }
    const search = () => {
      state.pagination.page = 1;
      getTrainingStat()
      getList();
      setCache({
        current: { timer: timer.value },
        saveKey: 'classStudentRecordEvaluationRecords'
      });
    };
    const onReset = () => {
      if(route.query.times) {
        timer.value = JSON.parse(route.query.times as any)
      } else {
        timer.value = [
          getNowDateAndMonday(new Date().getTime()),
          getNowDateAndSunday(new Date().getTime())
        ];
      }
      
      state.searchForm = {
        musicSheetName: '',
        heardLevel: null, //
        userMusicFlag: null, // 是否生成作品
        minScore: null,
        maxScore: null,
        musicStartTime: [],
        instrumentId: null
      };
      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(async () => {
      state.loading = true
      if(route.query.times) {
        timer.value = JSON.parse(route.query.times as any)
      }
      await catchData.getSubjects();
      await getTrainingStat()
      await 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}
                precision={0}
                v-model:value={state.searchForm.minScore}></NInputNumber>
              <span class={styles.pair}>-</span>
              <NInputNumber
                placeholder="最大分值"
                min={state.searchForm.minScore || 0}
                max={100}
                precision={0}
                showButton={false}
                v-model:value={state.searchForm.maxScore}></NInputNumber>
            </div>
          </NFormItem>

          <NFormItem>
            <NCascader
              to="body"
              placeholder="选择乐器"
              options={[
                { value: '', label: '全部乐器' },
                ...catchData.getSubjectList
              ]}
              childrenField="instruments"
              checkStrategy="child"
              expandTrigger="hover"
              showPath={false}
              clearable
              v-model:value={state.searchForm.instrumentId}
              onUpdate:value={(val: any, option: any, pathValues: any) => {
                console.log(val, option, pathValues);
              }}
            />
          </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="发布结束时间"
              {...({
                clearable: true
              } as any)}
              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.TrainDataTop, styles.TrainDataTopEvaluation]}>
          <div class={styles.TrainDataTopLeft}>
            <div class={styles.TrainDataItem}>
              <p class={styles.TrainDataItemTitle}>
                <div>
                  <span>
                    <NNumberAnimation
                      from={0}
                      to={state.stat.evaluateFrequency || 0}></NNumberAnimation>
                  </span>
                </div>
              </p>
              <p class={styles.TrainDataItemsubTitle}>评测次数</p>
            </div>
            <div class={styles.TrainDataItem}>
              <p class={styles.TrainDataItemTitle}>
                <div>
                  <span>
                    <NNumberAnimation
                      from={0}
                      to={state.stat.publishCount || 0}></NNumberAnimation>
                  </span>
                </div>
              </p>
              <p class={styles.TrainDataItemsubTitle}>作品数量</p>
            </div>
          </div>
        </div>
        <div class={[styles.tableWrap, styles.noSort]}>
          <NDataTable
            v-slots={{
              empty: () => <TheEmpty></TheEmpty>
            }}
            class={styles.classTable}
            loading={state.loading}
            columns={columns()}
            onUpdate:sorter={handleSorterChange}
            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
            saveKey='studentDetail-evaluationRecords'
          />
        </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>

        <CardPreview
          v-model:show={previewShow.value}
          item={previewItem.value}
          isDownload={false}
        />
      </>
    );
  }
});
