<template>
  <el-container>
    <el-header style="margin-top: 10px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="hover" class="stat-card">
            <el-row :gutter="20">
              <el-col :span="8">
                <h2 style="color: green; font-size: 30px">{{ totalNum }}</h2>
                <p class="success">总发布量</p>
              </el-col>
              <el-col :span="16">
                <div ref="pushLine" style="height: 150px"></div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <h2 style="color: orange; font-size: 30px">{{ imageNum }}</h2>
            <p class="warning">图片发布</p>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <h2 style="color: green; font-size: 30px">{{ videoNum }}</h2>
            <p class="success">视频发布</p>
          </el-card>
        </el-col>
      </el-row>
    </el-header>

    <el-main style="margin-top: 90px">
      <el-card shadow="hover" style="margin-top: 10px; height: 60px">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="40px">
          <el-form-item label="">
            <el-button type="warning" plain icon="Download" @click="handleExport">报表导出</el-button>
          </el-form-item>
          <el-form-item label="" prop="sourceType">
            <el-input v-model="queryParams.sourceName" style="width: 150px" placeholder="请输入文件名称" @input="getRecordList"
                      clearable></el-input>
          </el-form-item>
          <el-form-item label="" prop="sourceType">
            <el-select v-model="queryParams.sourceType" style="width: 150px" placeholder="请选择类型" @change="getRecordList"
                       clearable>
              <el-option v-for="dict in smsb_source_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="sourceTag">
            <el-select v-model="queryParams.sourceTag" style="width: 150px" placeholder="请选择分类" @change="getRecordList"
                       clearable>
              <el-option v-for="dict in smsb_source_classify" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="dataRage" style="width: 500px">
            <el-col :span="12" style="text-align: right">
              <el-radio-group v-model="timeRadio" size="small" @change="handleDateRangeChange">
                <!--              <el-radio-button label="今日" value="today" />-->
                <el-radio-button label="近7天" value="week" />
                <el-radio-button label="近30天" value="month" />
                <el-radio-button label="自定义" value="diy" />
              </el-radio-group>
            </el-col>
            <el-col :span="12" style="text-align: right">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="-"
                start-placeholder="开始日期" :disabled="diyFlag" :clearable="false" @change="handleDateRangeChange" end-placeholder="结束日期" style="margin-left: 10px; margin-right: 30px" />
            </el-col>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card style="margin-top: 10px">
        <div class="table-content">
          <el-table v-loading="loading" :data="playRecordList">
            <el-table-column label="资源ID" align="left" prop="sourceId" width="250" />
            <el-table-column label="资源名称" align="left" prop="fileName" :show-overflow-tooltip="true" />
            <el-table-column label="播放次数" align="center" prop="playTimes" width="200" />
            <el-table-column label="播放时长" align="center" prop="playDuration" width="200" />
            <el-table-column label="分类" align="center" prop="fileTag" width="120">
              <template #default="scope">
                <dict-tag :options="smsb_source_classify" :value="scope.row.fileTag" />
              </template>
            </el-table-column>
            <el-table-column label="类型" align="center" prop="fileType" width="120">
              <template #default="scope">
                <dict-tag :options="smsb_source_type" :value="scope.row.fileType" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
              <template #default="scope">
                <el-tooltip content="查看详情" placement="top">
                  <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getRecordList" />
      </el-card>
    </el-main>
  </el-container>
  <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body :style="{ height: '850px' }">
    <div>
      <el-row :gutter="20">
        <el-col :span="16" style="text-align: right">
          <el-radio-group v-model="DTimeRadio" size="small" @change="DHandleDateRangeChange">
            <!--              <el-radio-button label="今日" value="today" />-->
            <el-radio-button label="近7天" value="week" />
            <el-radio-button label="近30天" value="month" />
          </el-radio-group>
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-date-picker :disabled="true" v-model="DDateRange" type="daterange" range-separator="-"
            start-placeholder="开始日期" end-placeholder="结束日期" style="margin-left: 10px; margin-right: 30px" />
        </el-col>
      </el-row>
    </div>
    <div ref="tadLine" class="chart-placeholder"></div>
    <div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-table v-loading="loading" :data="deviceRecordList">
            <el-table-column label="设备名称" align="center" prop="deviceName" />
            <el-table-column label="播放次数" align="center" prop="playTimes" />
            <el-table-column label="播放时长" align="center" prop="duration" />
          </el-table>
        </el-col>
        <el-col :span="12">
          <el-table v-loading="loading" :data="itemRecordList">
            <el-table-column label="组名称" align="center" prop="itemName" />
            <el-table-column label="类型" align="center" prop="itemType">
              <template #default="scope">
                <dict-tag :options="smsb_item_type" :value="scope.row.itemType" />
              </template>
            </el-table-column>
            <el-table-column label="播放次数" align="center" prop="playTimes" />
            <el-table-column label="播放时长" align="center" prop="duration" />
          </el-table>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import {
  getPushLine,
  listDeviceAndItem,
  listPlayRecordSummary,
  pushNumber,
  timesAndDurationLine
} from '@/api/smsb/source/play_record';
import {SourcePlayRecordForm, SourcePlayRecordQuery, SourcePlayRecordVO} from '@/api/smsb/source/play_record_type';
import {onUnmounted} from 'vue';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {smsb_source_classify, smsb_source_type, smsb_item_type} = toRefs<any>(
  proxy?.useDict('smsb_source_classify', 'smsb_source_type', 'smsb_item_type')
);
const loading = ref(true);
const playRecordList = ref<SourcePlayRecordVO[]>([]);
const deviceRecordList = ref<SourcePlayRecordVO[]>([]);
const itemRecordList = ref<SourcePlayRecordVO[]>([]);
const timeRadio = ref('week');
const DTimeRadio = ref('week');
const dateRange = ref(['2025-01-01', '2025-01-01']);
const DDateRange = ref(['2025-01-01', '2025-01-01']);
const totalNum = ref(0);
const imageNum = ref(0);
const videoNum = ref(0);
const pushLine = ref();
const total = ref(0);
const tadLine = ref();
const dialogSourceId = ref();
const diyFlag = ref(true);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const data = reactive<PageData<SourcePlayRecordForm, SourcePlayRecordQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sourceType: null,
    sourceTag: null,
    startTime: null,
    endTime: null,
    sourceName: null
  },
  rules: {}
});

const getTimesAndDurationLine = async () => {
  const params = {
    startTime: DDateRange.value[0],
    endTime: DDateRange.value[1],
    sourceId: dialogSourceId.value
  };
  const res = await timesAndDurationLine(params);
  const playDurationList = res.data.playDurationList.map((seconds) => Math.round((seconds / 60) * 100) / 100);
  if (!tadLine.value) {
    // console.log('[tadLine] ref is null when initializing echarts');
  } else {
    // console.log('[tadLine] ref:', tadLine.value);
  }
  if (tadLine.value) {
    echarts.dispose(tadLine.value);
    // console.log('[tadLine] echarts instance disposed before init');
  }
  const tadLineInstance = echarts.init(tadLine.value, 'macaroons');
  // console.log('[tadLine] echarts instance created:', tadLineInstance);
  tadLineInstance.setOption({
    title: {
      text: ''
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['播放次数', '播放时长（分钟）']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: res.data.timeList
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '播放次数',
        type: 'line',
        stack: 'Total',
        data: res.data.playTimesList
      },
      {
        name: '播放时长（分钟）',
        type: 'line',
        stack: 'Total',
        data: playDurationList
      }
    ]
  });
};
const { queryParams, form, rules } = toRefs(data);
const getPushNumber = async () => {
  const res = await pushNumber();
  totalNum.value = res.data.totalNum;
  imageNum.value = res.data.imageNum;
  videoNum.value = res.data.videoNum;

  const lineRes = await getPushLine();
  if (!pushLine.value) {
    // console.log('[pushLine] ref is null when initializing echarts');
  } else {
    // console.log('[pushLine] ref:', pushLine.value);
  }
  if (pushLine.value) {
    echarts.dispose(pushLine.value);
    // console.log('[pushLine] echarts instance disposed before init');
  }
  const pushLineInstance = echarts.init(pushLine.value, 'macaroons');
  // console.log('[pushLine] echarts instance created:', pushLineInstance);
  pushLineInstance.setOption({
    title: {
      text: ''
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: lineRes.data.timeList
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '',
        type: 'line',
        stack: 'Total',
        data: lineRes.data.numberList
      }
    ]
  });
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'source/playRecord/summary/export',
    {
      ...queryParams.value
    },
    `playRecord_${new Date().getTime()}.xlsx`
  );
};
const handleView = async (row?: SourcePlayRecordVO) => {
  dialog.title = row.fileName;
  dialog.visible = true;
  dialogSourceId.value = row.sourceId;
  DHandleDateRangeChange();
};
const getDeviceItemList = async () => {
  const params = {
    startTime: DDateRange.value[0],
    endTime: DDateRange.value[1],
    sourceId: dialogSourceId.value
  };
  const res = await listDeviceAndItem(params);
  deviceRecordList.value = res.data.deviceList;
  itemRecordList.value = res.data.itemList;
};
/** 查询资源播放记录列表 */
const getRecordList = async () => {
  loading.value = true;
  queryParams.value.startTime = dateRange.value[0];
  queryParams.value.endTime = dateRange.value[1];
  const res = await listPlayRecordSummary(queryParams.value);
  playRecordList.value = res.rows;
  playRecordList.value.forEach((item) => {
    item.playDuration = formatDuration(item.playDuration);
  });
  total.value = res.total;
  loading.value = false;
};
// 格式化秒数为 HH:mm:ss
const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;

  const paddedHours = String(hours).padStart(2, '0');
  const paddedMinutes = String(minutes).padStart(2, '0');
  const paddedSeconds = String(secs).padStart(2, '0');

  return `${paddedHours}:${paddedMinutes}:${paddedSeconds}`;
};
const handleDateRangeChange = () => {
  const rangeType = timeRadio.value;
  const today = new Date();
  const startDate = new Date();
  const endDate = new Date();
  switch (rangeType) {
    case 'week':
      startDate.setDate(today.getDate() - 7);
      dateRange.value = [formatDate(startDate), formatDate(endDate)];
      diyFlag.value = true;
      break;
    case 'month':
      startDate.setMonth(today.getMonth() - 1);
      dateRange.value = [formatDate(startDate), formatDate(endDate)];
      diyFlag.value = true;
      break;
    case "diy" :
      diyFlag.value = false;
      dateRange.value = [formatDate(dateRange.value[0]), formatDate(dateRange.value[1])];
      break;
    default:
      break
      // throw new Error('Invalid range type');
  }
  getRecordList();
  getPushNumber();
};
const DHandleDateRangeChange = () => {
  const rangeType = DTimeRadio.value;
  const today = new Date();
  const startDate = new Date();
  const endDate = new Date();
  switch (rangeType) {
    case 'today':
      break;
    case 'week':
      startDate.setDate(today.getDate() - 7);
      break;
    case 'month':
      startDate.setMonth(today.getMonth() - 1);
      break;
    default:
      throw new Error('Invalid range type');
  }
  DDateRange.value = [formatDate(startDate), formatDate(endDate)];
  getTimesAndDurationLine();
  getDeviceItemList();
};
const formatDate = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
onMounted(() => {
  handleDateRangeChange();
  // getPushNumber();
  // getRecordList();
});

onUnmounted(() => {
  if (pushLine?.value) {
    echarts.dispose(pushLine.value);
    // console.log('[play_info] pushLine disposed on unmount');
  }
  if (tadLine?.value) {
    echarts.dispose(tadLine.value);
    // console.log('[play_info] tadLine disposed on unmount');
  }
});
</script>
<style scoped>
.stat-card {
  text-align: center;
  height: 170px;
}

.number {
  font-size: 24px;
  font-weight: bold;
}

.success {
  color: green;
}

.danger {
  color: red;
}

.warning {
  color: orange;
}

.chart-placeholder {
  height: 250px;
  /*background: #f5f5f5;*/
  border-radius: 8px;
}

.disk-progress .el-progress--line {
  margin-bottom: 15px;
  max-width: 600px;
  margin-top: 50px;
}
</style>
