<template>
  <div class="app-container">
    <el-button type="primary" style="position: absolute;right: 100px;z-index: 9999;top: 45px;" @click="formSubmit()">{{readonly ? '编辑' : '保存'}}</el-button>
    <el-button v-if="!readonly" style="position: absolute;right: 20px;z-index: 9999;top: 45px;" @click="formSubmit('-1')">取消</el-button>
    <Form ref="formRef" :key="formKey" :formList="formList" :ruleFormData="ruleForm" :config="{labelWidth: '140px', buttonGroup: []}" @fnClick="callback">
      <template #tempTimeList="{field, model, formModel }">
        <el-tag
          :key="tagIndex"
          v-for="(tag,tagIndex) in formModel[field.key]"
          :closable="readonly ? false : ruleForm.frequency === '1'"
          :disable-transitions="false"
          @close="handleClose(field.key, tagIndex)">
          {{tag}}
        </el-tag>
        <template v-if="readonly ? false : ruleForm.frequency === '1'">
          <el-time-picker
            style="width: 120px!important;"
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            :format="'HH:mm:ss'"
            @blur="handleInputConfirm(field.key)">
          </el-time-picker>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
        </template>
      </template>
    </Form>
    <div>
      <div class="mb20" style="border: 1px solid #eee;padding: 10px;">
        <span>出省流量统计</span>
        <div style="max-height: calc(100vh - 445px);overflow: auto;">
          <template v-if="timelineList && timelineList.length > 0">
            <div v-for="item of timelineList" class="ml20">
              <pre>{{item.description}}</pre>
            </div>
          </template>
          <div v-else class="ml20 mt20" style="height: 100px;color: #a3a3a3;">
            暂无数据
          </div>
        </div>
<!--        <div>-->
<!--          <TableList ref="tabRef" :columns="columns" :config="config" :queryParams="queryParams" :tableList="roleList" @fnRenderList="getList" @fnClick="callback"></TableList>-->
<!--        </div>-->
      </div>
    </div>
    <div style="text-align: right;" class="mr20">
      <el-button @click="callback({fnCode: 'cancel'})">返回</el-button>
    </div>
  </div>
</template>

<script>
  import Form from '@/components/form/index.vue';
  import TableList from '@/components/table/index.vue';
  import {getRmTcpdumpConfig, rmOutTrafficFlow, updateRmTcpdum} from "@/api/disRevenue/resource";
  export default {
    name: "flowForm",
    dicts: ['pppoe_enabled', 'frequency'],
    components: {Form, TableList},
    data() {
      return {
        formList: [],
        readonly: true,
        paramsData: {},
        ruleForm: {
          detectTimes: []
        },
        formModelData: {
          detectTimes: []
        },
        inputVisible: false,
        inputValue: '',
        formKey: 1,
        timelineList: [],
        roleList: [],
        // 列显隐信息
        columns: {
          id: {label: `ID`, width: '50'},
          clientId: {label: `clientID`, minWidth: '280'},
          name: {label: `磁盘名称`, minWidth: '60', visible: true},
          serial: {label: `序列号`, minWidth: '120', visible: true},
          total: {label: `总大小(GB)`, minWidth: '100',visible: true},
          type: {label: `类型`, minWidth: '60',visible: true},
          usedSpace: {label: `已用空间(GB)`, minWidth: '100',visible: true},
          readSpeed: {label: `读速率(KB/s)`, minWidth: '90',visible: true},
          writeSpeed: {label: `写速率(KB/s)`, minWidth: '90',visible: true},
          readIops: {label: `读IOPS`, minWidth: '60',visible: true},
          writeIops: {label: `写IOPS`, minWidth: '60',visible: true},
          status: {label: `状态`, minWidth: '50', slotName: 'tempDiskStatus', visible: true},
          omountFlag: {label: `执行卸载`, minWidth: '60', slotName: 'tempOmountFlag', visible: true},
        },
        config: {
          colHiddenCheck: true, colTopHiddenIcon: true,
          tableButton: {
            line: [
              {content: '测试磁盘IOOS', fnCode: 'testIoos', type: 'primary', showName: 'status', showVal: '1'},
              {content: '卸载', fnCode: 'uninstall', type: 'danger', showName: 'status', showVal: '0'},
              {content: '删除记录', fnCode: 'delete', type: 'danger', showName: 'status', showVal: '0'},
            ]
          }
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          total: 0
        },
      }
    },
    created() {
      this.paramsData = this.$route && this.$route.query;
      this.ruleForm['clientId'] = this.paramsData.clientId;
      this.fnFormList(this.readonly);
      this.fnRmOutTrafficFlow();
      this.fnRmTcpdumpConfig();
    },
    methods: {
      // 删除指定tag
      handleClose(tagKey, targetIndex) {
        this.ruleForm[tagKey].splice(targetIndex, 1);
      },
      // 点击添加tag
      showInput() {
        this.inputVisible = true;
        // this.$nextTick(_ => {
        //   this.$refs.saveTagInput.$refs.input.focus();
        // });
      },
      // 添加指定tag值
      handleInputConfirm(tagKey) {
        let inputValue = new Date(this.inputValue).toLocaleTimeString();
        if (inputValue) {
          // 1. 获取表单引用
          const formRef = this.$refs.formRef;
          // 2. 先清除所有表单校验
          if (formRef && formRef.$refs.ruleForm) {
            formRef.$refs.ruleForm.clearValidate(); // 清除校验提示
          }
          this.ruleForm[tagKey].push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      // 详情
      fnRmTcpdumpConfig() {
        getRmTcpdumpConfig(this.paramsData.clientId).then(res => {
          if (res && res.data) {
            res.data.detectFlag = res.data && (res.data.detectFlag || res.data.detectFlag === 0) ? res.data.detectFlag.toString() : res.data.detectFlag;
            res.data.detectTimes = res.data && res.data.detectTimes ? res.data.detectTimes.split(',') : [];
            res.data.frequency = res.data && (res.data.frequency || res.data.frequency === 0) ? res.data.frequency.toString() : res.data.frequency;
            this.formModelData = JSON.parse(JSON.stringify(res.data));
            this.ruleForm = JSON.parse(JSON.stringify(res.data));
          }
        });
      },
      // 出省流量统计
      fnRmOutTrafficFlow() {
        rmOutTrafficFlow({clientId: this.paramsData.clientId}).then(res => {
          if (res && res.data) {
            this.timelineList = res.data;
          }
        });
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        // listGroup(this.queryParams).then(response => {
        //   this.roleList = response.rows;
        //   this.queryParams.total = response.total;
        // })
      },
      // formList集合
      fnFormList(readonly) {
        this.formList = [{
          config: {title: 'tcpdump探测策略', labelWidth: '140px', colSpan: 'disBlock', readonly: readonly},
          controls: {
            id: {label: 'ID', hidden: true},
            clientId: {label: 'clientId', hidden: true},
            detectFlag: {label: '开启探测', span: 12, type: 'radio', options: this.dict.type.pppoe_enabled, required: true},
            frequency: {label: '频率', span: 12, type: 'select', options: this.dict.type.frequency, eventName: 'change'},
            detectTimes: {label: '时间', span: 24, slotName: 'tempTimeList', required: true, required: this.ruleForm.frequency === '1'},
          }
        }];
        this.formKey += 1;
      },
      formSubmit(num) {
        if (num === '-1') {
          // 1. 获取表单引用
          const formRef = this.$refs.formRef;
          // 2. 先清除所有表单校验
          if (formRef && formRef.$refs.ruleForm) {
            formRef.$refs.ruleForm.clearValidate(); // 清除校验提示
          }
          this.ruleForm = JSON.parse(JSON.stringify(this.formModelData));
          this.$nextTick(() => {
            this.readonly = true;
            this.fnFormList(this.readonly);
          });
        } else {
          if (!this.readonly) {
            this.formSumbit();
          } else {
            this.readonly = !this.readonly;
            this.fnFormList(this.readonly);
          }
        }
      },
      // 提交表单信息
      async formSumbit() {
        if (!await this.fnFormValid()) return;
        let params = JSON.parse(JSON.stringify(this.ruleForm));
        params['detectTimes'] = params['detectTimes'].toString();
        updateRmTcpdum(params).then(res => {
          this.$modal.msgSuccess("操作成功");
          this.fnRmTcpdumpConfig();
          this.readonly = true;
          this.fnFormList(this.readonly);
        });
      },
      // form验证
      fnFormValid() {
        return new Promise((resolve) => {
          this.ruleForm = {};
          const formValid = this.$refs.formRef.$refs.ruleForm;
          // 3. 操作form（如验证）
          formValid.validate((valid) => {
            if (valid) {
              this.ruleForm = formValid.model;
              resolve(true);
            } else {
              resolve(false);
            }
          });
        });
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'frequency':
              this.ruleForm = Object.assign(this.ruleForm, this.$refs.formRef.$refs.ruleForm.model, {detectTimes: this.formModelData['detectTimes']});
              if (dataVal === '1') {
                this.formList[0].controls.detectTimes['required'] = true;
              } else if (dataVal === '2') {
                this.formList[0].controls.detectTimes['required'] = false;
              }
              break;
            case 'submit':
              break;
            case 'cancel':
              this.$router.push({
                path:'/resource/serverRegister/details',
                query: {id: this.paramsData.id, readonly: true, clientId: this.paramsData.clientId}
              });
              break;
            default:
          }
        }
      },
    }
  }
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  ::v-deep .el-timeline .el-timeline-item:last-child .el-timeline-item__tail {
    display: block!important;
  }
</style>
