<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { traduction } from '@/utils/language';
import { rangeVerification } from '@/validators/validation-functions';
import { compareObjectEqual } from '@/utils/utils';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';
import Date from '@/utils/date';

const props = defineProps({
  templateData: {
    type: Object,
    default: () => ({}),
  },
  taskStatus: {
    type: Boolean,
    default: () => false,
  },
  aliveDateTime: {
    type: String,
    default: () => '',
  },
  aliveModel: {
    type: String,
    default: 'immediately',
  },
});
const deviceTypes = ref(['CPU', 'Memory', 'Disk', 'NIC']);
const modes = ref(['Quick', 'Full']);
const disabled = computed(() => {
  return props.taskStatus;
});
const formState = ref({
  DeviceType: true,
  Mode: true,
  DurationMinutes: true,
});

let baseDiagnoseParams = {
  DeviceType: '',
  Mode: '',
  DurationMinutes: '',
};
const basicParams = reactive(JSON.parse(JSON.stringify(baseDiagnoseParams)));
const oldData = reactive(JSON.parse(JSON.stringify(baseDiagnoseParams)));

watch(
  () => props.templateData,
  newVal => {
    let params = newVal;
    if (JSON.stringify(newVal) === '{}') {
      params = baseDiagnoseParams;
    } else {
      params = newVal.Diagnose[0];
    }
    for (let key in params) {
      if (Object.prototype.hasOwnProperty.call(basicParams, key)) {
        basicParams[key] = params[key];
        oldData[key] = params[key];
        resetControlValue(key, params[key]);
      }
    }
    changeDeviceType();
  },
);

const aliveTime = ref(props.aliveDateTime ? 
  new Date(props.aliveDateTime).pattern('HH:mm') :
  '');
const aliveDate = ref(props.aliveDateTime ? 
  new Date(props.aliveDateTime).pattern('yyyy/MM/dd') :
  '');
watch(
  () => props.aliveDateTime,
  newVal => {
    aliveTime.value = newVal ?
      new Date(newVal).pattern('HH:mm') :
      '';
    aliveDate.value = newVal ?
      new Date(newVal).pattern('yyyy/MM/dd'):
      '';
  },
);
function changeDateTime() {
  emits('datetime-change', aliveDate.value, aliveTime.value);
}

const aliveModel = ref(props.aliveModel);
watch(
  () => props.aliveModel,
  newVal => {
    aliveModel.value = newVal;
  },
);
function changeAliveModel() {
  emits('aliveModel-change', aliveModel.value);
}

const basicPoperState = reactive({
  DeviceType: false,
  Mode: false,
  DurationMinutes: false,
});

function togglePopper(target: string, value: boolean) {
  basicPoperState[target] = value;
}

const modelOptions = reactive([
  {
    label: traduction('SP_TASK_IMMEDIATELY'),
    value: 'immediately',
    disable: false,
    id: 1,
  },
  {
    label: traduction('SP_TASK_LATER'),
    value: 'later',
    disable: false,
    id: 2,
  },
]);

function resetControlValue(key: string, value: any) {
  basicParams[key] = value;
  if (formRules[key]) {
    formState.value[key] = formRules[key]?.validator(formRules[key], basicParams[key], () => {});
  }
}

const emits = defineEmits(['btn-status', 'data-change', 'datetime-change', 'aliveModel-change']);
const btnStatus = computed(() => {
  let status = compareObjectEqual(basicParams, oldData);
  let formValidateStatus = Object.values(formState.value).every(f => f);
  emits('btn-status', {
    status,
    validRes: formValidateStatus,
  });
  let changeData = setEmitData(basicParams);
  emits('data-change', {
    Diagnose: [changeData],
  });
  return status || !formValidateStatus;
});
function setEmitData(data: any) {
  let tmpData = JSON.parse(JSON.stringify(data));
  if (!tmpData.DurationMinutes) {
    delete tmpData.DurationMinutes;
  } else {
    tmpData.DurationMinutes = Number(tmpData.DurationMinutes);
  }
  return tmpData;
}

const formRules = reactive({
  DurationMinutes: {
    id: 'DurationMinutes',
    type: 'number',
    required: false,
    isInteger: true,
    min: 0,
    validator: rangeVerification,
    message: traduction('VALIDTOR_FORMAT_ERROR'),
    trigger: 'change',
  },
});

const basicTips = reactive({
  DurationMinutes: traduction('SP_INPUT_COMMON', { key: traduction('DIAGNOSIS_DURATION')}),
});

const basicFormRef = ref();
function changeDeviceType() {
  if (basicParams.DeviceType === 'CPU') {
    formRules.DurationMinutes.min = 1;
    formRules.DurationMinutes.max = 10000;
    formRules.DurationMinutes.message = traduction('VALIDTOR_INTGER_RANGE', [1, 10000]);
    basicTips.DurationMinutes = traduction('VALIDTOR_INTGER_RANGE', [1, 10000]);
  } else if (basicParams.DeviceType === 'Memory') {
    formRules.DurationMinutes.min = 1;
    formRules.DurationMinutes.max = 99999;
    formRules.DurationMinutes.message = traduction('VALIDTOR_INTGER_RANGE', [1, 99999]);
    basicTips.DurationMinutes = traduction('VALIDTOR_INTGER_RANGE', [1, 99999]);
  } else {
    formRules.DurationMinutes.min = 0;
    delete formRules.DurationMinutes.max;
    formRules.DurationMinutes.message = traduction('VALIDTOR_FORMAT_ERROR');
    basicTips.DurationMinutes = traduction('SP_INPUT_COMMON', { key: traduction('DIAGNOSIS_DURATION')});
  }
  basicFormRef.value.validateField('DurationMinutes', (res: boolean) => {
    formState.value.DurationMinutes = res;
  });
}


</script>

<template>
  <div class="root-container">
    <div class="basic-container">
      <el-form
        ref="basicFormRef"
        :model="basicParams"
        :rules="formRules"
        :validate-on-rule-change="false"
        label-position="left"
        label-width="auto"
      >
        <el-form-item :label="$t('IBMC_MANUAL_EFFECTIVE')" prop="aliveModel">
          <template #label>
            <span class="required-sign">{{ $t('IBMC_MANUAL_EFFECTIVE') }}</span>
          </template>
          <el-radio-group 
            id="aliveModelItem" 
            v-model="aliveModel"  
            @change="changeAliveModel"
          >
            <el-radio
              v-for="(item, index) in modelOptions"
              :key="item.id"
              v-addId.radio="'model' + index"
              :label="item.value"
              :disabled="disabled"
              class="radio-item"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="aliveModel === 'later'" :label="$t('SP_TASK_VALIDATE_TIME')" prop="time">
          <template #label>
            <span class="required-sign">{{ $t('SP_TASK_VALIDATE_TIME') }}</span>
          </template>
          <el-date-picker
            v-model="aliveDate"
            type="date"
            :disabled="disabled"
            :clearable="false"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="changeDateTime"
          />
          <el-time-picker
            v-model="aliveTime"
            :disabled="disabled"
            :clearable="false"
            format="HH:mm"
            value-format="HH:mm"
            @change="changeDateTime"
          />
        </el-form-item>
        <el-form-item :label="$t('DIAGNOSIS_ITEM')" prop="DeviceType">
          <el-radio-group
            id="DeviceType"
            v-model="basicParams.DeviceType"
            :disabled="disabled"
            class="switch-btn"
            @change="changeDeviceType"
          >
            <el-radio-button
              v-for="(item, index) in deviceTypes"
              :key="item"
              v-addId.radio="`DeviceType${index}`"
              :label="item"
            >
              {{ item }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item :label="$t('DIAGNOSIS_TYPE')" prop="Mode">
          <el-radio-group
            v-model="basicParams.Mode"
            :disabled="disabled"
          >
            <el-radio 
              v-for="(m, index) in modes"
              :key="index"
              v-addId.radio="m"
              class="radio-item" :label="m"
            ></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="$t('DIAGNOSIS_DURATION')" prop="DurationMinutes">
          <el-popover
            :content="basicTips.DurationMinutes"
            :visible="basicPoperState.DurationMinutes"
            :teleported="false"
            popper-class="wrap-popper"
            placement="right"
            trigger="focus"
            trigger-keys
          >
            <template #reference>
              <el-input
                id="basicDurationMinutes"
                v-model="basicParams.DurationMinutes"
                v-clearable
                clearable
                type="text"
                class="duration-input"
                :disabled="disabled"
                :placeholder="$t('COMMON_INPUT_TEXT')"
                @input="resetControlValue('DurationMinutes', $event)"
                @focus="togglePopper('DurationMinutes', true)"
                @blur="togglePopper('DurationMinutes', false)"
              >
                <template #suffix>
                  <ErrorIcon />
                  <ClearableIcon />
                </template>
              </el-input>
            </template>
          </el-popover>
          <span class="form-end">{{ $t('IBMA_LOG_EXPORT_TIME_UNIT') }}</span>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <span class="hidden">{{ btnStatus }}</span>
</template>
      

<style lang="scss" scoped>
.basic-container {
  .form-block {
    h4 {
      margin-bottom: 16px;
    }
    .form-block-content {    
      padding: 32px 16px 16px;
      border-radius: 4px;
      border: 1px solid #c3cedf;
    }
  }
  .el-form .form-row {
    border-radius: 4px;
    display: flex;
    flex-wrap: wrap;
    & > .el-form-item {
      margin-bottom: 24px;
      padding-right: 32px;
      width: calc(100% / 3);
    }
  }
  .form-end {
    margin: 0 8px;
  }
}
.duration-input {
  width: 60px !important;
}
.required-sign::before {
  content: '*';
  position: absolute;
  font-size: 12px;
  margin-left: -6px;
  color: var(--o-form-require-color);
  margin-right: 0;
}
:deep(.el-input) {
  width: 320px;
}

:deep(.el-select) {
  max-width: 320px;
  width: 100%;
}

:deep(.el-radio-group) {
  vertical-align: middle;
  .radio-item {
    width: 70px;
  }
}
:deep(.el-form-item.title) {
  margin-bottom: 16px !important;
  height: 24px;
  .el-form-item__label {
    font-size: 16px !important;
    font-weight: 600;
    color: var(--o-text-color-primary);
    line-height: 24px;
    padding-top: 0;
    padding-bottom: 0;
  }
}
:deep(.el-form-item.is-required) {
  .el-form-item__label::before {
    position: absolute;
    font-size: 16px;
    margin-left: -10px;
    margin-top: 2px;
  }
}
:deep(.basic-cert-container) {
  &.valid {
    margin-bottom: 16px !important;
  }
  height: 16px;
  .el-form-item__label-wrap {
    .el-form-item__label {
      padding-top: 0px;
    }
  }
  .el-form-item__content {
    position: relative;
    display: block;
  }
}

:deep(.el-form) {
  .el-form-item {
    margin-bottom: 24px;

    .el-form-item__label {
      padding-right: 24px;
      font-size: 12px;
    }
  }

  .save-btn {
    margin-bottom: 0;
  }

  .special-el-form-item {
    height: 16px;
    .el-form-item__label {
      padding-top: 0;
      padding-bottom: 0;
    }

    .el-form-item__content {
      .el-radio {
        height: auto;
      }
    }
  }
}
.hidden {
  opacity: 0;
}
</style>
<style>
.wrap-popper {
  max-width: 376px !important;
  white-space: wrap !important;
  font-size: 12px !important;
  width: max-content !important;
}
</style>