<template>
  <el-table id="emailTable" v-addId.table="'emailReceiveTable'" :data="props.data">
    <!-- 序号 -->
    <el-table-column :label="traduction('EVENT_ORDER')" type="index" width="50" />
    <!-- 邮件地址 -->
    <el-table-column :label="traduction('ALARM_REPORT_EMAIL_ADDRESS')" prop="serviceAddr">
      <template #default="scope">
        <div v-if="!scope.row.isEdit">
          <span :id="'emailAddress' + scope.$index">{{ scope.row.address }}</span>
        </div>
        <div v-if="scope.row.isEdit">
          <el-form
            :ref="setAddrFormRef"
            class="input-form"
            :class="{ 'has-error': scope.row.disabled }"
            :model="scope.row"
            :rules="rules"
            @validate="validateAction(scope.row).action"
          >
            <el-form-item prop="address">
              <el-popover
                v-model:visible="popoverVisible.address[scope.row.num]"
                popper-class="no-wrap-popover"
                placement="top"
                :teleported="true"
                :content="traduction('ALARM_REPORT_EMAIL_TIP')"
                trigger="focus"
                trigger-keys
              >
                <template #reference>
                  <el-input
                    v-model="scope.row.address"
                    v-addId.input="'address'"
                    v-clearable
                    clearable
                    maxlength="255"
                    @focus="focus('address', scope.row)"
                    @blur="blur('address', scope.row)"
                    @clear="clear('address', scope.row)"
                    @input="change('address', $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_DESCRIPTION')">
      <template #default="scope">
        <div v-if="!scope.row.isEdit">
          <span :id="'description' + scope.$index">{{ scope.row.description }}</span>
        </div>
        <div v-if="scope.row.isEdit">
          <el-form
            :ref="setDesFormRef"
            class="input-form"
            :class="{ 'has-error': scope.row.disabled }"
            :model="scope.row"
            :rules="rules"
            @validate="validateAction(scope.row).action"
          >
            <el-form-item prop="description">
              <el-popover
                v-model:visible="popoverVisible.description[scope.row.num]"
                popper-class="no-wrap-popover"
                placement="top"
                :teleported="true"
                :content="traduction('ALARM_REPORT_EMAIL_SUBJECT_TIP')"
                trigger="focus"
                trigger-keys
              >
                <template #reference>
                  <el-input
                    v-model="scope.row.description"
                    v-addId.input="'description'"
                    v-clearable
                    clearable
                    @focus="focus('description', scope.row)"
                    @blur="blur('description', scope.row)"
                    @clear="clear('description', scope.row)"
                    @input="change('description', $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_EMAIL_SEND')">
      <template #default="scope">
        <div v-if="!scope.row.isEdit">
          <span :class="{ statusTrue: scope.row.emailEnable, statusFalse: !scope.row.emailEnable }">
            <span v-if="scope.row.emailEnable" :id="'currentEnabled' + scope.$index">{{ traduction('ENABLED') }}</span>
            <span v-if="!scope.row.emailEnable" :id="'currentDisabled' + scope.$index">{{ traduction('DISABLED') }}</span>
          </span>
        </div>
        <div v-if="scope.row.isEdit">
          <el-switch id="emailEnable" v-model="scope.row.emailEnable"></el-switch>
        </div>
      </template>
    </el-table-column>
    <!-- 操作 -->
    <el-table-column :label="traduction('COMMON_OPERATE')" prop="serviceAddr">
      <template #default="scope">
        <div v-if="!scope.row.isEdit">
          <a
            :id="`edit${scope.row.num}`"
            :class="{ 'not-allow': !props.hasBaseConfig || props.isSystemLock }"
            class="operate edit"
            @click="edit(scope.row)"
          >{{ $t('COMMON_EDIT') }}</a>
          <a
            :id="`test${scope.row.num}`"
            :class="{ 'not-allow': !props.hasBaseConfig }"
            class="operate test"
            @click="test(scope.row)"
          >{{ $t('ALARM_REPORT_TEST') }}</a>
        </div>
        <div v-if="scope.row.isEdit">
          <a
            :id="`save${scope.row.num}`"
            class="operate save"
            @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 { traduction } from '@/utils/language';
import { nextTick, reactive, ref, watch } from 'vue';
import TableNoData from '@/components/TableNoData/TableNoData.vue';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';
import { DESCRIPTION } from '@/utils/regular';
const props = defineProps({
  data: {
    required: true,
    type: Object,
    default: () => {
      return {};
    },
  },
  isSystemLock: {
    required: true,
    type: Boolean,
  },
  hasBaseConfig: {
    required: true,
    type: Boolean,
  },
});
const validateResult = {};
const popoverVisible = reactive({
  address: {},
  description: {},
});
const formRefObjs: any = reactive({});
// 点击编辑的数据行序号
let editIndex: number = -1;
const emits = defineEmits(['operateChange']);
function edit(row: any) {
  if (!props.hasBaseConfig || 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 save(row: any) {
  if (JSON.stringify(validateResult).includes('false')) {
    return;
  }
  const params = {
    key: 'save',
    value: row,
  };
  emits('operateChange', params);
}
function test(row: any) {
  if (!props.hasBaseConfig) {
    return;
  }
  const params = {
    key: 'test',
    value: row,
  };
  emits('operateChange', params);
}
const rules = reactive({
  address: {
    trigger: 'change',
    type: 'text',
    message: traduction('COMMON_FORMAT_ERROR'),
    validator: (rule: any, value: any, callback: (error?: Error) => void) => {
      if (value === '') {
        callback();
        return;
      }
      let result = DESCRIPTION.test(value);
      let iAtPos = 0;
      let lastPos = 0;
      let iAtTimes = 0;
      let i = 0;
      for (const c of value) {
        if (c === '@') {
          iAtPos = i;
          iAtTimes++;
        } else if (c === '.') {
          lastPos = i;
        } else {
          
        }
        i++;
      }
      if (
        i > 255 ||
        iAtPos < 1 ||
        lastPos - 2 < iAtPos ||
        i - lastPos < 3 ||
        i - lastPos > 64 ||
        iAtTimes !== 1
      ) {
        callback(new Error(traduction('COMMON_FORMAT_ERROR')));
        return;
      }
      result ? callback() : callback(new Error(traduction('COMMON_FORMAT_ERROR')));
    },
  },
  description: {
    trigger: 'change',
    type: 'text',
    message: traduction('COMMON_FORMAT_ERROR'),
    validator: (rule: any, value: any, callback: (error?: Error) => void) => {
      if (value === '') {
        callback();
        return;
      }
      let result = DESCRIPTION.test(value);
      result ? callback() : callback(new Error(traduction('COMMON_FORMAT_ERROR')));
    },
  },
});

function change(key: string, value: Event, row: any) {
  // 调用校验方法校验数据是否能通过，因为当前校验方式是blur，在input事件触发时不会触发校验，
  // 但是为了在输入的时候控制保存按钮的状态，需要手动去触发校验函数获取校验结果，进而控制保存按钮状态
  validateResult[key] = rules[key].validator(rules[key], value, () => { });
  switch (key) {
    case 'address':
      row.address = value;
      break;
    case 'description':
      row.description = value;
      break;
    default:
      break;
  }
}
function validateAction(row: any) {
  const action = (key: string, 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 blur(key: string, row: any) {
  popoverVisible[key][row.num] = false;
}

function clear(key: string, row: any) {
  // 如果没有focus，那么这个地方需要手动调用一次校验
  if (popoverVisible[key] !== row.num) {
    if (key === 'description') {
      formRefObjs[editIndex]['des'].validateField(key);
    } else {
      formRefObjs[editIndex]['addr'].validateField(key);
    }
  }
}
function setAddrFormRef(el: any) {
  if (!formRefObjs[editIndex]) {
    formRefObjs[editIndex] = {};
  }
  formRefObjs[editIndex]['addr'] = el;
}
function setDesFormRef(el: any) {
  if (!formRefObjs[editIndex]) {
    formRefObjs[editIndex] = {};
  }
  formRefObjs[editIndex]['des'] = el;
}
watch(
  () => props.data,
  (val) => {
    val.map((item: any) => {
      popoverVisible.address[item.num] = false;
      popoverVisible.description[item.num] = false;
    });
  },
);
</script>

<style lang="scss" scoped>
.operate {
  cursor: pointer;
  color: var(--o-color-primary);
  &.not-allow {
    color: #b8becc !important;
    cursor: not-allowed !important;
  }
  &:hover {
    color: var(--o-color-primary-secondary);
  }
}
.edit {
  margin-right: 8px;
}
.save {
  margin-right: 8px;
}
.statusFalse > span {
  font-size: 12px;
  color: #ffffff;
  display: inline-block;
  border-radius: var(--i-button-border-radius);
  padding: 0 14px;
  background: var(--o-text-color-tertiary);
}
.statusTrue > span {
  font-size: 12px;
  color: #ffffff;
  display: inline-block;
  border-radius: var(--i-button-border-radius);
  padding: 0 14px;
  background: var(--o-color-success);
}
.input-form {
  &.has-error {
    .el-form-item {
      margin-bottom: var(--o-form-item-gap);
    }
  }
  .el-form-item {
    margin-bottom: 0;
  }
}
:deep(.el-table__cell) {
  vertical-align: baseline;
}
</style>
