// @ts-nocheck
import { Component, Prop } from 'vue-property-decorator';
import Checkbox from '../../Checkbox.vue';
import get from 'lodash/get';

@Component({})
export default class MDefense extends Checkbox {
  @Prop() specialIncomeCode: number;

  mounted() {
    this.$watch(`model.${this.fieldNode.name}`, (value) =>
      this.onChange(value)
    );

    if (this.specialIncomeCode === 13) {
      this.$watch('model.defenseINN', (inn) => this.onDefenseINNChange(inn));
    }
  }

  onChange(value: boolean): void {
    if (value) {
      const specialIncome = {
        IncomeSize: '',
        IncomeType: {
          code: this.specialIncomeCode,
        },
      };

      if (
        this.model.IncomeInfo?.IncomeType &&
        Array.isArray(this.model.IncomeInfo?.IncomeType) &&
        this.model.IncomeInfo?.IncomeType.findIndex(
          (income) => income.IncomeType.code === this.specialIncomeCode
        ) < 0
      ) {
        this.$set(this.model.IncomeInfo, 'IncomeType', [
          ...this.model.IncomeInfo.IncomeType,
          specialIncome,
        ]);
      } else {
        this.$set(this.model, 'IncomeInfo', {});
        this.$set(this.model.IncomeInfo, 'IncomeType', [specialIncome]);
      }
    } else {
      if (this.model.IncomeInfo?.IncomeType) {
        if (get(this.model, 'IncomeInfo.IncomeType.length') === 1) {
          this.$delete(this.model, 'IncomeInfo');
        } else {
          this.$set(
            this.model.IncomeInfo,
            'IncomeType',
            this.model.IncomeInfo.IncomeType.filter(
              (income) =>
                get(income, 'IncomeType.code') !== this.specialIncomeCode
            )
          );
        }
      }
    }
  }

  onDefenseINNChange(inn: string): void {
    const incomes = get(this.model, 'IncomeInfo.IncomeType');
    const income = incomes?.find(
      (incomeIT) => incomeIT.IncomeType.code === this.specialIncomeCode
    );

    if (!income) return;

    this.$set(income, 'IncomeSize', inn);
  }
}
