<template>
  <div class="pageTopForm">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" size="small" label-width="80px" class="demo-ruleForm" @submit.native.prevent>
      <el-col :span="8">
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="queryParams.taskName"
            placeholder="请输入任务名称"
            clearable
            @keyup.enter.native="handleQuery">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item class="lastBtnSty">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-col>
    </el-form>

    <!-- 表格数据 -->
    <TableList class="w100 h100" :columns="columns" :config="config" :modelIdent="this.$options.name" :queryParams="queryParams" :tableList="tableList" @fnClick="callback" @fnRenderList="getList" @value-change="handleValueChange">
      <template #tempDay="{ valueKey, row, column }">
        <span v-if="row && row[valueKey]">{{row[valueKey]}}/{{row.createTime}}</span>
      </template>
      <template #tempMonth="{ valueKey, row, column }">
        <span v-if="row && row[valueKey]">{{row[valueKey]}}/{{row.createTime.slice(0, 7)}}</span>
      </template>
      <template #tempResType="{ row, column }">
        <dict-tag :options="dict.type.resource_type" :value="row.resourceType"/>
      </template>
      <template #tempStatus="{ row, column }">
        <dict-tag :options="dict.type.task_status" :value="row.taskStatus"/>
      </template>
    </TableList>
  </div>
</template>

<script>
  import EchartsBar from "@/components/echartsList/bar.vue";
  import TableList from "@/components/table/index.vue";
  import {listTaskStatic, taskRecaculate} from "@/api/disRevenue/earnManage"
  export default {
    name: 'busValueCount',
    dicts: ['eps_bandwidth_type', 'task_status', 'resource_type'],
    components: {TableList, EchartsBar},
    props: {
      activeName: {
        type: String,
        default: "1000"
      }
    },
    watch: {
      activeName: {
        handler(val) {
          this.getList();
        },
        deep: true,
        immediate: true
      }
    },
    data() {
      return {
        tableList: [],
        loading: true,
        showSearch: true,
        // 列显隐信息
        columns: {
          id: {label: `ID`},
          taskName: {label: `任务名称`, minWidth: '150', visible: true},
          businessName: {label: `业务名称`, minWidth: '150', visible: true},
          resourceType: { label: `包含资源类型`, minWidth: '200', slotName: 'tempResType'},
          includedResources: { label: `包含资源`, minWidth: '300'},
          calculationType: {label: `计算类型`, minWidth:  '150'},
          percentile95: {label: `95值(Mbit)`, minWidth: '100',visible: true},
          monthlyAvgPercentile95: {label: `月均日95值(Mbit)`, minWidth: '150',visible: true},
          // js: {label: `外部数据记录95值(Mbit)`, minWidth: '200'},
          timeRange: {label: `时间段`, minWidth: '200',visible: true},
          taskStatus: {label: `任务状态`, minWidth: '80', slotName: 'tempStatus', visible: true},
          updateTime: {label: `修改时间`, minWidth: '150'},
          createTime: {label: `创建时间`, minWidth: '150'},
        },
        config: {
          tableButton: {
            top: [
              {content: '新增', fnCode: 'add', type: 'primary', icon: 'el-icon-plus', hasPermi: 'earnManage:busValueCount:add'},
              {content: '导出', fnCode: 'export', type: 'warning', icon: 'el-icon-download', hasPermi: 'earnManage:busValueCount:export'},
            ],
            line: [
              {content: '相关数据', fnCode: 'edit', type: 'primary', icon: 'el-icon-tickets', hasPermi: 'earnManage:busValueCount:relevantData'},
              {content: '重新计算', fnCode: 'calculate', type: 'primary', icon: 'el-icon-brush', hasPermi: 'earnManage:busValueCount:calculate'},
              {content: '图形查看', fnCode: 'echartView', type: 'primary', icon: 'el-icon-data-analysis', hasPermi: 'earnManage:busValueCount:graphicAnalysis'},
            ]
          }
        },
        queryParams: {
          pageNum: 1,
          pageSize: 8,
          total: 0,
        },
      }
    },
    // created() {
    //   this.$nextTick(() => {
    //     this.getList(1);
    //   });
    // },
    // activated() {
    //   this.$nextTick(() => {
    //     this.getList();
    //   });
    // },
    methods: {
      /** 查询角色列表 */
      getList(num) {
        this.loading = true;
        let newParams = {...this.queryParams};
        delete newParams['total'];
        newParams['calculationMode'] = this.activeName;
        listTaskStatic(newParams).then(response => {
          this.tableList = response.rows;
          this.queryParams.total = response.total;
          this.loading = false;
        })
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.$refs['queryRef'].validate((valid) => {
          if (!valid) {
            return false;
          }
        });
        this.queryParams.pageNum = 1;
        this.getList();
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryRef");
        this.handleQuery();
      },

      /** 图形分析 */
      graphicAnalysis(list) {
        const dictTypeArr = this.dict.type.eps_bandwidth_type;
        // 生成唯一 key（避免数据冲突）
        const storageKey = `temp_data_${Date.now()}`;
        // 1. 将数据存入 localStorage（需序列化）
        localStorage.setItem(storageKey, JSON.stringify({list: list, dictList: dictTypeArr, resourceType: 1, activeName: this.activeName}));
        // 1. 用 Vue Router 解析目标路由的完整 URL
        const routeLocation = this.$router.resolve({
          name: 'DialogView',
          query: { storageKey }
        });
        // 2. 打开新窗口（routeLocation.href 是完整路径）
        window.open(routeLocation.href, '_blank');
        // _blank：新标签页；_self：当前窗口（默认）
      },

      chartDataEvent(val) {
        // console.log('val===',val);
        return val;
      },

      // 处理子组件传递的新值
      handleValueChange(newValue) {
        // 父组件更新自身数据，实现同步
        this.showSearch = newValue;
        // console.log('父组件拿到新值:', newValue);
      },
      callback(result, rowData, selectChange, selectList) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'add':
              this.$router.push({
                path:'/earnManage/busValueCount/edit/index',
                query: {
                  calculationMode: this.activeName
                }
              });
              break;
            case 'edit':
              this.$router.push({
                path:'/earnManage/busValueCount/list/index',
                query:{
                  id: rowData.id,
                  resourceType: rowData && rowData.resourceType,
                  calculationType: rowData && rowData.calculationType,
                  calculationMode: this.activeName
                }
              });
              break;
            case 'echartView':
              this.$router.push({
                path:'/earnManage/busValueCount/chart/index',
                query:{
                  id: rowData.id,
                  taskName: rowData && rowData.taskName,
                  calculationType: rowData && rowData.calculationType,
                  resourceType: rowData && rowData.resourceType
                }
              });
              // this.graphicAnalysis(selectList);
              break;
            case 'calculate':
              // let fnType = taskRecaculate;
              taskRecaculate({id: rowData.id}).then(res => {
                this.getList();
                this.$modal.msgSuccess("操作成功！");
              }).catch(() => {});
              break;
            case 'export':
              let paramsList = Object.assign(this.queryParams,rowData, {calculationMode: this.activeName});
              this.download("system/taskStatistics/export", paramsList, `业务95值计算_${new Date().getTime()}.xlsx`, null, 'json');
              break;
            default:
          }
        }
      },
    }
  }
</script>

<style scoped>
  ::v-deep .lastBtnSty .el-form-item__content{
    margin-left: 10px!important;
  }
</style>
