<template>
  <div class="pageTopForm">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" size="small" label-width="80px" class="demo-ruleForm">
      <el-col :span="8">
        <el-form-item label="ClientID" prop="clientId">
          <el-input
            v-model="queryParams.clientId"
            placeholder="请输入ClientID"
            clearable
            @keyup.enter.native="handleQuery">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="类型" prop="bandwidthType">
          <el-select
            v-model="queryParams.bandwidthType"
            placeholder="请选择类型"
            @change="selectChangeVal"
            clearable>
            <el-option
              v-for="dict in dict.type.eps_bandwidth_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="queryParams.bandwidthType === '1'">
        <el-form-item label="95带宽值Mbps/日" title="95带宽值Mbps/日" prop="bandwidth95Daily" :rules="[{ required: true, message: `95带宽值Mbps/日为必填项`, trigger: 'change' }]">
          <el-date-picker
            v-model="queryParams.bandwidth95Daily"
            type="daterange"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="queryParams.bandwidthType === '2'">
        <el-form-item label="95带宽值Mbps/月" title="95带宽值Mbps/月" prop="bandwidth95Monthly" :rules="[{ required: true, message: `95带宽值Mbps/月为必填项`, trigger: 'change' }]">
          <el-date-picker
            v-model="queryParams.bandwidth95Monthly"
            type="monthrange"
            value-format="yyyy-MM"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="queryParams.bandwidthType === '3'">
        <el-form-item label="包端带宽值Mbps/日" title="包端带宽值Mbps/日" prop="packageBandwidthDaily" :rules="[{ required: true, message: `包端带宽值Mbps/日为必填项`, trigger: 'change' }]">
          <el-date-picker
            v-model="queryParams.packageBandwidthDaily"
            type="daterange"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="queryParams.bandwidthType === '4'">
        <el-form-item label="月均日95值Mbps" title="月均日95值Mbps" prop="avgMonthlyBandwidth95" :rules="[{ required: true, message: `月均日95值Mbps为必填项`, trigger: 'change' }]">
          <el-date-picker
            v-model="queryParams.avgMonthlyBandwidth95"
            type="monthrange"
            format="yyyy-MM"
            value-format="yyyy-MM"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="queryParams.bandwidthType === '5'">
        <el-form-item label="有效95带宽值Mbps/日" title="有效95带宽值Mbps/日" prop="effectiveBandwidth95Daily" :rules="[{ required: true, message: `有效95带宽值Mbps/日为必填项`, trigger: 'change' }]">
          <el-date-picker
            v-model="queryParams.effectiveBandwidth95Daily"
            type="daterange"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="queryParams.bandwidthType === '6'">
        <el-form-item label="有效95带宽值Mbps/月" title="有效95带宽值Mbps/月" prop="effectiveBandwidth95Monthly" :rules="[{ required: true, message: `有效95带宽值Mbps/月为必填项`, trigger: 'change' }]">
          <el-date-picker
            v-model="queryParams.effectiveBandwidth95Monthly"
            type="monthrange"
            format="yyyy-MM"
            value-format="yyyy-MM"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="queryParams.bandwidthType === '7'">
        <el-form-item label="有效月均日95值Mbps" title="有效月均日95值Mbps" prop="effectiveAvgMonthlyBandwidth95" :rules="[{ required: true, message: `有效月均日95值Mbps为必填项`, trigger: 'change' }]">
          <el-date-picker
            v-model="queryParams.effectiveAvgMonthlyBandwidth95"
            type="daterange"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="业务名称" prop="businessName">
          <el-select
            v-model="queryParams.businessName"
            placeholder="请选择业务名称"
            clearable>
            <el-option
              v-for="dict in busNameList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item class="lastBtnSty">
          <!--  暂时不需要提交         v-hasPermi="['system:bandwidth:list']" -->
          <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] === 0">{{row[valueKey]}}/{{row.createTime}}</span>
      </template>
      <template #tempMonth="{ valueKey, row, column }">
        <span v-if="row && row[valueKey] || row[valueKey] === 0">{{row[valueKey]}}/{{row.createTime.slice(0, 7)}}</span>
      </template>
    </TableList>
  </div>
</template>

<script>
  import EchartsBar from "@/components/echartsList/bar.vue";
  import TableList from "@/components/table/index.vue";
  import {listBandWidth, avgDetailMsg, recalBandWidth, listAllBusinessList} from "@/api/disRevenue/earnManage"
  export default {
    name: 'ServerTabs',
    dicts: ['eps_bandwidth_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`, width: '50'},
          clientId: {label: `ClientID`, minWidth: '280', visible: true},
          hardwareSn: {label: `硬件SN`, minWidth: '150'},
          businessName: {label: `业务名称`, minWidth: '150', visible: true},
          businessId: {label: `业务代码`, minWidth: '150'},
          bandwidth95Daily: {label: `95带宽值/日(Mbit)`, minWidth: '150', slotName: 'tempDay',visible: true},
          bandwidth95Monthly: {label: `95带宽值/月(Mbit)`, minWidth: '150', slotName: 'tempMonth',visible: true},
          avgMonthlyBandwidth95: {label: `月均日95值(Mbit)`, minWidth: '150',slotName: 'tempDay',visible: true},
          machineFlow: {label: `金山machineCode`, minWidth: '150',visible: true},
          uplinkSwitch: {label: `上联交换机`, minWidth: '150'},
          uplinkSwitchPort: {label: `上联交换机端口`, minWidth: '150'},
          // effectiveBandwidth95Daily: {label: `有效95带宽值Mbps/日`, minWidth: '200', slotName: 'tempDay', visible: true},
          // packageBandwidthDaily: {label: `包端带宽值Mbps/日`, minWidth: '200', slotName: 'tempDay',visible: true},
          // effectiveBandwidth95Monthly: {label: `有效95带宽值Mbps/月`, minWidth: '200', slotName: 'tempMonth'},
          // effectiveAvgMonthlyBandwidth95: {label: `有效月均日95值Mbps`, minWidth: '200', slotName: 'tempDay'},
          updateTime: {label: `创建时间`, minWidth: '150'},
        },
        config: {
          // searcherForm: [
          //   {label: '交换机名称', prop: 'roleName', type: 'selset', options: []}
          // ],
          tableButton: {
            top: [
              {content: '导出', fnCode: 'export', type: 'warning', icon: 'el-icon-download', hasPermi: 'earnManage:server:export'},
              {content: '图形分析', fnCode: 'echartView', type: 'success', icon: 'el-icon-data-analysis', hasPermi: 'rocketmq:trafficAnalysis'},
              // {content: '生成月均日95值', fnCode: 'createData', type: 'success', icon: 'el-icon-data-analysis', hasPermi: 'earnManage:server:add'},
            ],
            line: [
              {content: '相关数据', fnCode: 'edit', type: 'primary', icon: 'el-icon-tickets', hasPermi: 'earnManage:server:relevantData'},
              {content: '重新计算', fnCode: 'calculate', type: 'primary', icon: 'el-icon-brush', hasPermi: 'earnManage:server:calculate'},
            ]
          }
        },
        queryParams: {
          pageNum: 1,
          pageSize: 8,
          total: 0,
          bandwidthType: undefined,
          bandwidth95Daily: undefined,
          bandwidth95Monthly: undefined,
          packageBandwidthDaily: undefined,
          avgMonthlyBandwidth95: undefined,
          effectiveBandwidth95Daily: undefined,
          effectiveBandwidth95Monthly: undefined,
          effectiveAvgMonthlyBandwidth95: undefined,
        },
        busNameList: []
      }
    },
    created() {
      // this.getList(1);
      this.busList();
    },
    // activated() {
    //   this.$nextTick(() => {
    //     this.getList();
    //   });
    // },
    methods: {
      busList() {
        listAllBusinessList().then(val => {
          this.busNameList = val && val.data.map(item => {
            return Object.assign({label: item.businessName, value: item.businessName});
          });
        });
      },
      selectChangeVal(val) {
        let params = {
          bandwidth95Daily: undefined,
          bandwidth95Monthly: undefined,
          packageBandwidthDaily: undefined,
          avgMonthlyBandwidth95: undefined,
          effectiveBandwidth95Daily: undefined,
          effectiveBandwidth95Monthly: undefined,
          effectiveAvgMonthlyBandwidth95: undefined,
        };
        this.queryParams = Object.assign({}, this.queryParams, params);
      },
      /** 查询角色列表 */
      getList(num) {
        this.loading = true;
        let newParams = {...this.queryParams};
        delete newParams['total'];
        newParams['calculationMode'] = this.activeName;
        newParams['resourceType'] = 1;
        if (newParams['bandwidth95Daily'] && newParams['bandwidth95Daily'].length > 1) {
          newParams['startTime'] = newParams['bandwidth95Daily'][0];
          newParams['endTime'] = newParams['bandwidth95Daily'][1];
        }
        delete newParams['bandwidth95Daily'];

        if (newParams['bandwidth95Monthly'] && newParams['bandwidth95Monthly'].length > 1) {
          newParams['startTime'] = newParams['bandwidth95Monthly'][0];
          newParams['endTime'] = newParams['bandwidth95Monthly'][1];
        }
        delete newParams['bandwidth95Monthly'];

        if (newParams['packageBandwidthDaily'] && newParams['packageBandwidthDaily'].length > 1) {
          newParams['startTime'] = newParams['packageBandwidthDaily'][0];
          newParams['endTime'] = newParams['packageBandwidthDaily'][1];
        }
        delete newParams['packageBandwidthDaily'];

        if (newParams['avgMonthlyBandwidth95'] && newParams['avgMonthlyBandwidth95'].length > 1) {
          newParams['startTime'] = newParams['avgMonthlyBandwidth95'][0];
          newParams['endTime'] = newParams['avgMonthlyBandwidth95'][1];
        }
        delete newParams['avgMonthlyBandwidth95'];

        if (newParams['effectiveBandwidth95Daily'] && newParams['effectiveBandwidth95Daily'].length > 1) {
          newParams['startTime'] = newParams['effectiveBandwidth95Daily'][0];
          newParams['endTime'] = newParams['effectiveBandwidth95Daily'][1];
        }
        delete newParams['effectiveBandwidth95Daily'];

        if (newParams['effectiveBandwidth95Monthly'] && newParams['effectiveBandwidth95Monthly'].length > 1) {
          newParams['startTime'] = newParams['effectiveBandwidth95Monthly'][0];
          newParams['endTime'] = newParams['effectiveBandwidth95Monthly'][1];
        }
        delete newParams['effectiveBandwidth95Monthly'];

        if (newParams['effectiveAvgMonthlyBandwidth95'] && newParams['effectiveAvgMonthlyBandwidth95'].length > 1) {
          newParams['startTime'] = newParams['effectiveAvgMonthlyBandwidth95'][0];
          newParams['endTime'] = newParams['effectiveAvgMonthlyBandwidth95'][1];
        }
        delete newParams['effectiveAvgMonthlyBandwidth95'];

        if (newParams && newParams.bandwidthType && !newParams['startTime']) {
          this.$refs['queryRef'].validate((valid) => {
            if (!valid) {
              return false;
            }
          });
          return;
        }
        listBandWidth(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 'edit':
              this.$router.push({
                path:'/earnManage/server/list/index',
                query:{
                  id: rowData.id,
                  bandwidthType: rowData && rowData.bandwidthType
                }
              });
              break;
            case 'echartView':
              this.graphicAnalysis(selectList);
              break;
            case 'createData':
              this.$router.push({
                path:'/earnManage/server/edit/index',
                query:{
                  resourceType: 1
                }
              });
              break;
            case 'calculate':
              let fnType = recalBandWidth;
              if (rowData && rowData.bandwidthType === '4') {
                fnType = avgDetailMsg;
              }
              fnType(rowData.id).then(res => {
                this.getList();
                this.$modal.msgSuccess("操作成功！");
              }).catch(() => {});
              break;
            case 'export':
              let newParams = {...this.queryParams};
              delete newParams['total'];
              newParams['calculationMode'] = this.activeName;
              newParams['resourceType'] = 1;
              if (newParams['bandwidth95Daily'] && newParams['bandwidth95Daily'].length > 1) {
                newParams['startTime'] = newParams['bandwidth95Daily'][0];
                newParams['endTime'] = newParams['bandwidth95Daily'][1];
              }
              delete newParams['bandwidth95Daily'];

              if (newParams['bandwidth95Monthly'] && newParams['bandwidth95Monthly'].length > 1) {
                newParams['startTime'] = newParams['bandwidth95Monthly'][0];
                newParams['endTime'] = newParams['bandwidth95Monthly'][1];
              }
              delete newParams['bandwidth95Monthly'];

              if (newParams['packageBandwidthDaily'] && newParams['packageBandwidthDaily'].length > 1) {
                newParams['startTime'] = newParams['packageBandwidthDaily'][0];
                newParams['endTime'] = newParams['packageBandwidthDaily'][1];
              }
              delete newParams['packageBandwidthDaily'];

              if (newParams['avgMonthlyBandwidth95'] && newParams['avgMonthlyBandwidth95'].length > 1) {
                newParams['startTime'] = newParams['avgMonthlyBandwidth95'][0];
                newParams['endTime'] = newParams['avgMonthlyBandwidth95'][1];
              }
              delete newParams['avgMonthlyBandwidth95'];

              if (newParams['effectiveBandwidth95Daily'] && newParams['effectiveBandwidth95Daily'].length > 1) {
                newParams['startTime'] = newParams['effectiveBandwidth95Daily'][0];
                newParams['endTime'] = newParams['effectiveBandwidth95Daily'][1];
              }
              delete newParams['effectiveBandwidth95Daily'];

              if (newParams['effectiveBandwidth95Monthly'] && newParams['effectiveBandwidth95Monthly'].length > 1) {
                newParams['startTime'] = newParams['effectiveBandwidth95Monthly'][0];
                newParams['endTime'] = newParams['effectiveBandwidth95Monthly'][1];
              }
              delete newParams['effectiveBandwidth95Monthly'];

              if (newParams['effectiveAvgMonthlyBandwidth95'] && newParams['effectiveAvgMonthlyBandwidth95'].length > 1) {
                newParams['startTime'] = newParams['effectiveAvgMonthlyBandwidth95'][0];
                newParams['endTime'] = newParams['effectiveAvgMonthlyBandwidth95'][1];
              }
              delete newParams['effectiveAvgMonthlyBandwidth95'];

              if (newParams && newParams.bandwidthType && !newParams['startTime']) {
                this.$refs['queryRef'].validate((valid) => {
                  if (!valid) {
                    return false;
                  }
                });
                return;
              }
              let paramsList = Object.assign(newParams,rowData, {resourceType: 1,calculationMode: this.activeName});
              this.download("system/bandwidth/export", paramsList, `服务器带宽收益_${new Date().getTime()}.xlsx`, null, 'json');
              break;
            default:
          }
        }
      },
    }
  }
</script>

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