<template>
  <w-grid
    ref="gridRef"
    :title="$t('standard.country.grid.title')"
    :hide-bottom="false"
    :config-button="true"
    selection="multiple"
    :checkbox-selection="true"
    :tree="false"
    primary-key="code"
    :data-url="Environment.apiContextPath('/api/standard/country')"
    :pageable="false"
    :sort-by="['codeLatin3']"
    :toolbar-configure="{ noIcon: false }"
    :toolbar-actions="['query', 'refresh', 'separator', 'add', 'edit', 'remove', 'separator', 'view', 'separator', 'export']"
    :query-form-cols-num="5"
    :query-form-fields="[
      { name: 'code', label: $t('standard.country.entity.code'), type: 'text', clearable: true },
      { name: 'codeLatin3', label: $t('standard.country.entity.codeLatin3'), type: 'text', clearable: true },
      { name: 'nameChinese', label: $t('standard.country.entity.nameChinese'), type: 'text', clearable: true },
      { name: 'nameEnglish', label: $t('standard.country.entity.nameEnglish'), type: 'text', clearable: true },
    ]"
    :columns="columnsComputed"
    :editor="{
      dialog: {
        width: '800px',
      },
      form: {
        colsNum: 3,
        fields: [
          { name: 'code', label: $t('standard.country.entity.code'), type: 'text', required: true },
          { name: 'codeLatin2', label: $t('standard.country.entity.codeLatin2'), type: 'text', required: true },
          { name: 'codeLatin3', label: $t('standard.country.entity.codeLatin3'), type: 'text', required: true },
          { name: 'nameChinese', label: $t('standard.country.entity.nameChinese'), type: 'text', required: true },
          { name: 'nameChineseFull', label: $t('standard.country.entity.nameChineseFull'), type: 'text', colSpan: 2 },
          { name: 'remarkChinese', label: $t('standard.country.entity.remarkChinese'), type: 'text', colSpan: 3 },
          { name: 'nameEnglish', label: $t('standard.country.entity.nameEnglish'), type: 'text', required: true },
          { name: 'nameEnglishFull', label: $t('standard.country.entity.nameEnglishFull'), type: 'text', colSpan: 2 },
          { name: 'remarkEnglish', label: $t('standard.country.entity.remarkEnglish'), type: 'text', colSpan: 3 },
          { name: 'nameLocalShort', label: $t('standard.country.entity.nameLocalShort'), type: 'text', colSpan: 2 },
          { name: 'isIndependent', label: $t('standard.country.entity.isIndependent'), type: 'select', options: Options.yesNo() },
          {
            name: 'currency',
            label: $t('standard.country.entity.currency'),
            type: 'select',
            options: currencyOptionsRef,
            colSpan: 2,
            useInput: true,
            hideSelected: true,
            fillInput: true,
            onFilter: (val, update) => {
              if (val) {
                update(() => {
                  const input = val.toUpperCase();
                  const currencyOptions = [];
                  for (const currency of currencyList) {
                    if (
                      currency.code?.indexOf(input) > -1 ||
                      currency.codeLatin?.indexOf(input) > -1 ||
                      currency.nameChinese?.indexOf(input) > -1 ||
                      currency.nameEnglish?.indexOf(input) > -1
                    ) {
                      const item = createCurrencyOptionItem(currency);
                      if (item) {
                        currencyOptions.push(item);
                      }
                    }
                  }
                  currencyOptionsRef = currencyOptions;
                });
              } else {
                update(() => {
                  const currencyOptions = [];
                  for (const currency of currencyList) {
                    const item = createCurrencyOptionItem(currency);
                    if (item) {
                      currencyOptions.push(item);
                    }
                  }
                  currencyOptionsRef = currencyOptions;
                });
              }
            },
          },
          { name: 'languageCode2', label: $t('standard.country.entity.languageCode2'), type: 'text', colsFirst: true },
          { name: 'languageCode3', label: $t('standard.country.entity.languageCode3'), type: 'text' },
        ],
      },
    }"
    :viewer="{
      panel: {
        columnNum: 1,
        fields: [
          { name: 'code', label: $t('standard.country.entity.code') },
          { name: 'codeLatin2', label: $t('standard.country.entity.codeLatin2') },
          { name: 'codeLatin3', label: $t('standard.country.entity.codeLatin3') },
          { name: 'nameChinese', label: $t('standard.country.entity.nameChinese') },
          { name: 'nameChineseFull', label: $t('standard.country.entity.nameChineseFull') },
          { name: 'nameEnglish', label: $t('standard.country.entity.nameEnglish') },
          { name: 'nameEnglishFull', label: $t('standard.country.entity.nameEnglishFull') },
          { name: 'nameLocalShort', label: $t('standard.country.entity.nameLocalShort') },
          { name: 'remarkChinese', label: $t('standard.country.entity.remarkChinese') },
          { name: 'remarkEnglish', label: $t('standard.country.entity.remarkEnglish') },
          { name: 'languageCode2', label: $t('standard.country.entity.languageCode2') },
          { name: 'languageCode3', label: $t('standard.country.entity.languageCode3') },
          { name: 'isIndependent', label: $t('standard.country.entity.isIndependent') },
          {
            name: 'currency',
            label: $t('standard.country.entity.currency'),
            format: (value, row) => {
              return getCurrencyLabel(currencyMap[row.currency]);
            },
          },

          { name: 'dataComeFrom', label: $t('dataComeFrom') },
          { name: 'creator', label: $t('creator') },
          { name: 'createDate', label: $t('createDate') },
          { name: 'lastModifier', label: $t('lastModifier') },
          { name: 'lastModifyDate', label: $t('lastModifyDate'), format: Formater.none() },
        ],
      },
    }"
  ></w-grid>
</template>
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { axios, Environment, Formater, Options, eventBus } from 'platform-core';

let currentLocale = Environment.getConfigure().setting.i18n.locale;
let currencyMap = {};
let currencyList = [];
const { t } = useI18n();
const currencyOptionsRef = ref([]);
const columnsRef = ref([
  { width: 70, name: 'code', label: t('code') },
  { width: 70, name: 'codeLatin3', label: t('code') + '3' },
  {
    width: 150,
    name: 'nameChinese',
    label: t('name'),
    format: (value, row) => {
      if (row) {
        return getCountryName(row);
      }
    },
  },
  {
    name: 'currency',
    label: t('standard.entity.currency'),
    columns: [
      {
        width: 70,
        name: 'currencyCode',
        label: t('code'),
        sortable: false,
        format: (value, row) => {
          if (row.currency) {
            return currencyMap[row.currency]?.code;
          }
        },
      },
      {
        width: 70,
        name: 'currencyCodeLatin',
        label: t('code') + '2',
        sortable: false,
        format: (value, row) => {
          if (row.currency) {
            return currencyMap[row.currency]?.codeLatin;
          }
        },
      },
      {
        width: 150,
        name: 'currencyname',
        label: t('name'),
        sortable: false,
        format: (value, row) => {
          if (row.currency) {
            return getCurrencyName(currencyMap[row.currency]);
          }
        },
      },
    ],
  },
  {
    name: 'language',
    label: t('standard.entity.language'),
    columns: [{ width: 100, name: 'languageCode3', label: t('code') }],
  },

  { width: 100, name: 'lastModifier', label: t('lastModifier') },
  { width: 120, name: 'lastModifyDate', label: t('lastModifyDate'), format: Formater.dateOnly() },
]);

const columnsComputed = computed(() => {
  const result = [
    { width: 70, name: 'code', label: t('code') },
    { width: 70, name: 'codeLatin3', label: t('code') + '3' },
    {
      width: 150,
      name: 'nameChinese',
      label: t('name'),
      format: (value, row) => {
        if (row) {
          return getCountryName(row);
        }
      },
    },
    {
      name: 'currency',
      label: t('standard.entity.currency'),
      columns: [
        {
          width: 70,
          name: 'currencyCode',
          label: t('code'),
          sortable: false,
          format: (value, row) => {
            if (row.currency) {
              return currencyMap[row.currency]?.code;
            }
          },
        },
        {
          width: 70,
          name: 'currencyCodeLatin',
          label: t('code') + '2',
          sortable: false,
          format: (value, row) => {
            if (row.currency) {
              return currencyMap[row.currency]?.codeLatin;
            }
          },
        },
        {
          width: 150,
          name: 'currencyname',
          label: t('name'),
          sortable: false,
          format: (value, row) => {
            if (row.currency) {
              return getCurrencyName(currencyMap[row.currency]);
            }
          },
        },
      ],
    },
    {
      name: 'language',
      label: t('standard.entity.language'),
      columns: [{ width: 100, name: 'languageCode3', label: t('code') }],
    },

    { width: 100, name: 'lastModifier', label: t('lastModifier') },
    { width: 120, name: 'lastModifyDate', label: t('lastModifyDate'), format: Formater.dateOnly() },
  ];

  if (Environment.getConfigure().setting.i18n.locale === 'zh_CN') {
    result[2].name = 'nameChinese';
  } else {
    result[2].name = 'nameEnglish';
  }
  return result;
});

eventBus.on('localeChanged', (locale) => {
  currentLocale = locale;
  if (locale === 'zh_CN') {
    columnsRef.value.slice(2, 1, {
      width: 200,
      name: 'nameChinese',
      label: t('name'),
      format: (value, row) => {
        if (row) {
          return getCountryName(row);
        }
      },
    });
  } else {
    columnsRef.value.slice(2, 1, {
      width: 200,
      name: 'nameEnglish',
      label: t('name'),
      format: (value, row) => {
        if (row) {
          return getCountryName(row);
        }
      },
    });
  }
});

onMounted(() => {
  axios.get(Environment.apiContextPath('/api/standard/currency?pageable=false&sortBy=code')).then((response) => {
    currencyMap = {};
    currencyList = [];
    const currencyOptions = [];
    if (response?.data?.content) {
      for (const currency of response.data.content) {
        currencyMap[currency.code] = currency;
        currencyList.push(currency);
      }

      for (const currency of currencyList) {
        const item = createCurrencyOptionItem(currency);
        if (item) {
          currencyOptions.push(item);
        }
      }
    }
    currencyOptionsRef.value = currencyOptions;
  });
});

const getCurrencyLabel = (currency) => {
  return currency.code + ' ' + currency.codeLatin + ' ' + (currentLocale === 'zh_CN' ? currency.nameChinese : currency.nameEnglish);
};

const createCurrencyOptionItem = (currency) => {
  if (currency) {
    return {
      value: currency.code,
      label: getCurrencyLabel(currency),
    };
  }
  return null;
};

const getCountryName = (country) => {
  if (country) {
    return currentLocale === 'zh_CN' ? country.nameChinese : country.nameEnglish;
  }
  return null;
};

const getCurrencyName = (currency) => {
  if (currency) {
    return currentLocale === 'zh_CN' ? currency.nameChinese : currency.nameEnglish;
  }
  return null;
};
</script>
