<template>
  <Table
    :columns="columns"
    :data="data"
    class="survey-translation-table"
    row-key="tempId"
    stripe
  >
    <template slot="type" slot-scope="{ row }">
      <span class="ml-base" v-if="row.type == SUB_QUESTION_TYPE">{{
        t("survey_creator.question.sub_questions")
      }}</span>
      <span v-else-if="row.type">{{
        t(`survey_creator.question.types.${row.type}`)
      }}</span>
      <span class="ml-base" v-else>{{
        t("survey_creator.question.optional")
      }}</span>
    </template>
    <template slot="primaryLanguage" slot-scope="{ row }">
      <span v-if="row.number"
        >{{ row.number }}.
        {{ row.text | translate(primaryLanguage, true) }}</span
      >
      <span v-else>{{ row.text | translate(primaryLanguage, true) }}</span>
    </template>
    <template
      :slot="language"
      slot-scope="{ row }"
      v-for="language in camelLanguages"
    >
      <Input
        :autosize="{ minRows: 2, maxRows: 2 }"
        @on-change="onChange(row)"
        type="textarea"
        v-model="row.text[language]"
        :key="language"
      />
    </template>
  </Table>
</template>

<script lang="ts">
import Vue from "vue";
import _ from "lodash";
import LocaleMixin from "../../mixins/locale-mixin";
import SurveyTranslatorMixin from "../../mixins/survey-translator-mixin";
import { Input, Table } from "view-design";

export default Vue.extend({
  name: "translation-table",
  components: { Input, Table },
  props: ["value", "languages", "primaryLanguage"],
  mixins: [LocaleMixin, SurveyTranslatorMixin],
  inject: ["$rootComponent"],
  computed: {
    data() {
      return this.value;
    },
    camelLanguages() {
      return _.map(this.languages, (language) => _.camelCase(language));
    },
    columns() {
      let columns = [
        {
          title: this.t("survey_creator.translator.table.header_type"),
          slot: "type",
          tree: true,
        },
        {
          title:
            this.t(
              `survey_creator.translator.table.header_${_.camelCase(
                this.primaryLanguage
              )}`
            ) + this.t("survey_creator.translator.table.header_primary_name"),
          slot: "primaryLanguage",
        },
      ];
      _.forEach(
        _.map(this.languages, (language) => _.camelCase(language)),
        (language) => {
          columns.push({
            title: this.t(`survey_creator.translator.table.header_${language}`),
            slot: language,
          });
        }
      );
      return columns;
    },
  },
  methods: {
    onChange(row) {
      // @ts-ignore
      _.merge(this.buildDataMap(this.data)[row.tempId], row);
    },
  },
});
</script>
<style lang="less" scoped>
.survey-translation-table {
  /deep/ .ivu-icon {
    font-size: 14px;
  }

  /deep/ .ivu-table-cell-slot {
    display: inline;
  }
}
</style>
