<template>
  <div :class="open && open.length > 0 ? '' : 'app-container'">
    <Form ref="formRef" :formList="formList" :ruleFormData="ruleForm" :config="config" @fnClick="callback"></Form>
    <el-dialog title="并发限制警告" :visible.sync="errorMsgOpen" width="550px" append-to-body style="padding-bottom: 20px;">
      <div style="line-height: 22px;color: #444;height: calc(100vh - 190px);overflow: auto;" v-html="errorMsg"></div>
      <div style="text-align: right;margin-right: 20px;margin-top: 10px;">
        <el-button type="primary" @click="errorMsgOpen = false">去修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Handle">
  import Form from '@/components/form/index.vue';
  import {addMtrPolicy, updateMtrPolicy, getMtrPolicyt, allMtrClientIdData, networkInterList, getRegistList} from "@/api/disRevenue/resource"
  export default {
    name: 'mtrProbe_view',
    components: {Form},
    dicts: ['policy_method', 'rm_register_online_state', 'agent_update_result', 'rm_register_status', 'rm_register_snmp_detect'],
    props: {
      open: {
        type: String,
        default: ''
      },
      dialogRowData: {
        type: Object,
        default: () => {}
      }
    },
    watch: {
      open: {
        handler(val) {
          if (val === 'type_true') {
            this.paramsData = {};
            this.$set(this.ruleForm, 'mtrClientId', this.dialogRowData && this.dialogRowData.mtrClientId || '');
            this.$set(this.ruleForm, 'policyName', Date.now());
            this.$set(this.ruleForm, 'probeFrequency', '300');
            this.$set(this.ruleForm, 'clientAllId', false);
            if (this.formList && this.formList.length > 0) {
              this.formList[0].controls.serveripGroup['hidden'] = true;
              this.formList[0].controls.clientAllId['label'] = '显示相关IP';
            }
          } else if (val === 'type_false') {
            // 清空form
            this.$refs['formRef'].$refs.ruleForm.resetFields();
          }
        },
        deep: true,
        immediate: true
      },
    },
    data() {
      return {
        loading: false,
        ruleForm: {probeFlag: '1', policyName: Date.now(), probeFrequency: '300'},
        formList: [],
        paramsData: {},
        config: {},
        includeList: {},
        errorMsgOpen: false,
        errorMsg: '',
        routeType: '',
        clientIdList: {},
      }
    },
    created() {
      this.paramsData = this.$route && this.$route.query;
      if (this.open) {
        this.paramsData = {};
        if (this.dialogRowData && this.dialogRowData.mtrClientId) {
          this.$set(this.ruleForm, 'mtrClientId', this.dialogRowData && this.dialogRowData.mtrClientId || '');
          this.$set(this.ruleForm, 'clientAllId', false);
        }
      }
      // mtrAgent页面跳转过来的值
      if (this.paramsData && this.paramsData.routeType) {
        this.routeType = this.paramsData.routeType;
        this.$set(this.ruleForm, 'mtrClientId', this.paramsData && this.paramsData.mtrClientId || '');
        this.$set(this.ruleForm, 'clientAllId', false);
      }

      if (this.paramsData && this.paramsData.id) {
        this.getFormDataList(this.paramsData.id);
      } else {
        this.fnFormList();
        this.fnMtrClientList();
      }
      this.getClientIDList();
      if (this.paramsData && this.paramsData.readonly) {
        this.config = {
          buttonGroup: [{title: '返回', fnCode: 'goBack'}]
        };
      }
    },
    methods: {
      // formList集合
      fnFormList() {
        if (this.paramsData && this.paramsData.readonly) {
          this.formList = [{
            config: {title: ' ', colSpan: '', readonly: true},
            controls: {
              id: {label: 'ID',hidden: true},
              policyName: {label: '策略名称', span: 12, type: 'input', required: true},
              priority: {label: '优先级', span: 12, type: 'input'},
              mtrClientId: {label: 'MTRClientID', span: 12, type: 'select', options: []},
              probeFlag: {label: '是否探测', span: 12, type: 'radio', eventName: 'change',required: true, options: this.dict.type.rm_register_snmp_detect},
              startTime: {label: '开始时间', span: 12, type: 'datetime', hidden: this.ruleForm && this.ruleForm.probeFlag === '1' ? false: true},
              endTime: {label: '结束时间', span: 12, type: 'datetime', hidden: this.ruleForm && this.ruleForm.probeFlag === '1' ? false: true},
              probeFrequency: {label: '探测频率', span: 12, type: 'select', options: [{value: '300', label: '固定每5分钟'}], hidden: this.ruleForm && this.ruleForm.probeFlag === '1' ? false: true},
              updateTime: {label: '修改时间', span: 12, type: 'datetime'},
              createTime: {label: '创建时间', span: 12, type: 'datetime'},
              createBy: {label: '创建人', span: 12, type: 'input'},
              serverGroup: {label: '服务器集合', span: 12, type: 'textarea', rows:15, placeholder: '请粘贴/输入ClientID列表，如\nClientID1\nClientID2\n...', required: true},
              serveripGroup: {label: '探测目标IP集合', span: 12, type: 'textarea', rows:15},
            }
          }];
        } else {
          this.formList = [{
            config: {title: ' ', colSpan: '', readonly: this.paramsData && this.paramsData.readonly},
            controls: {
              id: {label: 'ID',hidden: true},
              policyName: {label: '策略名称', span: 18, type: 'input', required: true},
              mtrClientId: {label: 'MTRClientID', span: 18, type: 'select', required: true, options: []},
              serverGroup: {label: '服务器集合', span: 15, type: 'textarea', rows:15, placeholder: '请粘贴/输入ClientID列表，如\nClientID1\nClientID2\n...', required: true},
              clientAllId: {label: this.ruleForm && this.ruleForm.clientAllId ? '不显示相关IP' : '显示相关IP', span: 3, type: 'button', style: 'vertical-align: top'},
              serveripGroup: {label: '', span: 5, labelWidthNull: true, type: 'textarea', rows:15, placeholder: 'IP1\nIP2\nIP3\n...', hidden: this.ruleForm && this.ruleForm.serveripGroup ? false: true},
              probeFlag: {label: '是否探测', span: 18, type: 'radio', eventName: 'change',required: true, options: this.dict.type.rm_register_snmp_detect},
              startTime: {label: '开始时间', span: 18, type: 'datetime', eventName: 'change', pickerOptions: {}, hidden: this.ruleForm && this.ruleForm.probeFlag === '1' ? false: true},
              endTime: {label: '结束时间', span: 18, type: 'datetime', eventName: 'change', pickerOptions: {}, hidden: this.ruleForm && this.ruleForm.probeFlag === '1' ? false: true},
              probeFrequency: {label: '探测频率', span: 18, type: 'select', options: [{value: '300', label: '固定每5分钟'}], hidden: this.ruleForm && this.ruleForm.probeFlag === '1' ? false: true},
            }
          }];
        }
      },
      // 获取详情
      getFormDataList(id) {
        getMtrPolicyt(id).then(val => {
          if (val && val.data) {
            val.data['probeFlag'] = val.data['probeFlag'].toString();
            if (val.data && val.data['serveripGroup']) {
              val.data['clientAllId'] = true;
            }
            if (this.paramsData && this.paramsData.readonly) {
              val.data['serveripGroup'] = val.data && val.data['serveripGroup'] ? val.data['serveripGroup'].replace(/;/g, '<br>') : val.data['serveripGroup'];
              val.data['serverGroup'] = val.data && val.data['serverGroup'] ? val.data['serverGroup'].replace(/;/g, '<br>') : val.data['serverGroup'];
            } else {
              val.data['serveripGroup'] = val.data && val.data['serveripGroup'] ? val.data['serveripGroup'].replace(/;/g, '\n') : val.data['serveripGroup'];
              val.data['serverGroup'] = val.data['serverGroup'].replace(/;/g, '\n');
            }
            val.data['probeFrequency'] = val.data && val.data['probeFrequency'] ? val.data['probeFrequency'].toString() : null;
            this.ruleForm = val.data;
            this.fnFormList();
            this.fnMtrClientList();
          }
        }).catch(() => {
          // 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;
            });
          }
        });
      },
      fnMtrClientList() {
        allMtrClientIdData({}).then(res => {
          this.formList[0].controls.mtrClientId['options'] = res && res.data.map(item => {
            return Object.assign({label: item.mtrClientId, value: item.mtrClientId});
          });
        });
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'probeFlag':
              if (dataVal === '1') {
                this.formList[0].controls.startTime['hidden'] = false;
                this.formList[0].controls.endTime['hidden'] = false;
                this.formList[0].controls.probeFrequency['hidden'] = false;
              } else {
                this.formList[0].controls.startTime['hidden'] = true;
                this.formList[0].controls.endTime['hidden'] = true;
                this.formList[0].controls.probeFrequency['hidden'] = true;
              }
              break;
            case 'startTime':
              this.formList[0].controls.endTime['pickerOptions'] = {
                disabledDate: (time) => {
                  // 禁用开始时间之前的日期
                  return time.getTime() < new Date(dataVal).getTime();
                }
              };
              break;
            case 'endTime':
              this.formList[0].controls.startTime['pickerOptions'] = {
                disabledDate: (time) => {
                  // 禁用开始时间之前的日期
                  return time.getTime() > new Date(dataVal).getTime();
                }
              };
              break;
            case 'clientAllId':
              this.ruleForm = Object.assign({}, this.ruleForm, this.$refs.formRef.$refs.ruleForm.model);
              let params = JSON.parse(JSON.stringify(this.ruleForm));
              if (this.ruleForm && this.ruleForm.clientAllId) {
                this.formList[0].controls.serveripGroup['hidden'] = true;
                this.formList[0].controls.clientAllId['label'] = '显示相关IP';
                this.$set(this.ruleForm, 'clientAllId', false);
                this.$set(this.ruleForm, 'serveripGroup', '');
              } else {
                this.formList[0].controls.serveripGroup['hidden'] = false;
                this.formList[0].controls.clientAllId['label'] = '不显示相关IP';
                this.$set(this.ruleForm, 'clientAllId', true);
                this.$set(this.ruleForm, 'serveripGroup', '');
                if (params && params.serverGroup) {
                  networkInterList({clientIds: params.serverGroup.replace(/\n/g, ',')}).then(res => {
                    let str = '';
                    if (res && res.data) {
                      res && res.data.map(item => {
                        str+= item.publicIp + '\n';
                      });
                    }
                    this.$set(this.ruleForm, 'serveripGroup', str);
                  });
                }
              }
              break;
            case 'submit':
              let unknownData = [];
              if (dataVal && dataVal.serverGroup) {
                let deployList = JSON.parse(JSON.stringify(dataVal.serverGroup.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;
              }

              if (this.loading) return;
              this.loading = true;
              let fnType = addMtrPolicy;
              if (dataVal && dataVal.id) {
                fnType = updateMtrPolicy;
              }
              fnType(dataVal, {skipErrorHandling: true}).then(response => {
                this.$modal.msgSuccess(response.msg);
                this.loading = false;
                if (this.open) {
                  this.$emit("dialogResult", {open: true});
                } else if (this.routeType === 'mtrAgent') {
                  this.$router.push("/resource/mtrAgent")
                } else {
                  this.$router.push("/resource/mtrProbe")
                }
              }).catch((error) => {
                this.errorMsgOpen = true;
                this.errorMsg = error.replace(':',':<br>').replace(/,/g, '<br>');
                this.loading = false;
              });
              break;
            case 'cancel':
              if (this.open) {
                this.$emit("dialogResult", {open: false});
              } else if (this.routeType === 'mtrAgent') {
                this.$router.push("/resource/mtrAgent")
              } else {
                this.$router.push("/resource/mtrProbe")
              }
              break;
            default:
          }
        }
      }
    }
  }
</script>
<style scoped>
  ::v-deep .el-dialog__body{
    padding: 0px 20px 20px!important;
  }
</style>
