<script lang="ts">
// @ts-nocheck
import { costylForTicketsVisitTime } from '@utils/format-date';
import { ServiceApi } from '@openapi/registry-service';
import { DocumentApi } from '@openapi/document-registry';
import { notifyError } from '@utils/notify';

const serviceApi = new ServiceApi();
const documentApi = new DocumentApi();

export default {
  name: 'TicketObject',
  props: ['model', 'common'],
  data() {
    return {
      rawData: {
        bookId: null,
        esiaId: null,
        firstName: null,
        lastName: null,
        middleName: null,
        caseNumber: null,
        status: {
          statusCode: null,
          statusMessage: null,
        },
        timeSlot: {
          serviceId: null,
          slotId: null,
          visitTime: null,
          endVisitTime: null,
          organizationId: null,
        },
      },

      form: {
        bookId: null,
        esiaId: null,
        organization: null,
        statusMessage: null,
        statusIcon: null,
        service: null,
        caseNumber: null,
        visitTime: null,
        endVisitTime: null,
        firstName: null,
        lastName: null,
        middleName: null,
      },

      service: null,

      statusMap: {
        201: { icon: 'access_time', color: 'primary' },
        401: { icon: 'done_all', color: 'primary', isFinal: true },
        301: { icon: 'remove_circle_outline', color: 'primary', isFinal: true },
      },
    };
  },
  computed: {
    title() {
      return this.$tc('tickets.label') + ' ' + this.form.caseNumber;
    },
    isStatusFinal() {
      return this.statusMap[this.rawData.status.statusCode]
        ? this.statusMap[this.rawData.status.statusCode].isFinal
        : false;
    },
  },
  async beforeMount() {
    try {
      this.$q.loading.show();
      const ticket = await this.$store.dispatch(
        'ticketsService/tickets/fetchTicket',
        {
          id: this.common.id,
          useAuth: true,
        }
      );

      try {
        const serviceMatch = await serviceApi
          .pagingService(1, 5, `(tnsTargetId==${ticket.timeSlot?.serviceId})`)
          .then(({ data }) => data?.records || []);
        this.service = serviceMatch[0];
      } catch (e) {
        // ignore
      }

      this.updateTicketForm(ticket, this.service);
    } catch (e) {
      console.error(e);
      notifyError(e.message.toString());
    } finally {
      this.$q.loading.hide();
    }
  },
  methods: {
    async updateStatus(statusCode) {
      try {
        this.$q.loading.show();
        const rawData = await this.$store.dispatch(
          'ticketsService/tickets/updateTicketStatus',
          {
            id: this.rawData.bookId,
            statusCode,
            useAuth: true,
          }
        );
        this.updateTicketForm(rawData, this.service);
      } catch (e) {
        console.error(e);
      } finally {
        this.$q.loading.hide();
      }
    },

    async goToStatement(caseNumber) {
      try {
        this.$q.loading.show();
        const { data: statementsList } = await documentApi.pagingDocuments(
          'Applications',
          1,
          5,
          `(common.orderId==${caseNumber})`
        );

        if (statementsList.totalRows === 1) {
          const { id } = statementsList.records[0];
          this.$router.push({
            name: 'cards',
            params: {
              id,
              path: 'statements',
            },
            query: {
              active: 'author',
              components: this.$store.getters[
                'cardComponents/statements/components'
              ],
            },
          });
        } else if (statementsList.totalRows > 1) {
          notifyError(this.$tc('tickets.errors.tooManyPetitions'));
        } else {
          notifyError(this.$tc('tickets.errors.noPetitions'));
        }
      } catch (e) {
        console.error(e);
        notifyError(e.message.toString());
      } finally {
        this.$q.loading.hide();
      }
    },

    mapForm(ticket, service) {
      return {
        bookId: ticket.bookId,
        esiaId: ticket.esiaId,
        organization: ticket.timeSlot.organizationId,
        statusMessage: ticket.status.statusMessage,
        statusIcon: this.getStatusIcon(ticket.status.statusCode),
        service: service?.fullName ?? this.$tc('tickets.errors.noService'),
        caseNumber: ticket.caseNumber,
        visitTime: this.formatDatetime(ticket.timeSlot?.visitTime),
        endVisitTime: this.formatDatetime(ticket.timeSlot?.endVisitTime),
        firstName: ticket.firstName,
        lastName: ticket.lastName,
        middleName: ticket.middleName,
      };
    },

    updateTicketForm(rawData, service) {
      this.$set(this, 'rawData', rawData);
      this.$set(this, 'form', this.mapForm(rawData, service));
      // this.getServiceByTnsTargetId(rawData.)
      this.$forceUpdate();
    },

    formatDatetime(date) {
      // todo заменить на convertDateFromBackendFormat когда починят дату на сервере
      return costylForTicketsVisitTime(date);
    },

    getStatusIcon(statusCode) {
      const icon = this.statusMap[statusCode]?.icon;
      return icon ?? 'help_online';
    },

    async getServiceByTnsTargetId(tnsTargetId) {
      try {
        this.$q.loading.show();
        const servicesList = await serviceApi
          .pagingService(1, 5, `(tnsTargetId==${tnsTargetId})`)
          .then(({ data }) => data);

        if (servicesList.totalRows === 1) {
          // todo test 'statementsList' changed to 'servicesList'
          const { id } = servicesList.records[0];
          this.$router.push({
            name: 'cards',
            params: {
              id,
              path: 'statements',
            },
            query: {
              active: 'author',
              components: this.$store.getters[
                'cardComponents/statements/components'
              ],
            },
          });
        } else if (servicesList.totalRows > 1) {
          notifyError(this.$tc('tickets.errors.tooManyPetitions'));
        } else {
          notifyError(this.$tc('tickets.errors.noPetitions'));
        }
      } catch (e) {
        console.error(e);
        notifyError(e.message.toString());
      } finally {
        this.$q.loading.hide();
      }
    },
  },
};
</script>

<template>
  <div class="q-pa-md q-gutter-y-md">
    <div
      class="flex justify-between items-center bg-white q-pa-md rounded-borders"
    >
      <div
        :key="form.caseNumber"
        class="column justify-center text-h5"
        style="min-height: 36px"
      >
        {{ title }}
      </div>
      <div v-if="!isStatusFinal">
        <q-btn
          label="Завершить"
          outline
          color="positive"
          @click="updateStatus('401')"
        />
        <q-btn
          label="Не явился"
          outline
          color="negative"
          @click="updateStatus('301')"
        />
      </div>
    </div>
    <div class="bg-white rounded-borders row">
      <div class="row col-8">
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ $t('tickets.form.status') }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section avatar>
              <q-avatar rounded text-color="priamry" :icon="form.statusIcon" />
            </q-item-section>
            <q-item-section>
              <q-item-label>
                {{ form.statusMessage }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ $t('tickets.form.serviceId') }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ form.service }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <template v-if="form.caseNumber">
          <div class="col-6">
            <q-item>
              <q-item-section>
                <q-item-label>
                  {{ $t('tickets.form.statement') }}
                </q-item-label>
              </q-item-section>
            </q-item>
          </div>
          <div class="col-6">
            <q-item>
              <q-item-section>
                <q-item-label>
                  <q-chip
                    clickable
                    class="q-ma-none"
                    @click="goToStatement(form.caseNumber)"
                  >
                    {{ form.caseNumber }}
                  </q-chip>
                </q-item-label>
              </q-item-section>
            </q-item>
          </div>
        </template>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ $t('tickets.form.lastName') }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ form.lastName }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ $t('tickets.form.firstName') }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ form.firstName }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ $t('tickets.form.middleName') }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ form.middleName }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ $t('tickets.form.visitTime') }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ form.visitTime }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ $t('tickets.form.endVisitTime') }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
        <div class="col-6">
          <q-item>
            <q-item-section>
              <q-item-label>
                {{ form.endVisitTime }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </div>
      </div>
    </div>
  </div>
</template>
