<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { IconCaretDown } from '@computing/opendesign-icons';
import { strVerification } from '@/validators/validation-functions';
import { compareObjectEqual } from '@/utils/utils';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';
import { traduction } from '@/utils/language';
import Date from '@/utils/date';
const SPECIALS_STR = '******';
const URI_PATTERN_STRING = /^(?!.*[|\;&\$><,@\[\]]).*$/;

const props = defineProps({
  templateData: {
    type: Object,
    default: () => ({}),
  },
  taskStatus: {
    type: Boolean,
    default: () => false,
  },
  aliveDateTime: {
    type: String,
    default: () => '',
  },
  aliveModel: {
    type: String,
    default: 'immediately',
  },
});

const disabled = computed(() => {
  return props.taskStatus;
});
const formState = ref({
  ImageURI: true,
  SignalURI: true,
  ImageType: true,
  Parameter: true,
  UpgradeMode: true,
  ActiveMethod: true,
});

let baseUpgradeParams = {
  ImageURI: '',
  SignalURI: '',
  ImageType: '',
  Parameter: [],
  UpgradeMode: '',
  ActiveMethod: '',
};
const basicParams = reactive(JSON.parse(JSON.stringify(baseUpgradeParams)));
const oldData = reactive(JSON.parse(JSON.stringify(baseUpgradeParams)));
let getPlaceholder = ref('');
let getPlaceholder1 = ref('');
function setPlaceHolder(key: string, p: any) {
  if (key === 'ImageURI') {
    getPlaceholder.value = p[key] === SPECIALS_STR ? SPECIALS_STR : '';
    p[key] = '';
  }
  if (key === 'SignalURI') {
    getPlaceholder1.value = p[key] === SPECIALS_STR ? SPECIALS_STR : '';
    p[key] = '';
  }
}
watch(
  () => props.templateData,
  newVal => {
    let params = newVal;
    if (JSON.stringify(newVal) === '{}') {
      params = baseUpgradeParams;
    }
    for (let key in params) {
      if (basicParams.hasOwnProperty(key)) {
        setPlaceHolder(key, params);
        basicParams[key] = params[key];
        oldData[key] = params[key];
        resetControlValue(key, params[key]);
      }
    }
  },
);

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({
  ImageURI: false,
  SignalURI: false,
  ImageType: false,
  Parameter: false,
  UpgradeMode: false,
  ActiveMethod: 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', changeData);
  return !(!status && formValidateStatus);
});
function setEmitData(data: any) {
  let tmpData = JSON.parse(JSON.stringify(data));
  let parameter = '';
  if (tmpData.Parameter.length > 0) {
    parameter = tmpData.Parameter[0]
  }
  if (tmpData.ImageURI === '' && getPlaceholder.value === SPECIALS_STR) {
    delete tmpData.ImageURI;
  }
  if (tmpData.SignalURI === '' && getPlaceholder1.value === SPECIALS_STR) {
    delete tmpData.SignalURI;
  }
  tmpData.Parameter = parameter;
  return tmpData;
}

const formRules = reactive({
  ImageURI: {
    id: 'ImageURI',
    type: 'string',
    required: false,
    matchRule: URI_PATTERN_STRING,
    validator: strVerification,
    message: traduction('SP_URI_RULE'),
    trigger: 'change',
  },
  SignalURI: {
    id: 'SignalURI',
    type: 'string',
    required: false,
    matchRule: URI_PATTERN_STRING,
    validator: strVerification,
    message: traduction('SP_URI_RULE'),
    trigger: 'change',
  },
});

const basicTips = reactive({
  ImageURI: traduction('SP_INPUT_COMMON', { key: traduction('SP_URI_RULE')}),
  SignalURI: traduction('SP_INPUT_COMMON', { key: traduction('SP_URI_RULE')}),
});

const parameterList = ref(['all']);
const ImageTypeList = ref(<any>[]);
const UpgradeModeList = ref(<any>[]);
const ActiveMethodList = ref(<any>[]);
const IMAGE_TYPES = ['Firmware', 'SP'];
const UPGRADE_MODE = ['Auto', 'Recover'];
const ACTIVE_METHOD = ['Immediately', 'RestartOS', 'RestartServer', 'PowerCycle'];

onMounted(() => {
  IMAGE_TYPES.forEach(o => {
    ImageTypeList.value.push({ label: o, key: o });
  });
  UPGRADE_MODE.forEach(o => {
    UpgradeModeList.value.push({ label: o, key: o });
  });
  ACTIVE_METHOD.forEach(o => {
    ActiveMethodList.value.push({ label: o, key: o });
  });
});

</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"
            >
              {{ 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('UPGRADE_FILE_PATH')" prop="ImageURI">
          <el-popover
            :content="basicTips.ImageURI"
            :visible="basicPoperState.ImageURI"
            :teleported="false"
            popper-class="wrap-popper"
            placement="right"
            trigger="focus"
            trigger-keys
          >
            <template #reference>
              <el-input
                id="basicImageURI"
                v-model="basicParams.ImageURI"
                v-clearable
                clearable
                type="password"
                :disabled="disabled"
                :placeholder="getPlaceholder || $t('COMMON_INPUT_TEXT')"
                @input="resetControlValue('ImageURI', $event)"
                @focus="togglePopper('ImageURI', true)"
                @blur="togglePopper('ImageURI', false)"
              >
                <template #suffix>
                  <ErrorIcon />
                  <ClearableIcon />
                </template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item>
        
        <el-form-item :label="$t('AUTHENTICATION_FILE_PATH')" prop="SignalURI">
          <el-popover
            :content="basicTips.SignalURI"
            :visible="basicPoperState.SignalURI"
            :teleported="false"
            popper-class="wrap-popper"
            placement="right"
            trigger="focus"
            trigger-keys
          >
            <template #reference>
              <el-input
                id="basicSignalURI"
                v-model="basicParams.SignalURI"
                v-clearable
                clearable
                type="password"
                :disabled="disabled"
                :placeholder="getPlaceholder1 || $t('COMMON_INPUT_TEXT')"
                @input="resetControlValue('SignalURI', $event)"
                @focus="togglePopper('SignalURI', true)"
                @blur="togglePopper('SignalURI', false)"
              >
                <template #suffix>
                  <ErrorIcon />
                  <ClearableIcon />
                </template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item>

        <el-form-item :label="$t('IMAGE_TYPE')" prop="ImageType">
          <el-select
            v-model="basicParams.ImageType"
            v-addId.select="'ImageType'"
            :teleported="false"
            :disabled="disabled"
            :suffix-icon="IconCaretDown"
          >
            <el-option
              v-for="item in ImageTypeList"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item :label="$t('ATTACHED_PARAMETER')" class="item have-warn-item" prop="Parameter">
          <el-checkbox-group v-model="basicParams.Parameter">
            <el-checkbox
              v-for="(item, index) in parameterList"
              :id="item"
              :key="index"
              :disabled="disabled"
              :label="item"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item :label="$t('UPGRADE_MODE')" prop="UpgradeMode">
          <el-select
            v-model="basicParams.UpgradeMode"
            v-addId.select="'UpgradeMode'"
            :teleported="false"
            :disabled="disabled"
            :suffix-icon="IconCaretDown"
          >
            <el-option
              v-for="item in UpgradeModeList"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item :label="$t('VALIDATION_METHOD')" prop="ActiveMethod">
          <el-select
            v-model="basicParams.ActiveMethod"
            v-addId.select="'ActiveMethod'"
            :teleported="false"
            :disabled="disabled"
            :suffix-icon="IconCaretDown"
          >
            <el-option
              v-for="item in ActiveMethodList"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </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);
    }
  }
}
.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;
}
: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>