<script lang="ts" setup>
import { computed, nextTick, onMounted, reactive, ref, toRaw, watch } from 'vue';
import { getStoreData } from '@/utils/composition';
import { traduction } from '@/utils/language';
import { ISettingTitle } from '../model/model';
import { ITableColumns } from '@/model/base-interface';
import { IconCaretRight, IconCaretDown } from '@computing/opendesign-icons';
import biosCollapse from './biosCollapse.vue';
import useStore from '@/stores';

const store = useStore();
// 系统锁定状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const privil = getStoreData('loct', 'privil');
const hasConfigUsers = privil.includes('UserConfigEnabled');
const props = defineProps({
  data: {
    type: Object,
    required: true,
    default: () => []
  },
  rootData: {
    type: Object,
    required: false,
    default: () => []
  },
  isRoot: {
    type: Boolean,
    default: false
  }
});

const formRefObj = ref();

const emits = defineEmits(['showHelpTips', 'validate']);

const columns: ITableColumns[] = [
  {
    title: 'BIOS_CONFIGURATION_ITEM',
    width: '25%',
    content: 'AttributeName'
  },
  {
    title: 'FAN_CURRENT_VAL',
    width: '25%',
    content: 'CurrentValue'
  },
  {
    title: 'BIOS_PENDING_ITEM',
    width: '25%',
    content: 'SettingValue'
  }
];

const inputRule = reactive({
  stringValue: (min, max) => {
    return {
      trigger: 'change',
      type: 'text',

      validator: (rule: any, value: any, callback: (error?: Error) => void) => {
        let result = true;
        if (value.length < min || value.length > max) {
          result = false;
          callback(traduction('BIOS_STRING_ERROR', [min, max]));
          return;
        }
        result ? callback() : callback(new Error(traduction('COMMON_FORMAT_ERROR')));
      }
    };
  },
  numberValue: (item: any) => {
    return {
      trigger: 'change',
      type: 'text',
      validator: (rule: any, value: any, callback: (error?: Error) => void) => {
        if (!value && value !== 0) {
          callback(new Error(traduction('COMMON_FORMAT_ERROR')));
          return;
        }
        if ((value - item.standardValue) % item.ScalarIncrement !== 0) {
          callback(new Error(traduction('BIOS_NUMBER_ERROR', [item.standardValue,item.ScalarIncrement])));
          return;
        }
        callback();
      }
    };
  },
  otherValue: {
    trigger: 'change',
    type: 'text',
    message: '',
    validator: (rule: any, value: any, callback: (error?: Error) => void) => {
      callback();
    }
  }
});

const settingTitle = reactive([]) as Array<ISettingTitle>;
const activeName = ref('');
const selectTitle = ref('');

function handleChange(title: string) {
  selectTitle.value = title;
}

const validateResult = reactive([]);

function validateAction(row: any) {
  nextTick(() => {
    if (formRefObj.value) {
      for (let index = 0; index < formRefObj.value.length; index++) {
        formRefObj.value[index].validateField('CurrentValue');
      }
    }
  });
  const action = (key: string, value: boolean) => {
    row.pass = value;
    emits('validate');
  };
  return { action };
}

function validate() {
  emits('validate');
}

function showHelpTips(item: any) {
  emits('showHelpTips', item);
}

function init() {
  if (JSON.stringify(props.data) === '{}') {
    return;
  }
  settingTitle.splice(0);
  for (let index = 0; index < props.data?.length; index++) {
    const obj = {
      id: props.data[index].Name,
      title: props.data[index].Name,
      tableData: JSON.parse(JSON.stringify(props.data[index])),
      editData: props.data[index]
    };
    const resultAttributes = obj.editData?.Attributes && obj.editData?.Attributes?.length !== 0;
    const resultSubMenu = obj.editData?.SubMenu && obj.editData?.SubMenu?.length !== 0;
    if (resultAttributes || resultSubMenu) {
      settingTitle.push(obj);
    }
  }
}

watch(
  () => props.rootData,
  () => {
    init();
  },
  { deep: true }
);

onMounted(() => {
  nextTick(() => {
    init();
  });
});
</script>
<template>
  <div id="biosCollapse" class="bios-collapse">
    <el-collapse v-model="activeName" accordion @change="handleChange">
      <el-collapse-item
        v-for="item in settingTitle"
        :key="item.id"
        :id="`collapseItem${item.id}`"
        :title="item.title"
        :name="item.id"
      >
        <template #title>
          <div id="title-box" class="title-box">
            <div id="icon-box" class="icon-box" :class="{ 'no-margin': !props.isRoot }">
              <el-icon v-if="selectTitle !== item.title" id="titleRightIcon" class="title-icon">
                <IconCaretRight />
              </el-icon>
              <el-icon v-else class="titleIcon"><IconCaretDown /></el-icon>
              <div class="title-content">{{ item.title }}</div>
              <div
                :id="`${item.title}Pending`"
                class="pending-box"
                v-if="props.isRoot && item.editData.showPending"
              >
                {{ $t('BIOS_PENDING') }}
              </div>
            </div>
            <el-button
              text
              v-if="selectTitle === item.title && props.isRoot"
              :id="`operating${item.title}Id`"
              class="help-btn-text"
              @click.stop="showHelpTips(item)"
            >
              {{ $t('BIOS_PENDING_TIPS') }}
            </el-button>
          </div>
        </template>
        <div :id="`settingBox${item.id}`" class="setting-box" :class="{'margin-large' : !props.isRoot }" v-if="activeName === item.id">
          <div
            id="editTable"
            class="edit-table"
            v-if="!item.editData.ReadOnly && item.editData.Attributes?.length > 0"
          >
            <el-table
              v-addId.table="`assetChangeTable${item.id}`"
              :data="item.editData.Attributes.filter(i => !i.Hidden)"
              header-row-class-name="table-header"
            >
              <el-table-column
                v-for="item in columns"
                :key="item.title"
                :label="$t(item.title)"
                :min-width="item.width"
                show-overflow-tooltip
              >
                <template #default="scope">
                  <div
                    v-if="
                      item.content === 'CurrentValue' &&
                        (!scope.row.ReadOnly || !scope.row.Immutable)
                    "
                    :id="'CurrentValue' + scope.row.AttributeName"
                    class="status"
                  >
                    <el-form
                      ref="formRefObj"
                      class="form"
                      :model="scope.row"
                      label-width="0px"
                      :validate-on-rule-change="false"
                      @validate="validateAction(scope.row).action"
                    >
                      <!-- 枚举、布尔值 -->
                      <el-form-item
                        label=""
                        prop="CurrentValue"
                        class="form-item"
                        :rules="inputRule.otherValue"
                        v-if="scope.row.Type === 'Enumeration' || scope.row.Type === 'Boolean'"
                      >
                        <el-select
                          v-addId.select="`${scope.row.AttributeName}Input`"
                          :disabled="isSystemLock || !hasConfigUsers"
                          class="selectBox"
                          v-model="scope.row.CurrentValue"
                          popper-class="login-select"
                          :teleported="true"
                          :suffix-icon="IconCaretUp"
                        >
                          <el-option
                            :id="`${scope.row.AttributeName}Option${index}`"
                            v-for="(item, index) in scope.row.Value"
                            :key="item.ValueName"
                            :label="item.ValueName"
                            :value="item.ValueName"
                          />
                        </el-select>
                      </el-form-item>
                      <!-- 数字 -->
                      <el-form-item
                        label=""
                        prop="CurrentValue"
                        class="form-item number-item"
                        :rules="inputRule.numberValue(scope.row)"
                        v-else-if="scope.row.Type === 'Integer'"
                      >
                        <el-input-number
                          :disabled="isSystemLock || !hasConfigUsers"
                          v-model="scope.row.CurrentValue"
                          :step="scope.row.ScalarIncrement"
                          :max="scope.row.UpperBound"
                          :min="scope.row.LowerBound"
                          title=""
                        />
                      </el-form-item>
                      <!-- 密码 -->
                      <el-form-item
                        label=""
                        prop="CurrentValue"
                        class="form-item"
                        :rules="inputRule.stringValue(scope.row.Minlength, scope.row.MaxLength)"
                        v-else-if="scope.row.Type === 'Password'"
                      >
                        <el-input
                          class="table-input"
                          type="password"
                          :disabled="isSystemLock || !hasConfigUsers"
                          v-model="scope.row.CurrentValue"
                          password
                          :input-style="{ width: '200px' }"
                        ></el-input>
                      </el-form-item>
                      <!-- String -->
                      <el-form-item
                        label=""
                        prop="CurrentValue"
                        class="form-item"
                        :rules="inputRule.stringValue(scope.row.Minlength, scope.row.MaxLength)"
                        v-else
                      >
                        <el-input
                          class="table-input"
                          :disabled="isSystemLock || !hasConfigUsers"
                          v-model="scope.row.CurrentValue"
                          :input-style="{ width: '200px' }"
                        ></el-input>
                      </el-form-item>
                    </el-form>
                  </div>
                  <span
                    :id="item.content + scope.row.AttributeName"
                    :class="item.content"
                    class="cell-span"
                    v-else
                  >
                    {{ scope.row[item.content] }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div id="readOnlyBox" class="read-only-box" v-else>
            <div
              v-for="i in item.editData.Attributes"
              :key="i.AttributeName"
              class="read-only-item"
            >
              <div class="title">{{ i.AttributeName }}</div>
              <div class="content">{{ i.CurrentValue }}</div>
            </div>
          </div>
          <biosCollapse
            :id="`sub${item.id}`"
            v-if="item.editData?.SubMenu?.length > 0"
            :data="item.editData.SubMenu"
            :root-data="props.rootData"
            @validate="validate"
          />
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<style lang="scss" scoped>
.cpu-alert-container {
  margin-bottom: 8px;
}

.cpu-alert-container:nth-child(2) {
  margin-bottom: 16px;
}

h3 {
  font-size: $FONT-16;
  margin-bottom: 16px;
  .help-icon-cpu {
    margin-left: 3px;
    margin-top: -2px;

    :deep(.el-popper) {
      max-width: 382px;
    }
  }
}
.slider-item {
  margin-bottom: 50px;
  :deep(.el-slider__stop) {
    display: none;
  }

  .slider {
    width: calc(100% - 16px);
    margin-left: 8px;
  }
}

.bios-collapse {
  .btnBox {
    margin-bottom: 16px;
  }
  :deep(.el-collapse) {
    border-top: none;
    border-bottom: none;
    .el-collapse-item {
      margin-bottom: 8px;
      .el-collapse-item__wrap {
        background: var(--o-bg-color-light);
        border-bottom: none;
      }
      .el-collapse-item__content {
        padding-bottom: 0px;
        margin: 0;
        background: var(--o-bg-color-light);
        .el-scrollbar__wrap {
          background: var(--o-bg-color-light);
        }
      }
    }
    .tableHeight {
      min-height: 0px;
      .el-table__inner-wrapper {
        min-height: 0px;
      }
      .el-table__body-wrapper {
        min-height: 0px;

        .el-scrollbar {
          min-height: 0px;

          .el-scrollbar__wrap {
            min-height: 0px;
          }
        }
      }
    }

    :last-child {
      margin-bottom: 0px;
    }
    .el-collapse-item__header {
      border-bottom: none;
      border-radius: 4px;
      background: var(--o-bg-color-light);
      padding: 0;
    }
    .el-collapse-item__arrow {
      display: none;
    }
    .el-table__row > td {
      border: none;
      background: var(--o-bg-color-light);
    }
    .el-table__cell {
      border: none;
      background: var(--o-bg-color-light);
    }
    .setting-box {
      margin: 8px 32px;
      background: var(--o-bg-color-light);
      .settingBtnBox {
        margin-bottom: 16px;
      }
      .edit-table {
        .table-input {
          .el-input__wrapper {
            width: 200px;
          }
        }
        .el-table--fit {
          min-height: 0px;
        }
        .el-table__inner-wrapper {
          min-height: 0px;
        }
        .el-table__body-wrapper {
          min-height: 0px;
        }
        .el-scrollbar {
          min-height: 0px;
        }
        .el-scrollbar__wrap {
          min-height: 0px;
          overflow: visible;
        }
        .table-header {
          :first-child {
            border-radius: 4px 0px 0px 4px;
          }
          :last-child {
            border-radius: 0px 4px 4px 0px;
            border-right: none;
          }
          th {
            background: var(--o-border-color-base);
            border-right: 2px solid var(--o-color-white);
          }
        }
        .el-table__cell {
          vertical-align: top;
          .cell-span {
            min-height: 32px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: flex-start;
          }
        }
        .el-scrollbar__bar {
          display: none;
        }
        .el-input-number {
          width: 122px;
          .el-input__wrapper .el-input__inner {
            padding-right: 42px !important;
          }
        }
        .el-form {
          display: flex;

          .el-form-item {
            margin-bottom: 0;

            .el-form-item__content {
              width: 200px;

              .el-form-item__error {
                position: relative;
                top: 0;
                left: 0;
                word-wrap: break-word;
              }
            }
          }
          .number-item {
            .el-form-item__content {
              display: block;
            }
          }
        }
      }
      .read-only-box {
        display: flex;
        flex-wrap: wrap;

        .read-only-item {
          display: flex;
          margin-left: 8px;
          width: calc(50% - 8px);
          margin-top: 8px;
          .title {
            width: 50%;
            font-size: 12px;
            color: #4e5865;
            font-family: HarmonyOS Sans SC;
            font-weight: regular;
            line-height: 16px;
          }
          .content {
            width: 60%;
            font-size: 12px;
            color: #4e5865;
            font-family: HarmonyOS Sans SC;
            font-weight: regular;
            line-height: 16px;
          }
        }
        :first-child {
          margin-top: 0px;
        }
        :nth-child(2) {
          margin-top: 0px;
        }
      }
    }
    .margin-large{
      margin: 8px 16px;
    }
  }
  .selectBox {
    width: 200px;
  }
  .title-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;
    color: #000000;
    font-family: HarmonyOS Sans SC;
    font-weight: medium;
    line-height: 24px;
    width: 100%;
    padding-right: 16px;

    .icon-box {
      display: flex;
      align-items: center;
      justify-content: center;
      padding-left: 16px;
      .title-icon {
        font-size: 16px;
      }
      .title-content {
        font-size: 16px;
        color: #000000;
        font-family: HarmonyOS Sans SC;
        font-weight: bold;
        line-height: 24px;
        padding-left: 8px;
      }
      .pending-box {
        border-radius: 2px;
        background: var(--o-color-warning);
        font-size: 12px;
        color: var(--o-color-white);
        font-family: HarmonyOS Sans SC;
        font-weight: medium;
        line-height: 16px;
        padding: 4px 8px;
        margin-left: 8px;
      }
    }
    .help-btn-text {
      font-size: 12px;
      color: var(--o-button-color_label);
      font-family: HarmonyOS Sans SC;
      font-weight: medium;
      line-height: 16px;
      &:hover {
        color: var(--o-color-primary-secondary);
      }
    }
    .no-margin {
      padding-left: 0px;
    }
  }
}

.help-tips-box {
  width: 100%;
}
</style>
