<template>
  <div class="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="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="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="请选择类型"
            @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="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" :modelIdent="this.$options.name" :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] === 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 {listBandWidth, recalBandWidth, listAllBusinessList} from "@/api/disRevenue/earnManage"
  import {listAllResourList,resNameBtType, postInterFaceName, listAllSwitchName} 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:[],  // 服务器节点名称
        busNameList: [],
        // 列显隐信息
        columns: {
          id: { label: `ID`,width: '50', visible: false },
          uplinkSwitch: { label: `交换机名称`, minWidth: '120', visible: true },
          hardwareSn: { label: `硬件SN`, minWidth: '220'},
          interfaceName: { label: `接口名称`, minWidth: '100',visible: true },
          interfaceLinkDeviceType: { label: `接口连接设备类型`, slotName: 'tempType',minWidth: '130', visible: true },
          interfaceRemark: {label: `接口备注`,minWidth: '120'},
          bandwidth95Daily: { label: `95带宽值/日(Mbit)`, minWidth: '180', slotName: 'tempDay', visible: true },
          bandwidth95Monthly: { label: `95带宽值/月(Mbit)`, minWidth: '180', slotName: 'tempMonth', visible: true},
          avgMonthlyBandwidth95: {label: `月均日95值(Mbit`, minWidth: '180', slotName: 'tempDay', visible: true},
          clientId: {label: `ClientID`,minWidth: '320'},
          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'},
          updateTime: { label: `创建时间`, minWidth: '120'},
          updateTime: { label: `修改时间`, minWidth: '120'}
        },
        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: 'primary', icon: 'el-icon-tickets', hasPermi: 'earnManage:switch:relevantData'},
              {content: '重新计算', fnCode: 'calculate', type: 'primary', icon: 'el-icon-brush', hasPermi: 'earnManage:switch:calculate'},
            ]
          }
        },
        queryParams: {
          pageNum: 1,
          pageSize: 8,
          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();
      this.busList();
    },
    // activated() {
    //   this.getList();
    // },
    methods: {
      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'] = 2;
        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;
        })
      },
      fnSelectAllName() {
        listAllSwitchName({}).then(res => {
          if(res && res.data.length > 0) {
            this.uplinkList = res && res.data.map(item => {
              return Object.assign({label: item.switchName, value: item.switchName, clientId: item.clientId});
            });
          }
        });
        // 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});
        //     });
        //   }
        // });
      },
      busList() {
        listAllBusinessList().then(val => {
          this.busNameList = val && val.data.map(item => {
            return Object.assign({label: item.businessName, value: item.businessName});
          });
        });
      },
      changeEvent(val){
        let params = {};
        this.uplinkList.find(item => {
          if (item.label === val) {
            params = {clientId: item.clientId};
          }
        });
        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 newParams = {...this.queryParams};
              delete newParams['total'];
              newParams['calculationMode'] = this.activeName;
              newParams['resourceType'] = 2;
              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: 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>
