<template>
  <div class="app-container pageTopForm">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" size="small" label-width="80px" class="demo-ruleForm">
      <el-col :span="6">
        <el-form-item label="交换机名称" prop="uplinkSwitch">
          <el-select
            v-model="queryParams.uplinkSwitch"
            placeholder="请选择交换机名称"
            clearable
            @change="changeEvent">
            <el-option
              v-for="item in uplinkList"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="接口名称" prop="interfaceName">
          <el-select
            v-model="queryParams.interfaceName"
            placeholder="请选择接口名称"
            clearable>
            <el-option
              v-for="item in interfaceList"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="业务名称" prop="hardwareSn">
          <el-input
            v-model="queryParams.hardwareSn"
            placeholder="请选择业务名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-col>
<!--      <el-col :span="6">-->
<!--        <el-form-item label="服务器节点名称" title="服务器节点名称" prop="nodeName">-->
<!--          <el-select-->
<!--            v-model="queryParams.nodeName"-->
<!--            placeholder="请输入服务器节点名称"-->
<!--            clearable>-->
<!--            <el-option-->
<!--              v-for="item in nodeNameList"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--      </el-col>-->
      <el-col :span="6">
        <el-form-item label="类型" prop="bandwidthType">
          <el-select
            v-model="queryParams.bandwidthType"
            placeholder="请选择类型"
            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="6" 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="6" 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="6">
        <el-form-item class="lastBtnSty">
          <el-button type="primary" size="mini" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-col>
    </el-form>

    <!-- 表格数据 -->
    <TableList :columns="columns" :config="config" :queryParams="queryParams" :tableList="tableList" @fnClick="callback" @fnRenderList="getList" @value-change="handleValueChange">
      <!--    资源类型    -->
      <template #tempType="{ row, column }">
        <dict-tag :options="dict.type.rm_topology_type" :value="row.interfaceLinkDeviceType"/>
      </template>
      <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>
    </TableList>
  </div>
</template>

<script>
  import {listBandWidth, recalBandWidth} from "@/api/disRevenue/earnManage"
  import {listAllResourList,resNameBtType, postInterFaceName} from "@/api/disRevenue/resource"
  import EchartsLine from "@/components/echartsList/line.vue";
  import TableList from "@/components/table/index.vue";
  export default {
    name: 'SwitchTabs',
    dicts: ['sys_normal_disable','eps_bandwidth_type','rm_topology_type'],
    components: {TableList,EchartsLine},
    props: {
      activeName: {
        type: String,
        default: "1000"
      }
    },
    watch: {
      activeName: {
        handler(val) {
          this.getList();
        },
        deep: true,
        immediate: true
      }
    },
    data() {
      return {
        tableList: [],
        loading: true,
        showSearch: true,
        uplinkList:[],  // 交换机名称
        interfaceList:[],  // 接口名称
        // nodeNameList:[],  // 服务器节点名称
        // 列显隐信息
        columns: {
          id: { label: `ID`,width: '50', visible: false },
          uplinkSwitch: { label: `交换机名称`, minWidth: '180', visible: true },
          hardwareSn: { label: `硬件SN`, minWidth: '200'},
          interfaceName: { label: `接口名称`, minWidth: '120',visible: true },
          interfaceLinkDeviceType: { label: `接口连接设备类型`, slotName: 'tempType',minWidth: '180',
            slotHeaderName: '不同的类型统计方式不一样，当类型是服务器时，使用的是接口的接收流量，95带宽值Mbs/日和95带宽值Mbs/月统计的是交换机接口的接收流量；当类型是机房出口的时候，95带宽值Mbs/日和95带宽值Mbs/月统计的是交换机接口的发送流量', visible: true },
          interfaceRemark: {label: `接口备注`,minWidth: '150'},
          bandwidth95Daily: { label: `95带宽值/日(Mbit)`, minWidth: '200', slotName: 'tempDay', visible: true },
          bandwidth95Monthly: { label: `95带宽值/月(Mbit)`, minWidth: '200', slotName: 'tempMonth', visible: true},
          avgMonthlyBandwidth95: {label: `月均日95值(Mbit`, minWidth: '200', slotName: 'tempDay', visible: true},
          clientId: {label: `ClientID`,minWidth: '150'},
          businessId: {label: `业务代码`,minWidth: '150'},
          businessName: {label: `业务名称`,minWidth: '100'},
          // nodeName: { label: `服务器节点名称`, minWidth: '200'},
          // effectiveBandwidth95Daily: {label: `有效95带宽值Mbps/日`, minWidth: '200', slotName: 'tempDay', visible: true },
          // effectiveBandwidth95Monthly: {label: `有效95带宽值Mbps/月`, minWidth: '200', slotName: 'tempMonth',},
          // effectiveAvgMonthlyBandwidth95: {label: `有效月均日95值Mbps`, minWidth: '200', slotName: 'tempDay'},
          createTime: { label: `创建时间`, minWidth: '160'},
          lastModifyTime: { label: `修改时间`, minWidth: '160'}
        },
        config: {
          // searcherForm: [
          //   {label: '交换机名称', prop: 'roleName', type: 'selset', options: []}
          // ],
          tableButton: {
            top: [
              {content: '导出', fnCode: 'export', type: 'warning', icon: 'el-icon-download', hasPermi: 'earnManage:switch:export'},
              {content: '图形分析', fnCode: 'echartView', type: 'success', icon: 'el-icon-data-analysis', hasPermi: 'earnManage:switch:graphicAnalysis'},
              {content: '生成接口月均日95值', fnCode: 'createData', type: 'success', icon: 'el-icon-data-analysis', hasPermi: 'earnManage:switch:add'},
            ],
            line: [
              {content: '相关数据', fnCode: 'edit', type: 'text', icon: 'el-icon-tickets', hasPermi: 'earnManage:switch:relevantData'},
              {content: '重新计算', fnCode: 'calculate', type: 'text', icon: 'el-icon-brush', hasPermi: 'earnManage:switch:calculate'},
              {}
            ]
          }
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          total: 0,
          uplinkSwitch:undefined,
          interfaceName:undefined,
          hardwareSn:undefined,
          nodeName:undefined,
          bandwidthType:undefined,
          bandwidth95Daily:undefined,
          bandwidth95Monthly:undefined,
          packageBandwidthDaily: undefined,
          avgMonthlyBandwidth95: undefined,
          effectiveBandwidth95Daily: undefined,
          effectiveBandwidth95Monthly: undefined,
          effectiveAvgMonthlyBandwidth95: undefined,
        }
      }
    },
    created() {
      // this.getList(1);
      this.fnSelectAllName();
    },
    // activated() {
    //   this.getList();
    // },
    methods: {
      /** 查询角色列表 */
      getList(num) {
        this.loading = true;
        let newParams = {...this.queryParams};
        delete newParams['total'];
        newParams['calculationMode'] = this.activeName;
        newParams['resourceType'] = 2;
        if (newParams['bandwidth95Daily']) {
          newParams['startTime'] = newParams['bandwidth95Daily'][0];
          newParams['endTime'] = newParams['bandwidth95Daily'][1];
          delete newParams['bandwidth95Daily'];
        }
        if (newParams['bandwidth95Monthly']) {
          newParams['startTime'] = newParams['bandwidth95Monthly'][0];
          newParams['endTime'] = newParams['bandwidth95Monthly'][1];
          delete newParams['bandwidth95Monthly'];
        }
        if (newParams['packageBandwidthDaily']) {
          newParams['startTime'] = newParams['packageBandwidthDaily'][0];
          newParams['endTime'] = newParams['packageBandwidthDaily'][1];
          delete newParams['packageBandwidthDaily'];
        }
        if (newParams['avgMonthlyBandwidth95']) {
          newParams['startTime'] = newParams['avgMonthlyBandwidth95'][0];
          newParams['endTime'] = newParams['avgMonthlyBandwidth95'][1];
          delete newParams['avgMonthlyBandwidth95'];
        }
        if (newParams['effectiveBandwidth95Daily']) {
          newParams['startTime'] = newParams['effectiveBandwidth95Daily'][0];
          newParams['endTime'] = newParams['effectiveBandwidth95Daily'][1];
          delete newParams['effectiveBandwidth95Daily'];
        }
        if (newParams['effectiveBandwidth95Monthly']) {
          newParams['startTime'] = newParams['effectiveBandwidth95Monthly'][0];
          newParams['endTime'] = newParams['effectiveBandwidth95Monthly'][1];
          delete newParams['effectiveBandwidth95Monthly'];
        }
        if (newParams['effectiveAvgMonthlyBandwidth95']) {
          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;
        })
      },
      fnSelectAllName() {
        resNameBtType({resourceType: 2}).then(res => {
          if(res && res.length > 0) {
            this.uplinkList = res && res.map(item => {
              return Object.assign({label: item.resourceName, value: item.resourceName, ipAddress: item.ipAddress});
            });
          }
        });
        // resNameBtType({resourceType: 1}).then(res => {
        //   if(res && res.length > 0) {
        //     this.nodeNameList = res && res.map(item => {
        //       return Object.assign({label: item.resourceName, value: item.resourceName, ipAddress: item.ipAddress});
        //     });
        //   }
        // });
      },
      changeEvent(val){
        let params = {};
        this.uplinkList.find(item => {
          if (item.label === val) {
            params = {switchIp: item.ipAddress};
          }
        });
        postInterFaceName(Object.assign({},{resourceType: 2}, params)).then(res => {
          this.interfaceList = res && res.map(item => {
            return Object.assign({label: item.interfaceName, value: item.interfaceName});
          });
        });
      },
      /** 搜索按钮操作 */
      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: 2, 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 'insert':
              this.$router.push({
                path:'/earnManage/switch/list/index'});
              break;
            case 'edit':
              this.$router.push({
                path:'/earnManage/switch/list/index',
                query:{
                  id: rowData.id,
                  bandwidthType: rowData && rowData.bandwidthType
                }
              });
              break;
            case 'echartView':
              // if (selectList && selectList.length <= 0) {
              //   this.$modal.msgWarning("请选择数据！");
              //   return;
              // }
              this.graphicAnalysis(selectList);
              break;
            case 'createData':
              this.$router.push({
                path:'/earnManage/switch/edit/index',
                query:{
                  resourceType: 2
                }
              });
              break;
            case 'calculate':
              recalBandWidth(rowData.id).then(res => {
                this.getList();
                this.$modal.msgSuccess("操作成功！");
              }).catch(() => {});
              break;
            case 'export':
              // let dataList = [];
              // Object.keys(this.columns).forEach(item => {
              //   if (item.visible) {
              //     dataList.push(item.prop);
              //   }
              // });
              // this.download("system/bandwidth/export", {properties: dataList, resourceType: 2}, `交换机带宽收益_${new Date().getTime()}.xlsx`);
              let paramsList = Object.assign(this.queryParams,rowData, {resourceType: 2, calculationMode: this.activeName});
              this.download("system/bandwidth/export", paramsList, `交换机带宽收益_${new Date().getTime()}.xlsx`, null, 'json');
              break;
            default:
          }
        }
      }
    }
  }
</script>
<style>
  ::v-deep .el-tooltip__popper.is-dark{
    width: 350px!important; /* 固定宽度 */
    white-space: normal!important; /* 允许换行（默认不换行） */
  }
</style>
<style scoped>
  ::v-deep .lastBtnSty .el-form-item__content{
    margin-left: 10px!important;
  }
</style>
