import { Ref, computed, defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index2.module.less';
import { NButton, NDataTable, NNumberAnimation, NSpace } from 'naive-ui';
import { useECharts } from '@/hooks/web/useECharts';
import Pagination from '/src/components/pagination';
import { getTimes } from '/src/utils/dateFormat';
import { getTrainingStat } from '../../data-module/api';
import { useRoute, useRouter } from 'vue-router';
import { getTrainingList } from '../../classList/api';
import TheEmpty from '/src/components/TheEmpty';

export default defineComponent({
  name: 'home-trainData',
  props: {
    timer: {
      type: Array,
      defaut: () => []
    }
  },
  setup(props, { expose }) {
    const chartRef = ref<HTMLDivElement | null>(null);
    const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
    const qualifiedFlag = ref(true);
    const unqualifiedFlag = ref(true);
    const router = useRouter();
    const route = useRoute();
    const payForm = reactive({
      height: '360px',
      width: '100%',
      studentNum: 0,
      paymentAmount: 0,
      dateList: [],
      studentList: [],
      payInfoList: []
    });
    const totalDateRef = ref({
      qualifiedRate: 0,
      qualifiedStudentCount: 0,
      submitStudentCount: 0,
      totalStudentCount: 0,
      trainingCount: 0,
      trainingRate: 0 //
    } as any);
    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: 'teacherName'
        },
        {
          title: '布置时间',
          key: 'createTime',
          render(row: any) {
            return <>{row.createTime}</>;
          }
        },
        {
          title: '截止时间',
          key: 'expireDate',
          render(row: any) {
            return <>{row.expireDate}</>;
          }
        },
        {
          title: '训练状态',
          key: 'status',
          render(row: any) {
            return row.status == 0 ? (
              <div class={styles.indDot}>
                {' '}
                <span></span> 进行中
              </div>
            ) : (
              <div class={styles.endDot}>
                <span></span>已结束
              </div>
            );
          }
        },
        {
          title: '布置人数',
          key: 'expectNum'
        },
        {
          title: '提交人数',
          key: 'trainingNum'
        },
        {
          title: '达标人数',
          key: 'standardNum'
        },
        {
          title: '提交率',
          key: 'trainingRate',
          render(row: any) {
            return <>{row.trainingRate}%</>;
          }
        },
        {
          title: '达标率',
          key: 'qualifiedRate',
          render(row: any) {
            return <>{row.qualifiedRate}%</>;
          }
        },
        // {
        //   title: '',
        //   key: 'sex',
        //   render(row: any) {
        //     return <>{row.sex == '0' ? '女' : '男'}</>;
        //   }
        // },
        {
          title: '操作',
          key: 'id',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  text
                  type="primary"
                  onClick={() => gotoWorkDetail(row)}>
                  详情
                </NButton>
              </NSpace>
            );
          }
        }
      ];
    };
    const gotoWorkDetail = (row: any) => {
      console.log(row);
      // router.push({
      //   path: '/afterWorkDetail',
      //   query: {
      //     ...route.query,
      //     teacherName: row.teacherName,
      //     trainingId: row.id,
      //     id: row.classGroupId,
      //     name: row.classGroupName
      //   }
      // });

      router.push({
        path: '/homework-record-detail',
        query: {
          id: row.id,
          name: row.name,
          times: JSON.stringify(currentTimer.value)
        }
      });
    };
    const getList = async () => {
      state.loading = true;
      try {
        const res = await getTrainingStat({
          ...getTimes(
            currentTimer.value,
            ['startTime', 'endTime'],
            'YYYY-MM-DD'
          )
        });
        totalDateRef.value = { ...res.data };
        payForm.dateList = res.data.trainingStatDetails.map((item: any) => {
          return item.date;
        });
        payForm.payInfoList = res.data.trainingStatDetails.map((item: any) => {
          return item.qualifiedStudentCount;
        });
        payForm.studentList = res.data.trainingStatDetails.map((item: any) => {
          return item.unqualifiedStudentCount;
        });

        setChart();
      } catch (e) {
        console.log(e);
      }

      try {
        const res = await getTrainingList({
          ...state.pagination,
          ...getTimes(
            currentTimer.value,
            ['startTime', 'endTime'],
            'YYYY-MM-DD'
          )
        });

        state.tableList = res.data.rows;

        state.pagination.pageTotal = res.data.total;
        state.loading = false;
      } catch (e) {
        state.loading = false;
        console.log(e);
      }
      state.loading = false;
    };
    expose({ getList });
    const setChart = () => {
      setOptions({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              width: 2,
              color: '#A9C7FF'
            }
          }
        },
        legend: {
          show: false,
          selected: {
            //在这里设置默认展示就ok了
            达标人数: qualifiedFlag.value,
            未达标人数: unqualifiedFlag.value
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          axisLabel: {
            show: true
            // interval: 0
          },
          data: payForm.dateList
          // splitLine: {
          //   show: true,
          //   lineStyle: {
          //     width: 2,
          //     type: 'solid',
          //     color: 'rgba(226,226,226,0.5)'
          //   }
          // }
          // axisTick: {
          //   show: false
          // }
        },
        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.studentList,
            symbolSize: 10,
            type: 'line',
            name: '未达标人数',
            symbol: 'circle',
            smooth: true,
            itemStyle: {
              color: '#FF7AA7',
              borderColor: '#fff',
              borderWidth: 3
            },
            lineStyle: {
              width: 3 //设置线条粗细
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(255, 243, 246, 1)'
                    // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    // 100% 处的颜色
                    color: 'rgba(255, 246, 248, 0)'
                  }
                ]
              }
            },
            emphasis: {
              disabled: true
            }
          },
          {
            data: payForm.payInfoList,
            type: 'line',
            name: '达标人数',
            symbolSize: 10,
            symbol: 'circle',
            smooth: true,
            itemStyle: {
              color: '#198CFE',
              borderColor: '#fff',
              borderWidth: 3
            },
            lineStyle: {
              width: 2 //设置线条粗细
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(212, 231, 255, 1)'
                    // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: 'rgba(221, 235, 254, 0)' // 100% 处的颜色
                  }
                ]
              }
            },
            emphasis: {
              disabled: true
            }
          }
        ],

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

    return () => (
      <div class={styles.homeTrainData}>
        <div class={styles.TrainDataTop}>
          <div class={styles.TrainDataTopLeft}>
            <div class={styles.TrainDataItem}>
              <p class={styles.TrainDataItemTitle}>
                <div>
                  <span>
                    <NNumberAnimation
                      from={0}
                      to={totalDateRef.value.trainingCount}></NNumberAnimation>
                  </span>
                  次
                </div>
              </p>
              <p class={styles.TrainDataItemsubTitle}>作业次数</p>
            </div>
            <div class={styles.TrainDataItem}>
              <p class={styles.TrainDataItemTitle}>
                <div>
                  <span>
                    <NNumberAnimation
                      from={0}
                      to={
                        totalDateRef.value.totalStudentCount
                      }></NNumberAnimation>
                  </span>
                  人次
                </div>
              </p>
              <p class={styles.TrainDataItemsubTitle}>应交总人次</p>
            </div>
            <div class={styles.TrainDataItem}>
              <p class={styles.TrainDataItemTitle}>
                <div>
                  <span>
                    <NNumberAnimation
                      from={0}
                      to={
                        totalDateRef.value.submitStudentCount
                      }></NNumberAnimation>
                  </span>
                  人次
                </div>
              </p>
              <p class={styles.TrainDataItemsubTitle}>提交总人次</p>
            </div>
            <div class={styles.TrainDataItem}>
              <p class={styles.TrainDataItemTitle}>
                <div>
                  <span>
                    <NNumberAnimation
                      from={0}
                      to={
                        totalDateRef.value.qualifiedStudentCount
                      }></NNumberAnimation>
                  </span>
                  人次
                </div>
              </p>
              <p class={styles.TrainDataItemsubTitle}>达标总人次</p>
            </div>
            <div class={styles.TrainDataItem}>
              <p class={styles.TrainDataItemTitle}>
                <div>
                  <span>
                    <NNumberAnimation
                      from={0}
                      to={totalDateRef.value.trainingRate}></NNumberAnimation>
                  </span>
                  %
                </div>
              </p>
              <p class={styles.TrainDataItemsubTitle}>作业提交率</p>
            </div>
            <div class={styles.TrainDataItem}>
              <p class={styles.TrainDataItemTitle}>
                <div>
                  <span>
                    <NNumberAnimation
                      from={0}
                      to={totalDateRef.value.qualifiedRate}></NNumberAnimation>
                  </span>
                  %
                </div>
              </p>
              <p class={styles.TrainDataItemsubTitle}>作业达标率</p>
            </div>
          </div>
          <div class={styles.TrainDataTopRight}>
            <div
              onClick={() => {
                qualifiedFlag.value = !qualifiedFlag.value;
                setChart();
              }}
              class={[
                styles.DataTopRightItem,
                qualifiedFlag.value ? '' : styles.DataTopRightItemDis
              ]}>
              <div class={styles.DataTopRightDot}></div>
              <p>达标人数</p>
            </div>
            <div
              onClick={() => {
                unqualifiedFlag.value = !unqualifiedFlag.value;
                setChart();
              }}
              class={[
                styles.DataTopRightItem,
                unqualifiedFlag.value ? '' : styles.DataTopRightItemDis
              ]}>
              <div class={[styles.DataTopRightDot, styles.red]}></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
          />
        </div>
      </div>
    );
  }
});
