<template>
  <el-table
    id="syslogTable"
    v-addId.table="'syslogServerTable'"
    :data="props.data"
    :row-key="(row: any) => row.num"
  >
    <el-table-column type="expand" width="32px">
      <template #default="scope">
        <div class="expandTable">
          <el-table
            id="syslogSubTable"
            v-addId.table="'syslogServerTable'"
            :data="scope.row.logItem"
          >
            <!-- 日志类型 -->

            <el-table-column :label="traduction('ALARM_REPORT_LOG_TYPE')" class="log-type">
              <template #default="scope">
                <div>
                  <span :id="'LogType' + scope.$index">{{ $t(setType(scope.row.LogType)) }}</span>
                </div>
              </template>
            </el-table-column>
            <!-- 端口 -->

            <el-table-column :label="traduction('SERVICE_PORT')" class="port-column">
              <template #default="scope">
                <div v-show="!scope.row.isEdit">
                  <span :id="'port' + scope.$index">{{ scope.row.port }}</span>
                </div>
                <div v-show="scope.row.isEdit">
                  <el-form
                    :ref="setPortFormRef"
                    class="syslog-form"
                    :class="{ 'has-error': scope.row.disabled }"
                    :model="scope.row"
                    :rules="formRules"
                    @validate="validateAction(scope.row).action"
                  >
                    <el-form-item prop="port">
                      <el-popover
                        v-model:visible="popoverVisible.port[scope.row.num][scope.row.LogType]"
                        popper-class="no-wrap-popover"
                        placement="top"
                        :teleported="true"
                        :content="scope.row.validationPort.tip"
                        trigger="focus"
                        trigger-keys
                      >
                        <template #reference>
                          <el-input
                            v-model="scope.row.port"
                            v-addId.input="'portSection' + scope.num"
                            v-clearable
                            clearable
                            class="portSection"
                            @focus="innerFocus('port', scope.row)"
                            @blur="innerBlur('port', scope.row)"
                            @clear="clear('port', scope.row)"
                            @input="change('port', $event, scope.row)"
                          >
                            <template #suffix>
                              <ErrorIcon />
                              <ClearableIcon />
                            </template>
                          </el-input>
                        </template>
                      </el-popover>
                    </el-form-item>
                  </el-form>
                </div>
              </template>
            </el-table-column>
            <!-- 传输协议 -->
            <el-table-column
              :label="traduction('ALARM_REPORT_SYSLOG_PROTOCOL')"
              class="status-column"
            >
              <template #default="scope">
                <div v-if="scope.row.isEdit">
                  <el-radio-group v-model="scope.row.TransmissionProtocol">
                    <el-radio
                      v-for="item in protocolList"
                      :id="'syslog' + item.id"
                      :key="item.id"
                      :label="item.key"
                    ></el-radio>
                  </el-radio-group>
                </div>
                <span v-else>
                  {{ scope.row.TransmissionProtocol }}
                </span>
              </template>
            </el-table-column>
            <!-- 当前状态 -->
            <el-table-column
              :label="traduction('ALARM_REPORT_CURRENT_STATUS')"
              class="status-column"
            >
              <template #default="scope">
                <div v-if="scope.row.isEdit">
                  <el-switch id="Enabled" v-model="scope.row.Enabled"></el-switch>
                </div>
                <span
                  v-if="!scope.row.isEdit"
                  :class="{
                    statusTrue: scope.row.Enabled,
                    statusFalse: !scope.row.Enabled
                  }"
                >
                  <span v-if="scope.row.Enabled" :id="'currentEnabled' + scope.$index">
                    {{ $t('ENABLED') }}
                  </span>
                  <span v-if="!scope.row.Enabled" :id="'currentDisabled' + scope.$index">
                    {{ $t('DISABLED') }}
                  </span>
                </span>
              </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column
              :label="traduction('COMMON_OPERATE')"
              class="operate-column"
              width="210"
            >
              <template #default="scope">
                <div v-if="!scope.row.isEdit">
                  <a
                    :id="`test${scope.row.num}`"
                    :class="{ 'not-allow': !props.hasPermission }"
                    class="operate test"
                    @click="test(scope.row)"
                  >
                    {{ $t('ALARM_REPORT_TEST') }}
                  </a>
                </div>
                <div v-else>
                  <a :id="`test${scope.row.num}`" class="operate test not-allow">
                    {{ $t('ALARM_REPORT_TEST') }}
                  </a>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </el-table-column>
    <!-- 序号 -->
    <el-table-column :label="traduction('EVENT_ORDER')" type="index" width="150" />
    <!-- 服务器地址 -->
    <el-table-column
      :label="traduction('ALARM_REPORT_SERVICE_ADDR')"
      prop="serviceAddr"
      class="service-addr-column"
    >
      <template #default="scope">
        <div v-show="!scope.row.isEdit">
          <span :id="'serviceAddr' + scope.$index">{{ scope.row.serviceAddr }}</span>
        </div>
        <div v-show="scope.row.isEdit">
          <el-form
            :ref="setAddrFormRef"
            class="syslog-form"
            :class="{ 'has-error': scope.row.disabled }"
            :model="scope.row"
            :rules="formRules"
            @validate="validateAction(scope.row).action"
          >
            <el-form-item prop="serviceAddr">
              <el-popover
                v-model:visible="popoverVisible.serviceAddr[scope.row.num]"
                popper-class="no-wrap-popover"
                placement="top"
                :teleported="true"
                :content="scope.row.validationAddr.tip"
                trigger="focus"
                trigger-keys
              >
                <template #reference>
                  <el-input
                    v-model="scope.row.serviceAddr"
                    v-addId.input="'addrSection'"
                    v-clearable
                    clearable
                    class="serviceAddr"
                    @focus="focus('serviceAddr', scope.row)"
                    @blur="blur('serviceAddr', scope.row)"
                    @clear="clear('serviceAddr', scope.row)"
                    @input="change('serviceAddr', $event, scope.row)"
                  >
                    <template #suffix>
                      <ErrorIcon />
                      <ClearableIcon />
                    </template>
                  </el-input>
                </template>
              </el-popover>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </el-table-column>
    <!-- 操作 -->
    <el-table-column :label="traduction('COMMON_OPERATE')" class="operate-column" width="210">
      <template #default="scope">
        <div v-if="!scope.row.isEdit">
          <a
            :id="`edit${scope.row.num}`"
            :class="{ 'not-allow': !props.hasPermission || props.isSystemLock }"
            class="operate edit"
            @click="edit(scope.row)"
          >
            {{ $t('COMMON_EDIT') }}
          </a>
        </div>
        <div v-if="scope.row.isEdit">
          <a
            :id="`save${scope.row.num}`"
            class="operate save"
            :disabled="scope.row.disabled"
            @click="save(scope.row)"
          >
            {{ $t('COMMON_SAVE') }}
          </a>
          <a :id="`cancel${scope.row.num}`" class="operate cancel" @click="cancel(scope.row)">
            {{ $t('COMMON_CANCEL') }}
          </a>
        </div>
      </template>
    </el-table-column>
    <template #empty>
      <TableNoData />
    </template>
  </el-table>
</template>

<script lang="ts" setup>
import TableNoData from '@/components/TableNoData/TableNoData.vue';
import { traduction } from '@/utils/language';
import { DomainValidators } from '@/validators/domain-validators';
import { rangeVerification } from '@/validators/validation-functions';
import { ElForm } from 'element-plus';
import { nextTick, onMounted, reactive, ref, watch } from 'vue';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';
const props = defineProps({
  data: {
    required: true,
    type: Object,
    default: () => {
      return {};
    },
  },
  isSystemLock: {
    required: true,
    type: Boolean,
  },
  hasPermission: {
    required: true,
    type: Boolean,
  },
});
const emits = defineEmits(['operateChange']);
const popoverVisible = reactive({
  serviceAddr: {},
  port: [],
});
const formRefObjs: any = reactive({});
const formRefObjsPort: any = reactive([]);
const protocolList = reactive([
  {
    id: 'TCP',
    key: 'TCP',
  },
  {
    id: 'UDP',
    key: 'UDP',
  },
]);
// 点击编辑的数据行序号
let editIndex: number = -1;
function edit(row: any) {
  if (!props.hasPermission || props.isSystemLock) {
    return;
  }
  editIndex = row.num;
  const params = {
    key: 'edit',
    value: row,
  };
  emits('operateChange', params);
}
function cancel(row: any) {
  const params = {
    key: 'cancel',
    value: row,
  };
  emits('operateChange', params);
}

function setType(type: string) {
  switch (type) {
    case 'OperationLog': {
      return 'AUDIT_LOG';
    }
    case 'SELLog': {
      return 'SEL';
    }
    case 'SYSLog': {
      return 'SYSLOG';
    }
    case 'SOLLog': {
      return 'SOL';
    }
    default: {
      return '';
    }
  }
}
function save(row: any) {
  let result = true;
  if (row?.logItem && row?.logItem.length > 0) {
    row.logItem.forEach((item: any) => {
      if (item.disabled || item.port === null || item.port === '') {
        result = false;
      }
    });
  }
  
  if (row.disabled || !result) {
    return;
  }
  const params = {
    key: 'save',
    value: row,
  };
  emits('operateChange', params);
}
function test(row: any) {
  if (!props.hasPermission) {
    return;
  }
  const params = {
    key: 'test',
    value: row,
  };
  emits('operateChange', params);
}
const formRules: any = {
  serviceAddr: DomainValidators.ipv46AndDomin(),
  port: {
    trigger: 'change',
    required: true,
    type: 'number',
    isInteger: true,
    min: 1,
    max: 65535,
    message: traduction('VALIDTOR_RANGE'),
    validator: rangeVerification,
  },
};
// 表单校验结果
const validateResult = {};
function change(key: string, value: string, row: any) {
  validateResult[key] = formRules[key].validator(formRules[key], value, () => {});
}
// 表单校验发生时 - 控制保存按钮状态 state:校验结果
function validateAction(row: any) {
  const action = (key: any, value: boolean) => {
    validateResult[key] = value;
    nextTick(() => {
      let allStae: boolean[] = [];
      for (let item in validateResult) {
        if ({}.hasOwnProperty.call(validateResult, item)) {
          allStae.push(validateResult[item]);
        }
      }
      row.disabled = allStae.some(item => item === false);
    });
  };
  return { action };
}
function focus(key: string, row: any) {
  popoverVisible[key][row.num] = true;
}

function innerFocus(key: string, row: any) {
  popoverVisible[key][row.num][row.LogType] = true;
}

function blur(key: string, row: any) {
  popoverVisible[key][row.num] = false;
}

function innerBlur(key: string, row: any) {
  popoverVisible[key][row.num][row.LogType] = true;
}

function clear(key: string, row: any) {
  // 如果没有focus，那么这个地方需要手动调用一次校验
  if (popoverVisible[key] !== row.num) {
    if (key === 'port') {
      formRefObjs[row.num]['port'].validateField(key);
    } else {
      formRefObjs[row.num]['addr'].validateField(key);
    }
  }
}
function setAddrFormRef(el: any) {
  if (!formRefObjs[editIndex]) {
    formRefObjs[editIndex] = {};
  }
  formRefObjs[editIndex]['addr'] = el;
}
function setPortFormRef(el: any) {
  if (!formRefObjsPort[editIndex]) {
    formRefObjsPort[editIndex] = {};
  }
  formRefObjsPort[editIndex]['port'] = el;
}
watch(
  () => props.data,
  val => {
    val.map((item: any) => {
      item.logItem.map((i: any) => {
        (popoverVisible.port[item.num] as any) = {};
        (popoverVisible.port[item.num][i.LogType] as boolean) = false;
      });
      popoverVisible.serviceAddr[item.num] = false;
    });
  },
  { deep: true, immediate: true },
);
</script>

<style lang="scss" scoped>
.expandTable {
  padding-left: 32px;
}
.operate {
  cursor: pointer;
  color: var(--o-color-primary);
  &.not-allow {
    color: #b8becc !important;
    cursor: not-allowed !important;
  }
  &:hover {
    color: var(--o-color-primary-secondary);
  }
}
.portSection {
  width: 120px;
}
.edit {
  margin-right: 8px;
}
.save {
  margin-right: 8px;
}
.statusFalse {
  & > span {
    font-size: 12px;
    color: #ffffff;
    display: inline-block;
    background: var(--o-text-color-tertiary);
    border-radius: var(--i-button-border-radius);
    padding: 0 14px;
  }
}
.statusTrue {
  & > span {
    font-size: 12px;
    color: #ffffff;
    display: inline-block;
    background: var(--o-color-success);
    border-radius: 2px;
    padding: 0 14px;
  }
}
.log-type-item {
  margin-right: 18px;
}
.syslog-form {
  &.has-error {
    .el-form-item {
      margin-bottom: var(--o-form-item-gap);
    }
  }
  .el-form-item {
    margin-bottom: 0;
  }
}
.serviceAddr {
  max-width: 323px;
}
</style>
<style>
#syslogTable .el-table__cell {
  vertical-align: baseline;
  &.el-table__expand-column {
    .cell {
      position: relative;
      top: 3px;
    }
  }
}
</style>
