import { Ref, computed, defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import { NButton, NDataTable, NNumberAnimation } from 'naive-ui';
import numeral from 'numeral';
import { useECharts } from '@/hooks/web/useECharts';
import Pagination from '/src/components/pagination';
import { getTestStat } from '@/views/data-module/api';
import { getMinutes, getSecend, getTimes } from '/src/utils/dateFormat';
import { useRoute, useRouter } from 'vue-router';
import { getTrainingStatList } from '../../classList/api';
import dayjs from 'dayjs';
import TheEmpty from '/src/components/TheEmpty';
export default defineComponent({
  name: 'home-practiceData',
  props: {
    timer: {
      type: Array,
      defaut: () => []
    }
  },
  setup(props, { expose }) {
    const chartRef = ref<HTMLDivElement | null>(null);
    const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
    const practiceFlag = ref(true);
    const payForm = reactive({
      height: '360px',
      width: '100%',
      practiceUserCount: 0,
      paymentAmount: 0,
      practiceDurationAvg: 0,
      practiceDays: 0,
      practiceDurationTotal: 0,
      dateList: [],
      timeList: []
    });

    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 4
      },
      tableList: [] as any,
      goCourseVisiable: false
    });
    const currentTimer = computed(() => {
      return props.timer;
    });
    const columns = () => {
      return [
        {
          title: '日期',
          key: 'date'
        },
        {
          title: '练习人数',
          key: 'practiceUserCount',
          render(row: any) {
            return <>{row.practiceUserCount}人</>;
          }
        },
        {
          title: '平均练习时长(分钟)',
          key: 'practiceDuration',
          render(row: any) {
            return (
              <>
                {' '}
                <>
                  {row.practiceDuration
                    ? getMinutes(row.practiceDuration) > 0
                      ? getMinutes(row.practiceDuration) +
                        '分' +
                        getSecend(row.practiceDuration) +
                        '秒'
                      : getSecend(row.practiceDuration) + '秒'
                    : 0 + '分钟'}
                </>
              </>
            );
          }
        }
      ];
    };
    const getList = async () => {
      try {
        const res = await getTrainingStatList({
          page: 1,
          rows: 999,
          ...getTimes(
            currentTimer.value,
            ['startTime', 'endTime'],
            'YYYY-MM-DD'
          )
        });

        const res2 = await getTestStat({
          page: 1,
          rows: 999,
          ...getTimes(
            currentTimer.value,
            ['startTime', 'endTime'],
            'YYYY-MM-DD'
          )
        });
        state.tableList = res.data.rows;

        payForm.practiceDurationAvg = res2.data.practiceDurationAvg;
        payForm.practiceUserCount = res2.data.practiceUserCount;
        payForm.dateList = res2.data.trainingStatDetailList.map((item: any) => {
          return item.date;
        });

        payForm.timeList = res2.data.trainingStatDetailList.map((item: any) => {
          return item.practiceUserCount;
        });

        console.log('trainingStatDetailList', payForm.timeList);

        setChart();
      } catch (e) {
        console.log(e);
      }
    };
    expose({ getList });
    const setChart = () => {
      setOptions({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          show: false,
          selected: {
            //在这里设置默认展示就ok了
            练习人数: practiceFlag.value
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          axisLabel: {
            show: true,
            interval: 0
          },
          data: payForm.dateList
        },
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              formatter: '{value}人'
            },
            axisTick: {
              show: false
            },
            splitArea: {
              show: false,
              areaStyle: {
                color: ['rgba(255,255,255,0.2)']
              }
            },
            minInterval: 1,
            splitNumber: 5
          }
        ],
        grid: {
          left: '1%',
          right: '1%',
          top: '2%',
          bottom: 0,
          containLabel: true
        },
        series: [
          {
            // smooth: true,
            data: payForm.timeList,
            type: 'bar',
            barWidth: '48px',
            // label: {
            //   // 柱图头部显示值
            //   show: true,
            //   position: 'top',
            //   color: '#333',
            //   fontSize: '12px',
            //   fontWeight: 600
            // },

            itemStyle: {
              normal: {
                //这里设置柱形图圆角 [左上角，右上角，右下角，左下角]
                barBorderRadius: [8, 8, 0, 0],
                color: '#D5E9FF'
              },
              emphasis: {
                color: '#3583FA' //hover时改变柱子颜色
                // borderWidth: 4,
                // borderColor: 'rgba(213, 233, 255,.4)',
                // borderType: 'solid'
              }
            } as any
          }
        ],

        formatter: (item: any) => {
          if (Array.isArray(item)) {
            return [
              item[0].axisValueLabel,
              ...item.map((d: any) => {
                return `<br/>${d.marker}<span style="margin-top:10px;margin-left:5px;font-size: 13px;font-weight: 500;
                  color: #131415;font-weight: 600;
                  margin-top:12px
                  line-height: 18px;">练习人数: ${d.value}人 </span>`;
              })
            ].join('');
          } else {
            return item;
          }
        }
        // dataZoom: [
        //   {
        //     type: 'slider',
        //     start: 5,
        //     end: 100,
        //     filterMode: 'empty'
        //   }
        // ]
      });
    };

    onMounted(() => {
      getList();
    });

    return () => (
      <>
        <div class={styles.homeTrainData}>
          <div class={styles.TrainDataTop}>
            <div class={styles.TrainDataTopLeft}>
              <div class={styles.TrainDataItem}>
                <p class={styles.TrainDataItemTitle}>
                  <span>
                    <NNumberAnimation
                      from={0}
                      to={payForm.practiceUserCount}></NNumberAnimation>
                  </span>
                  人
                </p>
                <p class={styles.TrainDataItemsubTitle}>练习人数</p>
              </div>
              <div class={styles.TrainDataItem}>
                <p class={styles.TrainDataItemTitle}>
                  {getMinutes(payForm.practiceDurationAvg) > 0 ? (
                    <div>
                      <span>
                        <NNumberAnimation
                          from={0}
                          to={getMinutes(
                            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>
            <div class={styles.TrainDataTopRight}>
              <div
                // onClick={() => {
                //   practiceFlag.value = !practiceFlag.value;
                //   setChart();
                // }}
                class={[
                  styles.DataTopRightItem,
                  practiceFlag.value ? '' : styles.DataTopRightItemDis
                ]}>
                <div
                  class={[
                    styles.DataTopRightDot,
                    styles.DataTopRightDotBlue
                  ]}></div>
                <p>练习人数</p>
              </div>
            </div>
          </div>
          <div class={styles.chatrs}>
            <div
              ref={chartRef}
              style={{ height: payForm.height, width: payForm.width }}></div>
          </div>
          <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
              saveKey="orchestraRegistration-key"
            /> */}
          </div>
        </div>
      </>
    );
  }
});
