<template>
  <div class="app-container">
    <div style="display: flex; justify-content: center;">
      <div class="w100">
        <Form ref="formRef" :formList="formList" :config="{labelWidth: '140px',buttonGroup: []}" :ruleFormData="ruleFormData" @fnClick="callback"></Form>
      </div>
    </div>
    <div>
      <h3 style="padding: 15px 10px;border-bottom: 1px solid #ddd;">策略内容</h3>
      <template v-if="!(paramsData && paramsData.readonly)">
        <el-tabs v-model="activeName" class="plr-20">
          <el-tab-pane label="监控项" name="first">
            <el-collapse v-model="activeFirstName">
              <el-collapse-item title="固定监控项" :name="0">
                <template slot="title">
                  <span class="disInlineBlock" style="width: 15%;">固定监控项</span>
                  <div style="font-size: 13px;margin-left: 10%;">
                    采集周期：<el-select v-model="firstChangeTime" id="selDisabled" clearable placeholder="请选择" @change="handleChangeTime">
                    <el-option v-for="val in timeOptions" :key="val.value" :label="val.label" :value="val.value"></el-option>
                  </el-select>
                  </div>
                </template>
                <div v-for="item of firstData">
                  <div class="plr-50">
                    <div v-for="city of item.checkList" class="w100 mt10 mb10 disInlineBlock fontSize15">
                      <div class="disInlineBlock w50">
                        <span style="width: 200px" class="disInlineBlock">{{ city.metricKey }}</span>
                        <span>{{city.metricName}}</span>
                      </div>
                      <div class="disInlineBlock" style="color: #606266">
                        采集周期：<el-select v-model="city['time']" placeholder="请选择" clearable>
                        <el-option v-for="val in timeOptions" :key="val.value" :label="val.label" :value="val.value"></el-option>
                      </el-select>
                      </div>
                    </div>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-tab-pane>
          <el-tab-pane label="自动发现项" name="second">
            <el-collapse v-model="activeTwoName">
              <el-collapse-item v-for="(item,key,index) of secondData" :title="item.title" :name="index">
                <template slot="title">
                  <span class="disInlineBlock" style="width: 15%;">{{item.title}}</span>
                  <div style="font-size: 13px;margin-left: 10%;">
                    采集周期：<el-select v-model="item['time']" id="selDisabled" :disabled="key === 'switchNet' ? true : false" clearable placeholder="请选择">
                    <el-option v-for="val in timeOptions" :key="val.value" :label="val.label" :value="val.value"></el-option>
                  </el-select>
                  </div>
                </template>
                <div class="plr-50">
                  <div v-for="city of item.checkList" class="w100 mt10 mb10 disBlock fontSize15">
                    <span style="width: 300px" class="disInlineBlock">{{city.metricKey}}</span>
                    <span>{{city.metricName}}</span>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-else>
        <el-collapse v-model="activeTwoName">
          <template v-for="(item,index) of firstData">
            <el-collapse-item v-if="item.checkList && item.checkList.length > 0" :title="'监控项'" :name="index">
              <template slot="title">
                <span><span v-if="ruleFormData.priority === '1'">华为交换机>></span>监控项</span>
              </template>
              <div v-for="item of firstData">
                <div class="plr-50">
                  <div v-for="city of item.checkList" class="w100 mt10 mb10 disInlineBlock fontSize15">
                    <div class="disInlineBlock w50">
                      <span style="width: 150px;color: #C0C4CC;" class="disInlineBlock">{{ city.metricName }}</span>
                      <span>{{city.metricKey}}</span>
                    </div>
                    <div class="disInlineBlock" style="color: #606266">
                      采集周期为{{city.timeLabel}}
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </template>
          <template v-for="(item,key,index) of secondData">
            <el-collapse-item v-if="item.checkList && item.checkList.length > 0" :title="item.title" :name="index">
              <template slot="title">
                <span><span v-if="ruleFormData.priority === '1'">华为交换机>></span>自动发现项>>{{item.title}}</span>
              </template>
              <div class="plr-50">
                当前所有子项的采集周期均为{{item.timeLabel}}
                <div v-for="city of item.checkList" class="w100 mt10 mb10 disBlock fontSize15">
                  <span style="width: 300px;color: #C0C4CC;" class="disInlineBlock">{{city.metricName}}</span>
                  <span>{{city.metricKey}}</span>
                </div>
              </div>
            </el-collapse-item>
          </template>
        </el-collapse>
      </template>
    </div>
    <el-button v-if="!(paramsData && paramsData.readonly)" style="float: right;margin-top: 12px;margin-left: 10px;" @click="cancel">取消</el-button>
    <el-button v-if="!(paramsData && paramsData.readonly)" type="primary" style="float: right;margin-top: 12px;" @click="submit">提交</el-button>
    <el-button v-if="paramsData && paramsData.readonly" style="float: right;margin-top: 12px;margin-left: 10px;" @click="cancel">返回</el-button>
    <!--    弹窗  -->
    <el-dialog title="旧策略信息" :visible.sync="policyOpen" width="900px" height="300px" append-to-body>
      <TableList ref="tabRef" :columns="columns" :config="{colHiddenCheck: true, colTopHiddenIcon: true, currentSel: true}" :queryParams="queryParams" :tableList="tableList" @fnClick="callback"></TableList>
      <div style="text-align: right;margin-right: 20px;margin-top: 20px;">
        <el-button type="primary" style="margin-left: 10px;" @click="submitPubilc">确定</el-button>
        <el-button @click="policyOpen = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Form from '@/components/form/index.vue';
  import TableList from "@/components/table/index.vue"
  import {addResourcePolicy, updateResourcePolicy,getMonitorTempList, getMonitorPolicy, listAllSwitchName, listMonitorPolicy} from "@/api/disRevenue/resource"
  export default {
    name: "MonitorStrategy",
    components: {Form, TableList},
    dicts: ['policy_status', 'collection_cycle', 'switch_type'],
    props: {
      open: {
        type: String,
        default: () => {}
      }
    },
    watch: {
      open: {
        handler(val) {
          if (val === 'type_false') {
            // 清空form
            this.$refs['formRef'].$refs.ruleForm.resetFields();
            this.currentDataList = {};
          }
        },
        deep: true,
        immediate: true
      },
    },
    data() {
      return {
        activeName: 'first',
        activeFirstName: [0],
        firstChangeTime: '',
        activeTwoName: [0,1,2,3,4],
        timeOptions: [],
        ruleFormData: {
          deployDevice: []
        },
        formList: [],
        firstData: [
          {checkList: []}
        ],
        tempContent: {},
        paramsData: {},
        secondData: {
          switchNet: {title: '网络端口发现', time: '300',
            checkList: []
          },
          switchModule: {title: '光模块发现', time: '',
            checkList: []
          },
          switchMpu: {title: 'MPU发现', time: '',
            checkList: []
          },
          switchPwr: {title: '电源发现', time: '',
            checkList: []
          },
          switchFan: {title: '风扇发现', time: '',
            checkList: []
          },
        },
        policyOpen: false,
        currentDataList: {},
        tableList: [],
        queryParams: {
          total: 0,
          pageNum: 1,
          pageSize: 10
        },
        // 列显隐信息
        columns: {
          id: { label: `ID`,width: '50'},
          policyName: { label: `策略名称`, minWidth: '200', visible: true },
          description: { label: `描述`,minWidth: '200',visible: true},
          deployDevice: { label: `部署设备`,minWidth: '320',visible: true},
          switchType: { label: `交换机类型`,minWidth: '150', slotName: 'tempType'},
          priority: { label: `优先级`,minWidth: '150'},
          connected: { label: `策略内容`,minWidth: '200'},
          status: { label: `策略状态`, minWidth: '100', slotName: 'tempStatus'},
          deployTime: { label: `下发策略时间`,minWidth: '160'},
          updateTime:{ label: `创建人`,minWidth: '160'},
          createTime: { label: `创建时间`,minWidth: '160'},
        },
      }
    },
    created() {
      this.timeOptions = this.dict.type.collection_cycle;
      this.paramsData = this.$route && this.$route.query;
      // console.log('paramsData===',this.paramsData);
      if (this.paramsData && this.paramsData.id) {
        this.getFormDataList(this.paramsData.id);
      } else {
        this.getDataList();
      }
      this.fnFormList();
      this.switchListName();
    },
    methods: {
      // 接口名称
      switchListName() {
        listAllSwitchName({}).then(val => {
          if(val && val.data) {
            // this.switchNameList = val && val.data;
            this.formList[0].controls.deployDevice['options'] = val && val.data.map(item => {
              return Object.assign({label: item.switchName, value: item.clientId, id: item.clientId});
            });
          }
        });
      },
      // formList集合
      fnFormList(objVal) {
        if (this.open) {
          this.formList = [{
            config: {},
            controls: {
              id: {label: 'ID',hidden: true},
              policyName: {label: '策略名称', span: 18, type: 'input', required: true},
              oldPolicy: {label: '引用旧策略', span: 3, type: 'button', style: 'vertical-align: top'},
              description: {label: '描述', span: 18, type: 'textarea'},
              switchType: {label: '交换机类型', span: 18, type: 'select', required: true, options: this.dict.type.switch_type},
              deployDevice: {label: '部署设备', span: 18, type: 'treeSelect', options:[], multiple: true, required: true},
            }
          }];
        } else {
          this.formList = [{
            config: {readonly: this.paramsData && this.paramsData.readonly, colSpan: this.paramsData && this.paramsData.readonly ? '' : 'disBlock'},
            controls: {
              id: {label: 'ID',hidden: true},
              policyName: {label: '策略名称', span: 12, type: 'input', style: 'display: inline-block;', required: true},
              oldPolicy: {label: '引用旧策略', span: 3, type: 'button', style: 'display: inline-block;vertical-align: top', hidden: this.paramsData && this.paramsData.readonly ? true : false},
              priority: {label: '优先级', span: 12, type: 'input', hidden: this.paramsData && this.paramsData.readonly ? false : true},
              status: {label: '策略状态', span: 12, type: 'select',options: this.dict.type.policy_status, hidden: this.paramsData && this.paramsData.readonly ? false : true},
              deployTime: {label: '下发策略时间', span: 12, type: 'date', hidden: this.paramsData && this.paramsData.readonly ? false : true},
              createTime: {label: '创建时间', span: 12, type: 'datetime', hidden: this.paramsData && this.paramsData.readonly ? false : true},
              switchType: {label: '交换机类型', span: 12, type: 'select', required: true, options: this.dict.type.switch_type},
              createBy: {label: '创建人', span: 12, type: 'input',hidden: this.paramsData && this.paramsData.readonly ? false : true},
              deployDevice: {label: '部署设备', span: 12, type: 'treeSelect', options:[], multiple: true, required: true},
              description: {label: '描述', span: 12, type: 'textarea'},
            }
          }];
        }
      },
      // 获取详情
      getFormDataList(id, btnGain) {
        this.tempContent = {};
        getMonitorPolicy(id).then(val => {
          if (val && val.data) {
            if (val.data && val.data.policy) {
              val.data.policy['policyName'] = btnGain && btnGain ? val.data.policy['policyName'] + '-引用' : val.data.policy['policyName'];
              val.data.policy['deployDevice'] = val.data.policy.deployDevice.split(',');
              // val.data.policy['status'] = Number(val.data.policy.status);
              this.ruleFormData = val.data.policy;
            }
            this.tempContent = val.data['switch'];
          }
          this.getDataList();
        }).catch(() => {
          this.getDataList();
          // this.$modal.msgError("操作失败")
        });
      },
      getDataList() {
        let itemTypeList = ['monitorItem', 'autodiscoverItem'];
        itemTypeList.forEach(item => {
          let params = {resourceType: 'switch', itemType: item};
          this.fnGetMonitorTempList(params);
        });
      },
      // 通过监控模版选项 查询监控策略展示项
      fnGetMonitorTempList(params) {
        let obj = {};
        this.timeOptions.forEach(item => {
          obj[item.value] = item.label;
        });
        getMonitorTempList(params).then(res => {
          if (res && res.data) {
            if (params.itemType === 'monitorItem') {
              let otherData = res.data?.switchOther || [];
              if (this.tempContent?.switchOther) {
                this.tempContent['switchOther'].forEach(item => {
                  otherData.some(val => {
                    if (item.metricKey === val.metricKey) {
                      val['time'] = item.collectionCycle.toString();
                      val['timeLabel'] = obj[item.collectionCycle.toString()];
                      item['timeLabel'] = obj[item.collectionCycle.toString()];
                      return true;
                    }
                  })
                });
              }
              this.firstData[0].checkList = this.paramsData && this.paramsData.readonly ? this.tempContent['switchOther'] : otherData;
            }
            if (params.itemType === 'autodiscoverItem') {
              if (this.tempContent?.switchNet && this.tempContent?.switchNet.length > 0) {
                this.secondData['switchNet'].time = this.tempContent.switchNet[0].collectionCycle.toString();
                this.secondData['switchNet'].timeLabel = obj[this.tempContent.switchNet[0].collectionCycle.toString()];
                this.tempContent['switchNet'].timeLabel = obj[this.tempContent.switchNet[0].collectionCycle.toString()];
              }
              this.secondData['switchNet'].checkList = this.paramsData && this.paramsData.readonly ? this.tempContent?.switchNet : res.data?.switchNet || [];

              if (this.tempContent?.switchModule && this.tempContent?.switchModule.length > 0) {
                this.secondData['switchModule'].time = this.tempContent.switchModule[0].collectionCycle.toString();
                this.secondData['switchModule'].timeLabel = obj[this.tempContent.switchModule[0].collectionCycle.toString()];
              }
              this.secondData['switchModule'].checkList = this.paramsData && this.paramsData.readonly ? this.tempContent?.switchModule : res.data?.switchModule || [];

              if (this.tempContent?.switchMpu && this.tempContent?.switchMpu.length > 0) {
                this.secondData['switchMpu'].time = this.tempContent.switchMpu[0].collectionCycle.toString();
                this.secondData['switchMpu'].timeLabel = obj[this.tempContent.switchMpu[0].collectionCycle.toString()];
              }
              this.secondData['switchMpu'].checkList = this.paramsData && this.paramsData.readonly ? this.tempContent?.switchMpu : res.data?.switchMpu || [];

              if (this.tempContent?.switchPwr && this.tempContent?.switchPwr.length > 0) {
                this.secondData['switchPwr'].time = this.tempContent.switchPwr[0].collectionCycle.toString();
                this.secondData['switchPwr'].timeLabel = obj[this.tempContent.switchPwr[0].collectionCycle.toString()];
              }
              this.secondData['switchPwr'].checkList = this.paramsData && this.paramsData.readonly ? this.tempContent?.switchPwr : res.data?.switchPwr || [];

              if (this.tempContent?.switchFan && this.tempContent?.switchFan.length > 0) {
                this.secondData['switchFan'].time = this.tempContent.switchFan[0].collectionCycle.toString();
                this.secondData['switchFan'].timeLabel = obj[this.tempContent.switchFan[0].collectionCycle.toString()];
              }
              this.secondData['switchFan'].checkList = this.paramsData && this.paramsData.readonly ? this.tempContent?.switchFan : res.data?.switchFan || [];
            }
          }
        })
      },
      // 同步所有city的time为firstChangeTime的值
      handleChangeTime() {
        // 遍历firstData中的每一项
        this.firstData.forEach(item => {
          // 遍历当前项的checkList中的每个city
          item.checkList.forEach(city => {
            // 直接赋值，因为city是响应式对象（假设已初始化time属性）
            city.time = this.firstChangeTime;
          });
        });
      },
      // form验证
      fnFormValid() {
        return new Promise((resolve) => {
          this.ruleFormData = {};
          const formValid = this.$refs.formRef.$refs.ruleForm;
          // 3. 操作form（如验证）
          formValid.validate((valid) => {
            if (valid) {
              formValid.model.deployDevice = formValid.model.deployDevice.join('\n');
              this.ruleFormData = formValid.model;
              resolve(true);
            } else {
              resolve(false);
            }
          });
        });
      },
      async submit() {
        if (!await this.fnFormValid()) return;
        // 监控项
        let idsList = [];
        this.firstData.forEach(item => {
          item && item.checkList.forEach(ids => {
            if (ids && ids.time) {
              idsList.push({id: ids.id, collectionCycle: ids.time});
            }
          });
        });
        // 自动发现项
        let autoIds = [];
        Object.keys(this.secondData).forEach(key => {
          if (this.secondData[key].time) {
            this.secondData[key] && this.secondData[key].checkList.forEach(ids => {
              autoIds.push({id: ids.id, collectionCycle: this.secondData[key].time});
            });
          }
        });
        // console.log('ruleFormData===',this.ruleFormData);
        // console.log('idsList===',idsList);
        // console.log('autoIds===',autoIds);

        let paramsList = idsList.concat(autoIds);
        let params = Object.assign(this.ruleFormData, {resourceType: 'switch'},{collectionAndIdList: paramsList});
        let fnType = addResourcePolicy;
        if (this.paramsData && this.paramsData.id) {
          fnType = updateResourcePolicy;
        } else {
          delete params['id'];
        }
        this.$modal.loading();
        fnType(params).then(response => {
          this.$modal.msgSuccess(response.msg);
          if (this.open) {
            this.$emit("dialogResult", {open: false});
          } else {
            this.$router.push("/resource/switchMonitorStrat");
          }
          this.$modal.closeLoading();
        }).catch(error => {
          this.$modal.closeLoading();
        });
      },
      cancel() {
        if (this.open) {
          this.$emit("dialogResult", {open: false});
        } else {
          this.$router.push("/resource/switchMonitorStrat");
        }
      },
      /** 查询列表 */
      getList() {
        // this.$modal.loading();
        listMonitorPolicy(Object.assign({}, this.queryParams, {resourceType: 'switch',priority: 1})).then(response => {
          this.tableList = response.rows;
          this.queryParams.total = response.total;
          if (this.currentDataList && this.currentDataList['id']) {
            this.$refs.tabRef.setCurrent(this.currentDataList);
          }
        }).catch(err => {
          // this.$modal.closeLoading();
        })
      },
      submitPubilc() {
        this.policyOpen = false;
        this.getFormDataList(this.currentDataList.id, 'btnGain');
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'oldPolicy':
              this.policyOpen = true;
              this.$nextTick(() => {
                this.getList();
              });
              break;
            case 'currentData':
              this.currentDataList = dataVal;
              break;
            case 'cancel':
              break;
            default:

          }
        }
      },
    }
  }
</script>

<style scoped>
  ::v-deep #selDisabled{
    color: #303133!important;
  }
  ::v-deep .el-collapse-item__header {
    background-color: #d4e3fc!important;
    /*color: #fff!important;*/
    padding-left: 20px;
    font-size: 1rem;
  }
  ::v-deep .el-dialog__body {
    padding: 10px 20px!important;
  }
</style>
