<template>
  <div :class="open && open.length > 0 ? '' : '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="activeTwoName">
              <el-collapse-item v-for="(item,key,index) of firstData" :title="item.title" :name="index">
                <template v-if="key === 'cpu'">
                  <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="w50 mt10 mb10 disInlineBlock fontSize15">
                      <span style="width: 250px" class="disInlineBlock">{{city.metricKey}}</span>
                      <span>{{city.metricName}}</span>
                    </div>
                  </div>
                </template>
                <template v-else>
                  <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.groupTime" id="selDisabled" clearable placeholder="请选择" @change="handleChangeTime(item)">
                      <el-option v-for="val in timeOptions" :key="val.value" :label="val.label" :value="val.value"></el-option>
                    </el-select>
                    </div>
                  </template>
                  <div>
                    <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>
                </template>
              </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 === 'net' ? 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,key,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>{{item.title}}</span>
              </template>
              <div v-if="key === 'cpu'" class="plr-50">
                <div class="plr-50">
                 <div>当前所有子项的采集周期均为{{item.timeLabel}}</div>
                  <div v-for="city of item.checkList" class="w50 mt10 mb10 disInlineBlock fontSize15">
                    <span style="width: 250px" class="disInlineBlock">{{city.metricKey}}</span>
                    <span>{{city.metricName}}</span>
                  </div>
                </div>
              </div>
              <div v-else>
                <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">
                      采集周期为{{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>自动发现项>>{{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" class="disInlineBlock">{{city.metricKey}}</span>
                  <span>{{city.metricName}}</span>
                </div>
              </div>
            </el-collapse-item>
          </template>
        </el-collapse>
      </template>
    </div>
    <div style="height: 55px;margin-right: 20px;">
      <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>
    </div>
  </div>
</template>

<script>
  import Form from '@/components/form/index.vue';
  import {addResourcePolicy, updateResourcePolicy,getMonitorTempList, getMonitorPolicy, getRegistList} from "@/api/disRevenue/resource"
  export default {
    name: "LinuxMonitorStratEdit",
    components: {Form},
    dicts: ['collection_cycle', 'policy_status'],
    props: {
      open: {
        type: String,
        default: ''
      },
      dialogRowData: {
        type: Object,
        default: () => {}
      }
    },
    watch: {
      open: {
        handler(val) {
          if (val === 'type_true') {
            this.paramsData = {};
            this.$set(this.ruleFormData, 'deployDevice', this.dialogRowData.clientId);
            this.$set(this.ruleFormData, 'policyName', Date.now()
            );
          } else if (val === 'type_false') {
            // 清空form
            this.$refs['formRef'].$refs.ruleForm.resetFields();
          }
        },
        deep: true,
        immediate: true
      },
    },
    data() {
      return {
        activeName: 'first',
        firstChangeTime: '',
        activeTwoName: [0,1,2,3,4,5],
        timeOptions: [],
        ruleFormData: {
          policyName: Date.now(),
        },
        formList: [],
        clientIdList: {},
        firstData: {
          cpu: {title: 'CPU监控', time: '',
            checkList: []
          },
          other: {title: '其他监控', groupTime: '',
            checkList: []
          },
        },
        tempContent: {},
        paramsData: {},
        secondData: {
          vfs: {title: '发现挂载文件系统', time: '',
            checkList: []
          },
          net: {title: '发现网络接口', time: '300',
            checkList: []
          },
          disk: {title: '发现硬盘设备', time: '',
            checkList: []
          },
          docker: {title: '发现docker', time: '',
            checkList: []
          },
        }
      }
    },
    created() {
      this.timeOptions = this.dict.type.collection_cycle;
      this.paramsData = this.$route && this.$route.query;
      if (this.open) {
        this.paramsData = {};
        this.$set(this.ruleFormData, 'deployDevice', this.dialogRowData.clientId);
      }
      if (this.paramsData && this.paramsData.id) {
        this.getFormDataList(this.paramsData.id);
      } else {
        this.getDataList();
      }
      this.fnFormList();
      this.getClientIDList();
    },
    methods: {
      // formList集合
      fnFormList(objVal) {
        if (this.open) {
          this.formList = [{
            config: {},
            controls: {
              id: {label: 'ID',hidden: true},
              policyName: {label: '策略名称', span: 18, type: 'input', required: true},
              description: {label: '描述', span: 18, type: 'textarea'},
              deployDevice: {label: '部署设备', span: 18, type: 'textarea', rows: 2, 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', required: true},
              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: 'datetime', hidden: this.paramsData && this.paramsData.readonly ? false : true},
              createTime: {label: '创建时间', span: 12, type: 'datetime', hidden: this.paramsData && this.paramsData.readonly ? false : true},
              createBy: {label: '创建人', span: 12, type: 'input',hidden: this.paramsData && this.paramsData.readonly ? false : true},
              deployDevice: {label: '部署设备', span: 12, type: 'textarea', rows:15, required: true},
              description: {label: '描述', span: 12, type: 'textarea'},
            }
          }];
        }
      },
      // 获取详情
      getFormDataList(id) {
        this.tempContent = {};
        getMonitorPolicy(id).then(val => {
          if (val && val.data) {
            if (val.data && val.data.policy){
              if (this.paramsData && this.paramsData.readonly) {
                val.data.policy.deployDevice = val.data.policy.deployDevice.replace(/\n/g, '<br>');
              }
              this.ruleFormData = val.data.policy;
            }
            this.tempContent = val.data['linux'];
          }
          this.getDataList();
        }).catch(() => {
          this.getDataList();
          // this.$modal.msgError("操作失败")
        });
      },
      // 所有ClientID
      getClientIDList() {
        this.clientIdList = {};
        getRegistList({resourceType: 1}).then(res => {
          if (res && res.data) {
            res && res.data.map(item => {
              this.clientIdList[item.clientId] = item.clientId;
            });
          }
        });
      },
      getDataList() {
        let itemTypeList = ['monitorItem', 'autodiscoverItem'];
        itemTypeList.forEach(item => {
          let params = {resourceType: 'linux', 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') {
              // cpu
              if (this.tempContent?.cpu && this.tempContent?.cpu.length > 0) {
                this.firstData['cpu'].time = this.tempContent.cpu[0].collectionCycle.toString();
                this.firstData['cpu'].timeLabel = obj[this.tempContent.cpu[0].collectionCycle.toString()];
                this.tempContent['cpu'].timeLabel = obj[this.tempContent.cpu[0].collectionCycle.toString()];
              }
              this.firstData['cpu'].checkList = this.paramsData && this.paramsData.readonly ? this.tempContent?.cpu : res.data?.cpu || [];
              // other
              let otherData = res.data?.other || [];
              if (this.tempContent?.other) {
                this.tempContent['other'].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['other'].checkList = this.paramsData && this.paramsData.readonly ? this.tempContent['other'] : otherData;
              // 假设从接口获取firstData后，初始化每个city的time属性
              this.firstData['other'].checkList.forEach(city => {
                // 显式初始化time（若原本没有），确保响应式
                if (city.time === undefined) {
                  this.$set(city, 'time', ''); // 用$set添加响应式属性
                }
              });
            }
            if (params.itemType === 'autodiscoverItem') {
              if (this.tempContent?.vfs && this.tempContent?.vfs.length > 0) {
                this.secondData['vfs'].time = this.tempContent.vfs[0].collectionCycle.toString();
                this.secondData['vfs'].timeLabel = obj[this.tempContent.vfs[0].collectionCycle.toString()];
                this.tempContent['vfs'].timeLabel = obj[this.tempContent.vfs[0].collectionCycle.toString()];
              }
              this.secondData['vfs'].checkList = this.paramsData && this.paramsData.readonly ? this.tempContent?.vfs : res.data?.vfs || [];

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

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

              if (this.tempContent?.docker && this.tempContent?.docker.length > 0) {
                this.secondData['docker'].time = this.tempContent.docker[0].collectionCycle.toString();
                this.secondData['docker'].timeLabel = obj[this.tempContent.docker[0].collectionCycle.toString()];
              }
              this.secondData['docker'].checkList = this.paramsData && this.paramsData.readonly ? this.tempContent?.docker : res.data?.docker || [];
            }
          }
        })
      },
      // 同步所有city的time为firstChangeTime的值
      handleChangeTime(item) {
        // 遍历firstData中的每一项
        item.checkList.forEach(city => {
          // 遍历当前项的checkList中的每个city 直接赋值，因为city是响应式对象
          city.time = item.groupTime;
        });
      },
      // 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);
            }
          });
        });
      },
      async submit() {
        if (!await this.fnFormValid()) return;
        let unknownData = [];
        if (this.ruleFormData && this.ruleFormData.deployDevice) {
          let deployList = JSON.parse(JSON.stringify(this.ruleFormData.deployDevice.trim())).split('\n');
          deployList.forEach(item => {
            if (!this.clientIdList[item]) {
              unknownData.push(item);
            }
          });
        }
        if (unknownData && unknownData.length > 0) {
          this.$modal.msgWarning(`存在未知的ClientID: ${unknownData.join('; ')}`);
          return;
        }
        // 监控项
        let idsList = [];
        Object.keys(this.firstData).forEach(key => {
          if (key === 'other') {
            this.firstData[key] && this.firstData[key].checkList.forEach(ids => {
              if (ids && ids.time) {
                idsList.push({id: ids.id, collectionCycle: ids.time});
              }
            });
          } else {
            if (this.firstData[key].time) {
              this.firstData[key] && this.firstData[key].checkList.forEach(ids => {
                idsList.push({id: ids.id, collectionCycle: this.firstData[key].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: 'linux'},{collectionAndIdList: paramsList});
        let fnType = addResourcePolicy;
        if (this.paramsData && this.paramsData.id) {
          fnType = updateResourcePolicy;
        }
        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/serverMonitorStrat");
          }
          this.$modal.closeLoading();
        }).catch(error => {
          this.$modal.closeLoading();
        });
      },
      cancel() {
        if (this.open) {
          this.$emit("dialogResult", {open: false});
        } else {
          this.$router.push("/resource/serverMonitorStrat");
        }
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'submit':
              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;
  }
</style>
