<i18n>
{
  "en": {
    "ChecksCard": {
      "noChecksResult": "No checks result",
      "userCheck": "Before making a decision, it is necessary to check the compliance of a separate document or information according to the specified criterion. Automatic checks carried out by the system.",
      "null": ""
    }
  },
  "ru": {
    "ChecksCard": {
      "noChecksResult": "Нет результата по проверкам",
      "userCheck": "Перед вынесением решения необходимо осуществить проверку соответствия отдельного документа или сведения по указанному критерию. Автоматические проверки осуществлены системой.",
      "null": ""
    }
  }
}
</i18n>

<template>
  <div class="row q-pa-md justify-center" v-if="common.active === 'checks'">
    <div class="col-12 max-1280-width">
      <template v-if="model && recommendation && (checkList || tableChecks)">
        <q-expansion-item
          v-if="rejectBanner"
          :default-opened="expanded"
          class="text-grey-7"
          style="border: 1px solid red"
        >
          <template slot="header">
            <div
              :class="{ 'q-pl-sm': !expanded }"
              class="full-width flex items-center"
            >
              {{ $t('statements.dmn') }}:<span
                style="white-space: pre"
                class="text-black"
              >
                {{ $t('statements.decline') }}</span
              >
            </div>
          </template>
          <q-card>
            <q-card-section
              v-if="
                get(this.model, 'decisionData.recommendation.description') &&
                !get(recommendation, 'rejection')
              "
            >
              <div>
                {{ $t('statements.reason') }}:
                <span class="text-black">{{
                  model.recommendation.description
                }}</span>
              </div>
            </q-card-section>
            <q-card-section v-else-if="get(recommendation, 'rejection')">
              <template>
                <div
                  v-for="(rec, i) in recommendation.rejection"
                  :key="`${rec.reason}_${i}`"
                  :class="{
                    'bordered-divider': !expanded,
                    'q-pl-sm': !expanded,
                  }"
                  class="q-mt-sm"
                >
                  <div v-if="rec.reason">
                    {{ $t('statements.reason') }}:
                    <span class="text-black">{{ rec.reason }}</span>
                  </div>
                  <div v-if="rec.explanation">
                    {{ $t('statements.explanation') }}:
                    <span class="text-black">{{ rec.explanation }}</span>
                  </div>
                </div>
              </template>
            </q-card-section>
          </q-card>
        </q-expansion-item>
        <q-banner
          v-if="acceptBanner"
          class="text-grey-7"
          style="border: 1px solid green"
        >
          <div>
            {{ $t('statements.dmn') }}:
            <span class="text-black">{{ $t('statements.accept') }}</span>
          </div>
        </q-banner>
      </template>
      <template v-if="manualVerificationsBanner">
        <q-banner class="q-py-md yellow-banner" rounded>
          <div>{{ $t('ChecksCard.userCheck') }}</div>
        </q-banner>
      </template>
      <base-decision-table
        class="Checks-Table"
        v-if="checkList"
        :check-list="checkList"
        :corrections="corrections"
      />
      <base-checks-table
        class="Checks-Table"
        v-if="tableChecks && !this.checkList"
        :table-checks="tableChecks"
        :table-mode="tableMode"
        :model="model"
        :common="common"
        :service="serviceCard"
        @commonModels="commonModels"
      />
      <div v-if="noChecks" class="full-width text-center">
        {{ $t('ChecksCard.noChecksResult') }}
      </div>
    </div>
    <template v-for="(name, i) in componentNames">
      <component
        :is="components[name]"
        v-if="!isEmpty(components[name])"
        :key="i"
        :common="common"
        :model="model"
        :user-task="userTask"
        @commonModels="commonModels"
      />
    </template>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import isArray from 'lodash/isArray';

export default {
  props: ['common', 'model', 'userTask'],

  data() {
    return {
      components: {},
      componentNames: ['correction_dialog_single', 'linked_objects_dialog'],
      userChecksColumns: [
        {
          label: this.$t('base.checkboxTable.docColumnTitle'),
          name: 'document',
          headerStyle: 'min-width: 200px',
        },
        {
          label: this.$t('base.checkboxTable.resColumnTitle'),
          name: 'result',
        },
      ],
    };
  },

  computed: {
    serviceCard() {
      return this.$store.getters['registryService/services/servicesCard'];
    },
    manualVerificationsBanner() {
      const manualVerificationsIsAdded = get(
        this.userTask,
        'userTask.outData.manualVerificationsIsAdded',
        null
      );
      const checkListIsMandatory = get(
        this.userTask,
        'userTask.outData.checkListIsMandatory'
      );
      const manualVerificationExist = get(
        this.model,
        'decisionData.manualVerificationExist',
        null
      );

      return (
        !manualVerificationsIsAdded &&
        !this.checkList &&
        checkListIsMandatory &&
        manualVerificationExist
      );
    },
    acceptBanner() {
      const manualVerificationsIsAdded = get(
        this.userTask,
        'userTask.outData.manualVerificationsIsAdded',
        null
      );
      const manualVerificationExist = get(
        this.model,
        'decisionData.manualVerificationExist',
        null
      );
      const decisionIsAccept =
        get(this.recommendation, 'decision') === 'Accept';

      return (
        (manualVerificationsIsAdded || !manualVerificationExist) &&
        decisionIsAccept
      );
    },
    hasUncheckedVerifications() {
      const checked: string[] = this.tableChecks?.objects.reduce(
        (acc: string[], obj: { verifications?: { key: string } }) => {
          return [
            ...acc,
            ...Object.keys(obj.verifications || {}).map((key: string) => {
              return key;
            }),
          ];
      }, []);

      const checks = [];
      this.tableChecks?.groups.forEach((g: any) => {
        g.verifications.forEach((obj: { code: string }) => {
          checks.push(obj.code);
        });
      });
      const diff = checks.filter(x => !checked.includes(x));
      return !!diff.length;
    },
    rejectBanner() {
      const manualVerificationsIsAdded = get(
        this.userTask,
        'userTask.outData.manualVerificationsIsAdded',
        null
      );
      const manualVerificationExist = get(
        this.model,
        'decisionData.manualVerificationExist',
        null
      );
      const decisionIsReject =
        get(this.recommendation, 'decision') === 'Reject';

      return (
        (manualVerificationsIsAdded || !manualVerificationExist) &&
        decisionIsReject
      );
    },
    expanded() {
      const rejection = get(this.recommendation, 'rejection');
      return !(Array.isArray(rejection) && rejection.length > 1);
    },
    noChecks() {
      return !this.checkList && !this.tableChecks;
    },
    tableChecks() {
      if (this.tableObjects && this.tableGroups) {
        return {
          objects: this.tableObjects,
          groups: this.tableGroups,
        };
      } else {
        return null;
      }
    },
    checkList() {
      if (
        get(this.model, 'checkList') &&
        typeof get(this.model, 'checkList') !== 'string'
      ) {
        return get(this.model, 'checkList');
      } else {
        return null;
      }
    },
    corrections() {
      if (get(this.model, 'decisionData.corrections')) {
        return get(this.model, 'decisionData.corrections');
      }
      return null;
    },
    isManualVerificationsAdded() {
      return get(this.userTask, 'userTask.defId') ===
        'MakeDecisionHiddenNewTask'
        ? get(
            this.userTask,
            'userTask.outData.manualVerificationsIsAdded',
            null
          )
        : true;
    },
    tableMode() {
      if (
        get(this.userTask, 'userTask.defId') === 'MakeDecisionHiddenNewTask'
      ) {
        return 'edit';
      }
      return 'default';
    },
    recommendation() {
      return get(this.model, 'decisionData.recommendation', null);
    },
    tableObjects() {
      if (
        get(this.model, 'decisionData.objects') &&
        isArray(get(this.model, 'decisionData.objects'))
      ) {
        // For sorting array without vuex mutation
        const objects = [...get(this.model, 'decisionData.objects')];
        return objects.sort((prev, next) => {
          return parseInt(prev.id) - parseInt(next.id);
        });
      } else {
        return null;
      }
    },
    tableGroups() {
      return get(this.model, 'decisionData.groups', null);
    },
  },
  mounted() {
    this.fetchComponents();
  },
  methods: {
    get,
    isEmpty,
    commonModels(val) {
      this.$emit('commonModels', val);
    },
    fetchComponents() {
      const componentsObj = this.components ? this.components : {};
      this.componentNames.forEach((name) => {
        // todo refactor
        if (!name || get(this.components, `${name}`)) return; // не выполняем загрузку, если нет pathComponent или уже загружено
        componentsObj[name] = {};
        this.$set(
          componentsObj,
          name,
          this.$GlobalComponentImporter.registerComponent(
            name,
            `cards/statements/`
          )
        );
      });
      this.components = componentsObj;
    },
  },
};
</script>

<style lang="scss">
.Checks {
  &-Table {
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 20px;
  }
}
</style>