<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  nextTick,
  computed,
} from 'vue';
import { useI18n } from 'vue-i18n';
import TableNoData from '@/components/TableNoData/TableNoData.vue';
import TableExtendData from './components/tableExtendData.vue';
import { loading, showFailedMessage, showSuccessMessage } from '@/utils/composition';
import ibmaServer from './ibma.server';
import { DEFAULT_DATA } from '@/model/base-enum';
import { rangeVerification, strVerification } from '@/validators/validation-functions';
import { traduction, getErrorTranslate } from '@/utils/language';
import useStore from '@/stores';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';

const i18n = useI18n();
const store = useStore();
const smsName = store.state.loct.smsName;
const { getTimerData, patchTimerData } = ibmaServer(smsName);

const etag = ref('');
const port1Form1 = ref();
const tableId = 'unitsTable';
let boardData: any = {};
let tableData = reactive({
  boardTableData: [],
} as any);
const isEdit = ref(false);
const canSave = ref(false);
let initData = reactive([] as any);

const total = ref(0);
const currentPage = ref(1);
let pageSizeCount = ref(10);

// 获取locked锁定值
let systemLockDownEnabled = computed(() => {
  return store.state.glob.systemLocked;
});
// 常规配置权限
const isBaseConfig = checkPrivil(UserPrivil.baseConfig);

// 第几页点击
const handleCurrentChange = (pageNumber: number) => {
  pageChange();
  validateResult = {};
};
// 框内页码范围
const handleSizeChange = (pageCount: number) => {
  pageSizeCount.value = pageCount;
  currentPage.value = 1;
  pageChange();
};
function pageChange() {
  tableData.boardTableData = JSON.parse(
    JSON.stringify(
      initData.slice(
        (currentPage.value - 1) * pageSizeCount.value,
        pageSizeCount.value * currentPage.value,
      ),
    ),
  );
}

watch(tableData, (now, old) => {
  findDiff();
});
function findDiff() {
  let result = true;
  for (let key in validateResult) {
    // 任意一个校验失败
    if (!validateResult[key]) {
      result = false;
      break;
    }
  }
  if (!result) {
    canSave.value = false;
    return;
  }
  let len =
    pageSizeCount.value * currentPage.value > initData.length
      ? initData.length
      : pageSizeCount.value * currentPage.value;
  for (
    let i = 0, j = (currentPage.value - 1) * pageSizeCount.value;
    i < tableData.boardTableData.length, j < len;
    i++, j++
  ) {
    if (Object.prototype.hasOwnProperty.call(tableData.boardTableData[i], 'tipState1')) {
      tableData.boardTableData[i].tipState1 = undefined;
    }
    if (Object.prototype.hasOwnProperty.call(tableData.boardTableData[i], 'tipState2')) {
      delete tableData.boardTableData[i].tipState2;
    }
    if (JSON.stringify(initData[j]) !== JSON.stringify(tableData.boardTableData[i])) {
      canSave.value = true;
      break;
    } else {
      canSave.value = false;
    }
  }
}

function getCurrentData(): any {
  pageSizeCount.value = 10;
  currentPage.value = 1;
  tableData.boardTableData.splice(0);
  initData.splice(0);
  loading(true);
  getTimerData()
    .then((res: any) => {
      etag.value = res.headers.etag;
      if (res.data.Members && res.data.Members.length > 0) {
        total.value = res.data.Members.length;
        res.data.Members.forEach((borad: any, index: number) => {
          const showData = parseData(borad, index);
          if (showData) {
            initData.push(showData);
          }
        });
        tableData.boardTableData = JSON.parse(JSON.stringify(initData));
        pageChange();
      }
    })
    .finally(() => {
      loading(false);
    });
}
onMounted(() => {
  getCurrentData();
});

function isOtherEmptyProperty(value: any, unit?: string): any {
  if (
    value === null ||
    value === undefined ||
    value === 'N/A' ||
    value === '' ||
    value === 'Unknown'
  ) {
    return DEFAULT_DATA.noDataStr;
  } else {
    return value;
  }
}
function parseData(board: any, id: number): any {
  const type = board.FunctionType;
  let extendAttr = [] as any;
  if (board.TimerActionStatus !== null) {
    Object.keys(board.TimerActionStatus).forEach(key => {
      const extendItem = {
        name: key,
        status: board.TimerActionStatus[key],
      };
      if (extendItem) {
        extendAttr.push(extendItem);
      }
    });
  }
  let extendObj = {
    extendTitleArr: unitsCardExtendArr,
    extendAttr: extendAttr as any[],
  };

  return {
    id,
    name: isOtherEmptyProperty(board.Id) || ' ',
    status: board.Enabled === false ? false : true,
    intervalInSeconds: String(board.IntervalInSeconds) || ' ',
    runTimes: board.RunTimes === ' ' || board.RunTimes === null ? ' ' : String(board.RunTimes),
    initRunTimes: board.RunTimes === ' ' || board.RunTimes === null ? ' ' : String(board.RunTimes),
    description: isOtherEmptyProperty(board.Description) || ' ',
    isInfinity: board.RunTimes === 0,
    isCanChange: board.Enabled === null,
    MaxIntervalInSeconds: board.MaxIntervalInSeconds,
    MinIntervalInSeconds: board.MinIntervalInSeconds,
    extendObj,
  };
}

// 表头数组
const columns = [
  {
    title: 'IBMC_TIMER_NAME',
    width: '20%',
    content: 'name',
    show: true,
  },
  {
    title: 'STATUS',
    width: '10%',
    content: 'status',
    show: true,
  },
  {
    title: 'IBMC_TIMER_MONITOR',
    width: '15%',
    content: 'intervalInSeconds',
    show: true,
  },
  {
    title: 'IBMC_TIMER_TIMES',
    width: '30%',
    content: 'runTimes',
    show: true,
  },
  {
    title: 'COMMON_DESCRIPTION',
    width: '20%',
    content: 'description',
    show: true,
  },
];
// Units卡扩展数据
const unitsCardExtendArr = [
  {
    label: 'IBMC_ATTR_NAME',
    content: 'name',
    hide: false,
  },
  {
    label: 'STATUS',
    content: 'status',
    hide: false,
  },
];
function initBasicCard(bodyData: any): any {
  const name = isOtherEmptyProperty(bodyData?.Name) || ' ';
  const status = isOtherEmptyProperty(bodyData?.Enabled) || ' ';
  const extendData = {
    name,
    status,
  };
  return extendData;
}
function editPort(value: boolean) {
  isEdit.value = value;
  if (!value) {
    tableData.boardTableData = JSON.parse(JSON.stringify(initData));
    canSave.value = value;
  }
  pageChange();
}
function confirm() {
  loading(true);
  let Members = [];
  for (let index = 0; index < tableData.boardTableData.length; index++) {
    let TimerActionStatus = {};
    if (tableData.boardTableData[index].extendObj?.extendAttr.length !== 0) {
      for (let item of tableData.boardTableData[index].extendObj?.extendAttr) {
        TimerActionStatus[item.name] = { Enabled: item.status.Enabled };
      }
    }
    const obj = {
      Id: tableData.boardTableData[index]['name'],
      Enabled: tableData.boardTableData[index]['status'],
      IntervalInSeconds: Number(tableData.boardTableData[index]['intervalInSeconds']),
      RunTimes: tableData.boardTableData[index]['isInfinity']
        ? 0
        : Number(tableData.boardTableData[index]['runTimes']),
      TimerActionStatus,
    };

    Members.push(obj);
  }

  patchTimerData(Members, etag.value)
    .then((res: any) => {
      isEdit.value = false;
      getCurrentData();
      showSuccessMessage();
    })
    .catch((error: any) => {
      pageSizeCount.value = 10;
      currentPage.value = 1;
      pageChange();
      loading(false);
      isEdit.value = false;
      const errorCode = error?.data.error[0].code;
      showFailedMessage(getErrorTranslate(errorCode));
    });
}
let validateResult = {};
function rules(type: boolean) {
  return {
    type: 'number',
    required: true,
    isInteger: true,
    min: type ? 0 : 1,
    max: 10000,
    message: traduction('VALID_VALUE_RANGE_TIP', [type ? 0 : 1, 10000]),
    validator: rangeVerification,
    trigger: 'blur',
  };
}
function intervalRule(min: number, max: number) {
  return {
    type: 'number',
    required: true,
    isInteger: true,
    min,
    max,
    message: traduction('VALID_VALUE_RANGE_TIP', [min, max]),
    validator: rangeVerification,
    trigger: 'blur',
  };
}

// 输入框 发生input 事件
function input(inputItem: any, value: number, valid: string) {
  nextTick(() => {
    findDiff();
  });
}
// 表单校验发生时 - 控制保存按钮状态 state:校验结果
function validate(index: number, name: any) {
  const fn = (key: string, state: boolean) => {
    validateResult[name] = state;
    nextTick(() => {
      findDiff();
    });
  };
  return { action: fn };
}

function isInfinity(data: any, isCheck: boolean) {
  if (!isCheck) {
    data.runTimes = data.initRunTimes > 10000 ? data.initRunTimes : '1';
  } else {
    data.runTimes = '0';
  }
  for (let item of port1Form1.value) {
    item.validate();
  }
}
</script>

<template>
  <div id="unitPage" class="system-info-table">
    <div class="port-buttons">
      <el-button
        v-if="!isEdit"
        id="portEdit"
        type="primary"
        :disabled="systemLockDownEnabled || !isBaseConfig"
        @click="editPort(true)"
      >
        {{ $t('COMMON_EDIT') }}
      </el-button>
      <el-button
        v-if="isEdit" id="portSave" :disabled="!canSave" type="primary"
        @click="confirm()"
      >
        {{ $t('COMMON_SAVE') }}
      </el-button>
      <el-button v-if="isEdit" id="portCancel" @click="editPort(false)">
        {{ $t('COMMON_CANCEL') }}
      </el-button>
    </div>
    <el-table
      :id="tableId"
      :data="tableData.boardTableData"
      resizable
      border
      row-key="id"
      class="table"
    >
      <el-table-column class="expand" type="expand" min-width="20px">
        <template #default="scope">
          <span v-t="'IBMC_SUB_ATTRIBUTE'" class="module-title" />
          <TableExtendData
            :data-list="scope.row.extendObj.extendTitleArr"
            :fields="scope.row.extendObj.extendAttr"
            :is-edit="isEdit"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-for="col in columns"
        :key="col?.content"
        :label="$t(col?.title)"
        :prop="col?.content"
        :min-width="col?.width"
      >
        <template #default="scope">
          <div v-if="col.content === 'name' && isEdit" class="text-h32">
            {{ scope.row.name }}
          </div>
          <div v-if="col.content === 'status' && isEdit" class="text-h32">
            <el-switch
              :id="'switch_' + scope.row.name"
              v-model="scope.row.status"
              :active-value="true"
              :inactive-value="false"
              :disabled="scope.row.isCanChange"
            />
          </div>
          <div v-if="col.content === 'status' && !isEdit">
            <el-tag v-if="scope.row.status" type="success">{{ $t('STORE_ENABLED') }}</el-tag>
            <el-tag v-else type="info">{{ $t('IBMC_DISENABLED') }}</el-tag>
          </div>
          <div v-if="col.content === 'intervalInSeconds' && isEdit" class="text-h32">
            <el-form
              ref="port1Form"
              :model="scope.row"
              :validate-on-rule-change="false"
              @validate="validate(scope.$index, scope.row.name).action"
            >
              <el-form-item
                prop="intervalInSeconds"
                class="input-form-item"
                :rules="
                  intervalRule(scope.row.MinIntervalInSeconds, scope.row.MaxIntervalInSeconds)
                "
              >
                <div class="inputBox text-h32">
                  <el-tooltip
                    :visible="scope.row.tipState1"
                    :content="
                      $t('VALIDTOR_INTGER_RANGE', [
                        scope.row.MinIntervalInSeconds,
                        scope.row.MaxIntervalInSeconds
                      ])
                    "
                    :hide-after="0"
                    placement="top"
                    transition="none"
                    trigger-keys
                  >
                    <el-input
                      v-model="scope.row.intervalInSeconds"
                      v-addId.input="scope.row.id1"
                      v-clearable
                      clearable
                      type="number"
                      class="input"
                      @focus="scope.row.tipState1 = true"
                      @blur="scope.row.tipState1 = false"
                      @input="input('httpServerIpv4', $event, 'ipV4')"
                    >
                      <template #suffix>
                        <ErrorIcon />
                        <ClearableIcon />
                      </template>
                    </el-input>
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div
            v-if="col.content === 'runTimes' && isEdit && scope.row.runTimes !== ' '"
            class="text-h32"
          >
            <el-form
              ref="port1Form1"
              :model="scope.row"
              :validate-on-rule-change="false"
              @validate="validate(scope.$index, scope.row.name).action"
            >
              <el-form-item
                prop="runTimes"
                class="input-form-item"
                :rules="rules(scope.row.isInfinity)"
              >
                <div class="inputBox">
                  <el-tooltip
                    :visible="scope.row.tipState2"
                    :content="$t('VALIDTOR_INTGER_RANGE', [1, 10000])"
                    :hide-after="0"
                    placement="top"
                    transition="none"
                    trigger-keys
                  >
                    <el-input
                      v-model="scope.row.runTimes"
                      v-addId.input="scope.row.id1"
                      v-clearable
                      clearable
                      type="number"
                      class="input"
                      :disabled="scope.row.isInfinity || scope.row.initRunTimes > 10000"
                      @focus="scope.row.tipState2 = true"
                      @blur="scope.row.tipState2 = false"
                    >
                      <template #suffix>
                        <ErrorIcon />
                        <ClearableIcon />
                      </template>
                    </el-input>
                  </el-tooltip>
                  <el-checkbox
                    v-model="scope.row.isInfinity"
                    :label="$t('IBMA_INFINITY')"
                    size="large"
                    class="checkBox"
                    @change="isInfinity(scope.row, scope.row.isInfinity)"
                  />
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div v-if="col.content === 'runTimes' && !isEdit && scope.row.runTimes === '0'">
            {{ $t('IBMA_INFINITY') }}
          </div>
          <div v-if="col.content === 'description' && isEdit" class="text-h32">
            {{ scope.row.description }}
          </div>
        </template>
      </el-table-column>
      <template #empty>
        <TableNoData />
      </template>
    </el-table>
    <div v-if="total > 0" class="pagination">
      <el-pagination
        v-model:currentPage="currentPage"
        v-addId.pagination="'alarmPageNation'"
        :page-sizes="[10, 15, 30, 50]"
        :page-size="pageSizeCount"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.port-buttons {
  margin-bottom: 16px;
}
.system-info-table {
  background: var(--o-bg-color-base);
  border-radius: 4px;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  .pagination {
    margin-top: 16px;
  }
  .table {
    min-height: 251px;
  }
  :deep(.el-table--border) {
    .el-table__cell:first-child .cell {
      width: 16px;
      padding-left: 0;
      display: inline-block;
    }

    .el-table__cell {
      padding: 8px;
      .cell {
        line-height: 32px;
      }
    }
    .el-table__header {
      .cell {
        line-height: 16px;
        height: 16px;
      }
    }

    tr,
    colgroup {
      th:nth-child(1),
      col:nth-child(1),
      td:nth-child(1) {
        width: 40px;
        max-width: 40px;
      }
    }
  }

  .el-tabs__content {
    margin-top: 0;
  }

  .summary {
    padding: 16px 0;
  }
  .label-content {
    background: var(--o-border-color-light);
    border-radius: 8px;
    width: 28px;
    height: 16px;
    display: inline-block;
    text-align: center;
    margin: 0 16px 0 8px;
    font-size: 12px;
    font-weight: 900;
  }

  .label {
    font-size: 12px;
    color: $APP-COLOR-TEXT;
    letter-spacing: 0;
    line-height: 16px;
  }
  .detail {
    width: 50%;
    float: left;
    display: flex;
    margin-top: 8px;
  }

  .module-title {
    font-weight: 700;
    margin: 16px 0;
    display: block;
  }
}
.inputBox {
  display: flex;
  .input {
    width: 56px;
  }
  .checkBox {
    margin-left: 26px;
    line-height: 32px;
    height: 32px;
  }
}

.text-h32 {
  min-height: 32px;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  :deep(.el-form-item) {
    margin-bottom: 0px !important;
    .el-form-item__content {
      display: block;
    }
  }
  :deep(.el-form-item__error) {
    padding-bottom: 0;
    position: relative;
    top: 0;
    left: 0;
    word-wrap: break-word;
    white-space: nowrap;
  }
}
</style>
<style lang="scss">
#unitPage {
  .el-scrollbar{
    .el-table__expanded-cell {
      padding-left: 40px !important;
      padding-top: 0;
      background: var(--o-bg-color-light);
    }
  }
  

  .el-table tr th {
    font-weight: 600 !important;
  }

  .expanded {
    background: var(--o-bg-color-light);
    box-shadow: inset 0 -1px 0 0 var(--o-border-color-light);
  }

  .el-table__header {
    width: 100% !important;
  }

  .el-table__body {
    width: 100% !important;
  }
}
</style>
