<template>
  <div class="app-container">
    <div>
      <el-steps :active="active" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="监控信息"></el-step>
        <el-step title="信息确认"></el-step>
      </el-steps>
      <!--    内容区   -->
      <div style="margin-top: 30px;">
        <!--    active:0    -->
        <div v-show="active === 0">
           <Form ref="formRef" style="text-align: center;" :formList="formList" :ruleFormData="ruleFormData" :config="config" @fnClick="callback"></Form>
        </div>
        <!--    active:2    -->
        <div v-show="active === 1">
          <el-tabs type="border-card" v-model="activeTypeName" @tab-click="handleClick">
            <!--    2-1    -->
            <el-tab-pane label="Linux系统" name="linux">
              <el-tabs v-model="linuxActiveName" @tab-click="handleClick">
                <!--    2-1-1    -->
                <el-tab-pane label="监控项" name="monitorItem">
                  <el-collapse v-model="activeNames">
                    <el-collapse-item v-for="(item,index) of linuxSystem.monitorItem['dataList']" :title="item.title" :name="index">
                      <template slot="title">
                        {{item.title}}
                        <el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" :disabled="item.disabled" class="ml20" @change="(checked) => handleCheckAllChange(checked,item)">全选</el-checkbox>
                      </template>
                      <el-checkbox-group v-model="checkParams[item.modelName]" @change="(checkValList) => handleCheckedCitiesChange(checkValList, item)" style="padding: 0 20px;">
                        <el-checkbox v-for="city of item.checkList" :label="city.id" :key="city.id" :disabled="item.disabled" class="w45 mt10 mb10">
                          <span style="width: 200px" class="disInlineBlock">{{city.metricKey}}</span>
                          <span>{{city.metricName}}</span>
                        </el-checkbox>
                      </el-checkbox-group>
                    </el-collapse-item>
                  </el-collapse>
                </el-tab-pane>
                <!--    2-1-2    -->
                <el-tab-pane label="自动发现项" name="autodiscoverItem">
                  <el-collapse v-model="activeNames">
                    <el-collapse-item v-for="(item,index) of linuxSystem.autodiscoverItem['dataList']" :title="item.title" :name="index">
                      <div style="display: flex;justify-content: center;">
                        <el-checkbox-group v-model="checkParams[item.modelName]" style="padding: 0 20px;">
                          <el-checkbox v-for="city of item.checkList" :disabled="item.disabled" :label="city.id" :key="city.id" class="mt10 mb10 disBlock">
                            <span style="width: 200px" class="disInlineBlock">{{city.metricKey}}</span>
                            <span>{{city.metricName}}</span>
                          </el-checkbox>
                        </el-checkbox-group>
                      </div>
                    </el-collapse-item>
                  </el-collapse>
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
            <!--    2-2    -->
            <el-tab-pane label="华为交换机" name="switch">
              <span slot="label">
                华为交换机
                <el-tooltip trigger="click" effect="dark" placement="top">
                  <template #content>针对CloudEngine 58&68&78&88&98系列</template>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-tabs v-model="hwActiveName" @tab-click="handleClick">
                <!--    2-2-1    -->
                <el-tab-pane label="监控项" name="monitorItem">
                  <template v-for="(item,index) of monitorTable['nodeOne']">
                    <TableList :ref="`tableRef_${item.config.tableKey}`" :config="item.config" :columns="switchColumns" :queryParams="{total: 0}" :tableList="item.tableList"  @fnClick="callback"></TableList>
                  </template>
                </el-tab-pane>
                <!--    2-2-2    -->
                <el-tab-pane label="自动发现项" name="autodiscoverItem">
                  <el-collapse v-model="activeNames">
                    <el-collapse-item v-for="(val,index) of monitorTable['nodeTow']" :title="val.title" :name="index">
                      <TableList :class="val && val.classType" :ref="`tableRef_${val.config.tableKey}`" :config="val.config" :columns="switchColumns" :queryParams="{total: 0}" :tableList="val.tableList"  @fnClick="callback"></TableList>
                    </el-collapse-item>
                  </el-collapse>
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
          </el-tabs>
        </div>
        <!--    active:3    -->
        <div v-show="active === 2">
          <MonitorTempView :ruleForm="ruleFormData" :otherList="synthesisList"></MonitorTempView>
        </div>
      </div>
    </div>
    <el-button type="primary" v-show="active > 1" style="float: right;margin-top: 12px;margin-left: 10px;" @click="submit">提交</el-button>
    <el-button type="primary" v-show="active < 2" style="float: right;margin-top: 12px;" @click="next('1')">下一步</el-button>
    <el-button type="primary" v-show="active > 0" style="float: right;margin-top: 12px;" @click="next('-1')">上一步</el-button>
    <el-button type="primary" style="float: right;margin-top: 12px;" @click="goBack">返回</el-button>
  </div>
</template>

<script setup>
  import Form from '@/components/form/index.vue';
  import TableList from "@/components/table/index.vue"
  import {getMonitorTempList} from "@/api/disRevenue/resource"
  import MonitorTempView from './view'
  export default {
    name: 'MonitorTempDetails',
    components: {Form, TableList, MonitorTempView},
    data() {
      return {
        active: 0,
        activeNames: [0, 1,2,3],
        activeTypeName: 'linux',  // 两个系统
        linuxActiveName: 'monitorItem', // linux系统下的两个栏
        hwActiveName: 'monitorItem',  // 华为交换机下的两个栏
        dataListMap: {},  // 存储监控字段
        checkAllParams: {},
        checkParams: {cpu: [], other: [], point: [], net:[], disk: [], docker: []},
        allSelectedData: {},
        synthesisList: {},
        // 第一节点
        ruleFormData: {
          id: null,
          switchName: '',
          serverPort: ''
        },
        config: {
          buttonGroup: []
        },
        formList: [{
          config: {title: ''},
          controls: {
            id: {label: 'ID',hidden: true},
            switchName: {label: '模版名称', span: 12, type: 'input', style: 'display: block;margin: 0 auto;', rules: [{required: true, message: '请输入模版名称', trigger: 'blur'}]},
            serverPort: {label: '描述', span: 12, type: 'textarea'}
          }
        }],
        // 第二节点 1栏
        linuxSystem: {
          monitorItem: {
            firstTitle: 'Linux系统', title: '监控项',
            dataList: [{
              title: 'CPU监控', modelName: 'cpu', checkAll: true, isIndeterminate: false, disabled: true,
              checkList: [
                {id: '1', name: 'system.cpu.load.avg1', towName: 'CPU的1分钟负载'},
                {id: '2', name: 'system.cpu.util.normal', towName: 'CPU正常运行时间'},
                {id: '3', name: 'system.cpu.load.avg5', towName: 'CPU的5分钟负载'},
                {id: '4', name: 'system.cpu.utilee.idle', towName: 'CPU空闲时间'},
                {id: '5', name: 'system.cpu.load.avg15', towName: 'CPU的15分钟负载'},
              ]},
              {
                title: '其他监控', modelName: 'other', checkAll: false, isIndeterminate: false,
                checkList: []
              }
            ],
          },
          autodiscoverItem: {
            firstTitle: 'Linux系统', title: '自动发现项',
            dataList:[{
              title: '发现挂载文件系统', modelName: 'point', checkAll: false, isIndeterminate: false, disabled: true,
              checkList: []
              }, {
                title: '发现网络接口', modelName: 'net', checkAll: false, isIndeterminate: false, disabled: true,
                checkList: []
              }, {
                  title: '发现硬盘设备', modelName: 'disk', checkAll: false, isIndeterminate: false, disabled: true,
                  checkList: []
              }, {
                  title: '发现docker', modelName: 'docker', checkAll: false, isIndeterminate: false, disabled: true,
                  checkList: []
              }
            ]
          },
        },
        // 第二节点 2栏 列显隐信息
        switchColumns: {
          id: { label: `ID`, visible: false },
          metricKey: { label: `监控标识`, visible: true},
          metricName: { label: `监控名称`, visible: true},
          oid: { label: `监控OID`, visible: true },
          filterValue: { label: `过滤值`, visible: true},
          monitorDescription: { label: `自动监控说明`, visible: true}
        },
        monitorTable: {
          nodeOne: [{
            firstTitle: '华为交换机', secondTitle: '监控项',
            tableList: [],
            config: {tableKey: 'web', colTopHiddenIcon: true}
          }],
          nodeTow: [
            {
              firstTitle: '华为交换机', secondTitle: '自动发现项', title: '网络端口发现', classType: 'checkHidden',
              tableList: [],
              config: {tableKey: 'web1', colTopHiddenIcon: true, selectable: true}
            },
            {
              firstTitle: '华为交换机', secondTitle: '自动发现项',title: 'MPU发现', classType: 'checkHidden',
              tableList: [],
              config: {tableKey: 'web2', colTopHiddenIcon: true, selectable: true}
            },
            // {
            //   firstTitle: '华为交换机', secondTitle: '自动发现项',title: '电源发现', classType: 'checkHidden',
            //   tableList: [
            //     {id: 1, ident: 'sysDescr', name: '系统描述', monitor: '1.3.6.1.2.1.1.1', filter: '', explain: ''},
            //     {id: 2, ident: 'sysObjectID', name: '系统Object ID', monitor: '1.3.6.1.2.1.1.2', filter: '', explain: ''},
            //     {id: 3, ident: 'sysUpTime', name: '系统运行时间', monitor: '1.3.6.1.2.1.1.1', filter: '', explain: ''},
            //     {id: 4, ident: 'sysContact', name: '系统联系信息', monitor: '1.3.6.1.2.1.1.1', filter: '', explain: '', relevance: {id: [2]}},
            //     {id: 5, ident: 'sysName', name: '系统名称', monitor: '1.3.6.1.2.1.1.1', filter: '', explain: ''},
            //   ],
            //   config: {tableKey: 'web2', colTopHiddenIcon: true, selectable: true}
            // },
            {
              firstTitle: '华为交换机', secondTitle: '自动发现项',title: '风扇发现', classType: 'checkHidden',
              tableList: [],
              config: {tableKey: 'web2', colTopHiddenIcon: true, selectable: true}
            },
        ]},
      }
    },
    created() {
      Object.keys(this.linuxSystem).forEach(res => {
        this.linuxSystem[res]['dataList'].forEach(item => {
          this.checkAllParams[item.modelName] = {
            firstTitle: this.linuxSystem[res].firstTitle,
            secondTitle: this.linuxSystem[res].title,
            lastTitle: item.title,
            data: []
          }
        });
      })
    },
    methods: {
      fnGetMonitorTempList(params) {
        let towType = this.hwActiveName;
        towType = this.linuxActiveName;
        getMonitorTempList(params).then(res => {
          // console.log('data====',res);
          if (this.activeTypeName === 'linux') {
            if (this.linuxActiveName === 'monitorItem'){
              this.linuxSystem[this.linuxActiveName].dataList[0].checkList = res.data && res.data.cpu;
              this.linuxSystem[this.linuxActiveName].dataList[1].checkList = res.data && res.data.other;
              // 全选操作
              this.handleCheckAllChange(true, this.linuxSystem[this.linuxActiveName].dataList[0]);
            } else {
              this.checkParams.point = res.data.point.map(item => item.id);
              this.checkParams.net = res.data.net.map(item => item.id);
              this.checkParams.disk = res.data.disk.map(item => item.id);
              this.checkParams.docker = res.data.docker.map(item => item.id);
              this.linuxSystem[this.linuxActiveName].dataList[0].checkList = res.data && res.data.point;
              this.linuxSystem[this.linuxActiveName].dataList[1].checkList = res.data && res.data.net;
              this.linuxSystem[this.linuxActiveName].dataList[2].checkList = res.data && res.data.disk;
              this.linuxSystem[this.linuxActiveName].dataList[3].checkList = res.data && res.data.docker;
            }
          } else {
            if (params.itemType === 'monitorItem') {
              let defaultNum = 0;
              let relevance = {id: []};
              res.data.system.forEach((item,index) => {
                if (item && item.filterValue === '9') {
                  defaultNum = index;
                }
                if (item && item.monitorDescription === '如果需要设备索引，当选中此项的时候，设备索引项自动选中') {
                  relevance['id'].push(item.id);
                }
              });
              res.data.system[defaultNum]['relevance'] = relevance;
              this.monitorTable.nodeOne[0].tableList = res.data.system;
            } else {
              this.monitorTable.nodeTow[0].tableList = res.data.netport;
              this.monitorTable.nodeTow[1].tableList = res.data.lightmodule;
              this.monitorTable.nodeTow[2].tableList = res.data.fan;
            }
          }
        });
      },
      async next(num) {
        console.log('num====',num,'this.active===',this.active);
        if (num === '-1') {
          this.active--;
        } else {
          if (this.active === 0 && !await this.fnFormValid()) {
            return;
          } else {
            this.handleClick();
          }
          if (this.active === 1) {
            this.selectAllChange();
          }
          this.active++;
        }
      },
      handleClick() {
        let params = {};
        if (this.activeTypeName === 'linux') {
          params = {resourceType: this.activeTypeName, itemType: this.linuxActiveName};
        } else {
          params = {resourceType: this.activeTypeName, itemType: this.hwActiveName};
        }
        this.fnGetMonitorTempList(params);
      },
      // form验证
      fnFormValid() {
        return new Promise((resolve) => {
          this.ruleFormData = {};
          const formValid = this.$refs.formRef.$refs.ruleForm;
          // 3. 操作form（如验证）
          formValid.validate((valid) => {
            if (valid) {
              this.ruleFormData = formValid.model;
              resolve(true);
            } else {
              resolve(false);
            }
          });
        });
      },
      // 点击下一步，获取多个table列表中所选中的行数据
      selectAllChange () {
        this.allSelectedData = {};
        Object.keys(this.monitorTable).forEach(res => {
          this.monitorTable[res].forEach(item => {
            // 获取子组件的ref（格式：tableRef_${tableKey}）
            const tableRef = this.$refs[`tableRef_${item.config.tableKey}`];
            if (tableRef && tableRef.length && tableRef[0].ids.length) {
              // 调用子组件的方法获取选中数据
              const selectedData = tableRef[0].getSelectedData();
              // firstTitle: '华为交换机', secondTitle: '监控项',
              selectedData['firstTitle'] = item.firstTitle;
              selectedData['secondTitle'] = item.secondTitle;
              selectedData['lastTitle'] = item.title;
              this.allSelectedData[selectedData.tableKey] = selectedData;
            }
          });
        });
        this.lastStepView();
      },
      // 最后一步展示
      lastStepView() {
        this.synthesisList = Object.assign({}, this.checkAllParams, this.allSelectedData);
      },
      // 全选按钮
      handleCheckAllChange(checked, itemAll) {
        let arrList = itemAll.checkList.map(item => {return item.id});
        this.checkParams[itemAll.modelName] = checked ? arrList : [];
        this.checkAllParams[itemAll.modelName].data = checked ? itemAll.checkList : [];
        itemAll.isIndeterminate = false;
      },
      // 单个选择按钮
      handleCheckedCitiesChange(checkValList, iteListAll) {
        iteListAll.checkAll = checkValList.length === iteListAll['checkList'].length;
        iteListAll.isIndeterminate = checkValList.length > 0 && checkValList.length < iteListAll['checkList'].length;
        // this.checkParams[iteListAll.modelName] = checkValList;
        this.checkAllParams[iteListAll.modelName].data = iteListAll['checkList'].filter(item =>
          checkValList.includes(item.id)
        );
      },
      // 提交
      submit() {
        console.log('ruleFormData==',this.ruleFormData);
        console.log('synthesisList==',this.synthesisList);
      },
      // 返回
      goBack() {
        this.$router.push({path:'/resource/monitorTemp'});
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'submit':
              console.log('dataVal===',dataVal);
              break;
            default:
          }
        }
      }
    }
  }
</script>
<style scoped>
  ::v-deep .el-collapse-item__header {
    background-color: #d4e3fc!important;
    /*color: #fff!important;*/
    padding-left: 20px;
    font-size: 1rem;
  }
  ::v-deep .checkHidden .el-table .el-table__fixed .el-table__header-wrapper .el-table__header .el-table-column--selection .el-checkbox__input {
    display: none!important;
  }
</style>
