<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">
                <!--    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" 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.metricKey" :key="city.metricKey" :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">
                      <template slot="title">
                        {{item.title}}
                        <el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" class="ml20" @change="(checked) => handleCheckAllChange(checked,item)">全选</el-checkbox>
                      </template>
                      <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.metricKey" :key="city.metricKey" 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">
                <!--    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, addMonitorTemp, updateMonitorTemp, getMonitorTemp} from "@/api/disRevenue/resource"
  import MonitorTempView from './view'
  export default {
    name: 'MonitorTempDetails',
    components: {Form, TableList, MonitorTempView},
    data() {
      return {
        paramsData: {},
        tempContent: {},
        active: 0,
        activeNames: [0, 1,2,3, 4],
        activeTypeName: 'linux',  // 两个系统
        linuxActiveName: 'monitorItem', // linux系统下的两个栏
        hwActiveName: 'monitorItem',  // 华为交换机下的两个栏
        dataListMap: {},  // 存储监控字段
        checkAllParams: {},
        checkParams: {cpu: [], other: [], point: [], net:[], disk: [], docker: []},
        allSelectedData: {},
        synthesisList: {},
        // 第一节点
        ruleFormData: {},
        config: {
          buttonGroup: []
        },
        formList: [{
          config: {title: ''},
          controls: {
            id: {label: 'ID',hidden: true},
            templateName: {label: '模版名称', span: 12, type: 'input', style: 'display: block;margin: 0 auto;', rules: [{required: true, message: '请输入模版名称', trigger: 'blur'}]},
            description: {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: 'vfs', checkAll: true, isIndeterminate: false, disabled: true,
              checkList: []
              }, {
                title: '发现网络接口', modelName: 'net', checkAll: true, isIndeterminate: false, disabled: true,
                checkList: []
              }, {
                  title: '发现硬盘设备', modelName: 'disk', checkAll: true, isIndeterminate: false, disabled: true,
                  checkList: []
              }, {
                  title: '发现docker', modelName: 'docker', checkAll: true, isIndeterminate: false, disabled: true,
                  checkList: []
              }
            ]
          },
        },
        // 第二节点 2栏 列显隐信息
        switchColumns: {
          id: { label: `ID`, visible: true},
          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: '光模块发现', classType: 'checkHidden',
              tableList: [],
              config: {tableKey: 'web2', colTopHiddenIcon: true, selectable: true}
            },
            {
              firstTitle: '华为交换机', secondTitle: '自动发现项',title: 'MPU发现', classType: 'checkHidden',
              tableList: [],
              config: {tableKey: 'web3', colTopHiddenIcon: true, selectable: true}
            },
            {
              firstTitle: '华为交换机', secondTitle: '自动发现项',title: '电源发现', classType: 'checkHidden',
              tableList: [],
              config: {tableKey: 'web4', colTopHiddenIcon: true, selectable: true}
            },
            {
              firstTitle: '华为交换机', secondTitle: '自动发现项',title: '风扇发现', classType: 'checkHidden',
              tableList: [],
              config: {tableKey: 'web5', colTopHiddenIcon: true, selectable: true}
            },
        ]},
      }
    },
    created() {
      this.paramsData = this.$route && this.$route.query;
      // console.log('paramsData===',this.paramsData);
      if (this.paramsData && this.paramsData.id) {
        this.getFormDataList(this.paramsData.id);
      }
      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: {
      // 获取详情
      getFormDataList(id) {
        this.tempContent = {};
        getMonitorTemp(id).then(val => {
          if (val && val.data) {
            this.activeTypeName = val.data.template.resourcyType;
            this.ruleFormData = val.data.template;
            this.tempContent[val.data.template.resourcyType] = val.data[val.data.template.resourcyType];
          }
        }).catch(() => {
          // this.$modal.msgError("操作失败")
        });
      },
      fnGetMonitorTempList(params) {
        this.$modal.loading();
        getMonitorTempList(params).then(res => {
          // console.log('data====',res,'params==',params);
          if (this.activeTypeName === 'linux') {
            if (params.itemType === 'monitorItem'){
              this.linuxSystem[params.itemType].dataList[0].checkList = res.data && res.data.cpu;
              this.linuxSystem[params.itemType].dataList[1].checkList = res.data && res.data.other;
              if (this.tempContent && this.tempContent['linux']) {
                // cpu
                if (this.tempContent['linux'] && this.tempContent['linux'].cpu && this.tempContent['linux'].cpu.length > 0) {
                  this.linuxSystem[params.itemType].dataList[0].checkAll = true;
                  // 全选操作
                  this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[0]);
                } else {
                  this.linuxSystem[params.itemType].dataList[0].checkAll = false;
                  // let newLinuxOne = {...this.linuxSystem[params.itemType].dataList[0]};
                  // newLinuxOne['checkList'] = this.tempContent['linux'] && this.tempContent['linux'].cpu;
                  // let checkData = this.tempContent && this.tempContent['linux'] ? newLinuxOne : this.linuxSystem[params.itemType].dataList[0];
                  // // 全选操作 this.tempContent['linux'].cpu
                  // this.handleCheckAllChange(true, checkData);
                }
                // other
                if (res.data && res.data.other && res.data.other.length === this.tempContent['linux'] && this.tempContent['linux'].other && this.tempContent['linux'].other.length) {
                  this.linuxSystem[params.itemType].dataList[1].checkAll = true;
                  // 全选操作
                  this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[1]);
                } else {
                  this.linuxSystem[params.itemType].dataList[1].checkAll = false;
                  let newLinuxOne = {...this.linuxSystem[params.itemType].dataList[1]};
                  newLinuxOne['checkList'] = [];
                  this.tempContent['linux'].other.some(item => {
                    this.linuxSystem[params.itemType].dataList[1].checkList.some(val => {
                      if (item.metricKey === val.metricKey){
                        newLinuxOne['checkList'].push(val);
                        return true;
                      }
                    });
                  });
                  // 全选操作
                  this.handleCheckAllChange(true, newLinuxOne, true);
                }
              } else {
                this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[0]);
              }
            } else {
              this.linuxSystem[params.itemType].dataList[0].checkList = res.data && res.data.vfs;
              this.linuxSystem[params.itemType].dataList[1].checkList = res.data && res.data.net;
              this.linuxSystem[params.itemType].dataList[2].checkList = res.data && res.data.disk;
              this.linuxSystem[params.itemType].dataList[3].checkList = res.data && res.data.docker;
              if (this.paramsData && this.paramsData.id) {
                // vfs
                if (this.tempContent['linux'] && this.tempContent['linux'].vfs && this.tempContent['linux'].vfs.length > 0) {
                  this.linuxSystem[params.itemType].dataList[0].checkAll = true;
                  this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[0]);
                } else {
                  this.linuxSystem[params.itemType].dataList[0].checkAll = false;
                }
                // net
                if (this.tempContent['linux'] && this.tempContent['linux'].net && this.tempContent['linux'].net.length > 0) {
                  this.linuxSystem[params.itemType].dataList[1].checkAll = true;
                  this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[1]);
                } else {
                  this.linuxSystem[params.itemType].dataList[1].checkAll = false;
                }
                // disk
                if (this.tempContent['linux'] && this.tempContent['linux'].disk && this.tempContent['linux'].disk.length > 0) {
                  this.linuxSystem[params.itemType].dataList[2].checkAll = true;
                  this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[2]);
                } else {
                  this.linuxSystem[params.itemType].dataList[2].checkAll = false;
                }
                // docker
                if (this.tempContent['linux'] && this.tempContent['linux'].docker && this.tempContent['linux'].docker.length > 0) {
                  this.linuxSystem[params.itemType].dataList[3].checkAll = true;
                  this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[3]);
                } else {
                  this.linuxSystem[params.itemType].dataList[3].checkAll = false;
                }
              } else {
                this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[0]);
                this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[1]);
                this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[2]);
                this.handleCheckAllChange(true, this.linuxSystem[params.itemType].dataList[3]);
              }
            }
          } else {
            if (params.itemType === 'monitorItem') {
              let defaultNum = 0;
              let relevance = {id: []};
              res.data.switchOther.forEach((item,index) => {
                if (item && item.filterValue === '9') {
                  defaultNum = index;
                }
                if (item && item.monitorDescription === '如果需要设备索引，当选中此项的时候，设备索引项自动选中') {
                  relevance['id'].push(item.id);
                }
              });
              res.data.switchOther[defaultNum]['relevance'] = relevance;
              this.monitorTable.nodeOne[0].tableList = res.data.switchOther;
              if (this.paramsData && this.paramsData.id) {
                let tabDefSel = [];
                this.tempContent['switch'].switchOther.some(item => {
                  res.data.switchOther.some(val => {
                    if (item.metricKey === val.metricKey) {
                      tabDefSel.push(val);
                      return;
                    }
                  });
                });
                setTimeout(() => {
                  this.$refs[`tableRef_web`][0].defaultSelectRows(tabDefSel);
                },500);
              }
            } else {
              if (this.paramsData && this.paramsData.id) {
                // 网络
                this.monitorTable.nodeTow[0].tableList = res.data.switchNet;
                if (this.tempContent['switch'] && this.tempContent['switch'].switchNet && this.tempContent['switch'].switchNet.length > 0) {
                  setTimeout(() => {
                    this.$refs[`tableRef_web1`][0].selectAllRows();
                  },500);
                }
                // 光模块
                this.monitorTable.nodeTow[1].tableList = res.data.switchModule;
                if (this.tempContent['switch'] && this.tempContent['switch'].switchModule && this.tempContent['switch'].switchModule.length > 0) {
                  setTimeout(() => {
                    this.$refs[`tableRef_web2`][0].selectAllRows();
                  },500);
                }
                // MPU
                this.monitorTable.nodeTow[2].tableList = res.data.switchMpu;
                if (this.tempContent['switch'] && this.tempContent['switch'].switchMpu && this.tempContent['switch'].switchMpu.length > 0) {
                  setTimeout(() => {
                    this.$refs[`tableRef_web3`][0].selectAllRows();
                  },500);
                } else {
                }
                // 电源
                this.monitorTable.nodeTow[3].tableList = res.data.switchPwr;
                if (this.tempContent['switch'] && this.tempContent['switch'].switchPwr && this.tempContent['switch'].switchPwr.length > 0) {
                  setTimeout(() => {
                    this.$refs[`tableRef_web4`][0].selectAllRows();
                  },500);
                }
                // 风扇
                this.monitorTable.nodeTow[4].tableList = res.data.switchFan;
                if (this.tempContent['switch'] && this.tempContent['switch'].switchFan && this.tempContent['switch'].switchFan.length > 0) {
                  setTimeout(() => {
                    this.$refs[`tableRef_web5`][0].selectAllRows();
                  },500);
                }
              } else {
                this.monitorTable.nodeTow[0].tableList = res.data.switchNet;
                this.monitorTable.nodeTow[1].tableList = res.data.switchModule;
                this.monitorTable.nodeTow[2].tableList = res.data.switchMpu;
                this.monitorTable.nodeTow[3].tableList = res.data.switchPwr;
                this.monitorTable.nodeTow[4].tableList = res.data.switchFan;
                setTimeout(() => {
                  this.$refs[`tableRef_web1`][0].selectAllRows();
                  this.$refs[`tableRef_web2`][0].selectAllRows();
                  this.$refs[`tableRef_web3`][0].selectAllRows();
                  this.$refs[`tableRef_web4`][0].selectAllRows();
                  this.$refs[`tableRef_web5`][0].selectAllRows();
                },500);
              }
            }
          }
          this.$modal.closeLoading();
        });
      },
      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 if (this.active === 1) {
            this.selectAllChange();
          } else {
            this.handleClick();
          }
          this.active++;
        }
      },
      handleClick() {
        let itemTypeList = ['monitorItem', 'autodiscoverItem'];
        itemTypeList.forEach(item => {
          let params = {resourceType: this.activeTypeName, itemType: item};
          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() {
        if (this.activeTypeName === 'linux') {
          this.synthesisList = Object.assign({}, this.checkAllParams);
        } else {
          this.synthesisList = Object.assign({}, this.allSelectedData);
        }

      },
      // 全选按钮
      handleCheckAllChange(checked, itemAll, isIndetBool) {
        // console.log('itemAll===',itemAll.checkList);
        let arrList = itemAll && itemAll.checkList && itemAll.checkList.map(item => {return item.metricKey});
        this.checkParams[itemAll.modelName] = checked ? arrList : [];
        this.checkAllParams[itemAll.modelName].data = checked ? itemAll.checkList : [];
        itemAll.isIndeterminate = isIndetBool ? true : 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.metricKey)
        );
      },
      // 提交
      submit() {
        let params = Object.assign({}, {monitorIds: '', resourceType: this.activeTypeName}, this.ruleFormData);
        let idList = [];
        Object.keys(this.synthesisList).forEach(item => {
          idList = idList.concat(this.synthesisList[item].data.map(val => val.id));
        });
        params['monitorIds'] = idList;
        this.$modal.loading();
        let fnType = addMonitorTemp;
        if (this.paramsData && this.paramsData.id) {
          fnType = updateMonitorTemp;
        }
        fnType(params).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$router.push("/resource/monitorTemp");
          this.$modal.closeLoading();
        }).catch(() => {
          this.$modal.closeLoading();
          this.$modal.msgError("操作失败")
        });
        // 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;
  }
</style>
