<template>
  <h-modal
    v-model:visible="modalVisible"
    :width="600"
    :title="t('queryConfiguration.common.dbmodalTitleSec')"
    :maskClosable="false"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
  >
    <div class="map-item" v-for="item in formValue" :key="item.key">
      <h-col style="line-height: 30px; margin-bottom: 6px">{{ item.label }}=</h-col>
      <h-row
        v-for="(row, index) in item.value"
        class="fixHeight"
        :gutter="4"
        style="margin-bottom: 16px"
      >
        <h-col v-if="index > 0" style="width: 100px">
          <h-select
            style="width: 96px"
            :placeholder="t('queryConfiguration.common.splicePlaceholder')"
            v-model:value="row.splicer"
            showSearch
          >
            <h-select-option
              v-for="item in splicerEnum"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </h-select-option>
          </h-select>
        </h-col>
        <h-col style="flex: 1">
          <h-select
            style="width: 100%"
            :style="{ maxWidth: index > 0 ? '354px' : '454px' }"
            :placeholder="t('queryConfiguration.common.modalPlaceholder')"
            v-model:value="row.field"
            :filter-option="filterOption"
            showSearch
          >
            <h-select-option v-for="(item, key) in options" :label="item" :value="item" :key="key">
              {{ item }}
            </h-select-option>
          </h-select>
        </h-col>
        <div class="button-list">
          <h-button type="link" default @click="montage(item, row, index)">
            {{ t('queryConfiguration.common.splice') }}
          </h-button>
          <h-button type="link" danger @click="deleteRow(item, row, index)" v-if="index > 0">
            {{ t('queryConfiguration.common.delete') }}
          </h-button>
        </div>
      </h-row>
    </div>
  </h-modal>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
import { message } from '@crami/ui';
import { getInfo, ICP_CONFIG, useMonitorLang } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import useMonitorLang from '@/utils/hooks/useMonitorLang'; */
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useHttp, Http } from '@crami/http';
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: '',

  setup(_props, { emit }) {
    const { t } = useI18n();
    const modalVisible = ref(false);
    const options = ref([]);
    const confirmLoading = ref(false);
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    let eid;
    let config = {};

    const formValue = ref([
      {
        label: t('queryConfiguration.common.labelCode'),
        key: 'code',
        value: [],
      },
      {
        label: t('queryConfiguration.common.labelName'),
        key: 'name',
        value: [],
      },
      {
        label: t('queryConfiguration.common.labelVersion'),
        key: 'version',
        value: [],
      },
    ]);

    useMonitorLang(() => {
      formValue.value[0].label = t('queryConfiguration.common.labelCode');
      formValue.value[1].label = t('queryConfiguration.common.labelName');
      formValue.value[2].label = t('queryConfiguration.common.labelVersion');
    }, 300);

    const splicerEnum = ref([
      { label: '无', value: 'NULL' },
      { label: '、', value: '、' },
      { label: '·', value: '·' },
      { label: '-', value: '-' },
      { label: '.', value: '.' },
    ]);

    const showModal = (row, _config = {}) => {
      eid = row.EID;
      config = _config;
      initFormValue(row);
      getObjType(row);
      modalVisible.value = true;
    };

    // 解析数据生成formvalue需要的格式
    const initFormValue = info => {
      // js对象解构赋值设置默认值不能处理值为null的情况
      let {
        CODE_MAPPING_FIELDS: codeMappingFields,
        CODE_MAPPING_SPLICERS: codeMappingSplicers,
        NAME_MAPPING_FIELDS: nameMappingFields,
        NAME_MAPPING_SPLICERS: nameMappingSplicers,
        VERSION_MAPPING_FIELDS: versionMappingFields,
        VERSION_MAPPING_SPLICERS: versionMappingSplicers,
      } = info;
      codeMappingFields = (codeMappingFields || '').split(' ');
      !codeMappingFields[0] && (codeMappingFields[0] = undefined);
      (codeMappingSplicers = (codeMappingSplicers || '').split(' ')).unshift(undefined);
      nameMappingFields = (nameMappingFields || '').split(' ');
      !nameMappingFields[0] && (nameMappingFields[0] = undefined);
      (nameMappingSplicers = (nameMappingSplicers || '').split(' ')).unshift(undefined);
      versionMappingFields = (versionMappingFields || '').split(' ');
      !versionMappingFields[0] && (versionMappingFields[0] = undefined);
      (versionMappingSplicers = (versionMappingSplicers || '').split(' ')).unshift(undefined);

      formValue.value[0].value = [];
      formValue.value[1].value = [];
      formValue.value[2].value = [];

      codeMappingFields.forEach((item, index) => {
        formValue.value[0].value.push({
          field: item,
          splicer: codeMappingSplicers[index],
        });
      });
      nameMappingFields.forEach((item, index) => {
        formValue.value[1].value.push({
          field: item,
          splicer: nameMappingSplicers[index],
        });
      });
      versionMappingFields.forEach((item, index) => {
        formValue.value[2].value.push({
          field: item,
          splicer: versionMappingSplicers[index],
        });
      });
    };

    // 获取名称映射options
    const getObjType = async row => {
      const result = await Http.post({
        url: config.optionsApiUrl,
        params: {
          userId: commonParams.value?.userId,
          ...commonApi().system.getData.params,
          objectId: row.EID,
        },
      });
      const { data, code } = result;

      if (code == 200) {
        options.value = data;
      } else {
        message.error(result.msg);
      }
    };

    const montage = (item, _row, index) => {
      item.value.splice(index + 1, 0, { field: undefined, splicer: undefined });
    };

    const deleteRow = (item, _row, index) => {
      item.value.splice(index, 1);
    };

    const filterOption = (input: string, option: { label: string; value: string }) => {
      return option.label.indexOf(input) > -1;
    };

    // 名称映射 提交
    const handleOk = () => {
      saveNameMapping();
    };

    const validateForm = () => {
      const VERSION = 'version';

      for (let map of formValue.value) {
        if (VERSION === map.key) {
          for (let index in map.value) {
            const value = map.value[index];
            if (!value.field && value.splicer) {
              message.warning(
                t('queryConfiguration.common.blankTipDesc', {
                  type: map.label,
                  name: t('queryConfiguration.common.field'),
                }),
              );
              return;
            } else if (value.field && !value.splicer && index != 0) {
              message.warning(
                t('queryConfiguration.common.blankTipDesc', {
                  type: map.label,
                  name: t('queryConfiguration.common.splicer'),
                }),
              );
              return;
            } else {
            }
          }
        } else {
          if (!map.value || !map.value.length) {
            message.warning(t('queryConfiguration.common.selectTipSec', { type: map.label }));
            return;
          }
          for (let index in map.value) {
            const value = map.value[index];

            if (!value.field) {
              message.warning(
                t('queryConfiguration.common.blankTipDesc', {
                  type: map.label,
                  name: t('queryConfiguration.common.field'),
                }),
              );
              return;
            }
            if (!value.splicer && index != 0) {
              message.warning(
                t('queryConfiguration.common.blankTipDesc', {
                  type: map.label,
                  name: t('queryConfiguration.common.splicer'),
                }),
              );
              return;
            }
          }
        }
      }
      return true;
    };

    // 名称映射 提交请求
    const saveNameMapping = async () => {
      if (!validateForm()) return;

      confirmLoading.value = true;

      const codeMappingFields = formValue.value[0].value.map(item => item.field).join(' ');
      const codeMappingSplicers = formValue.value[0].value
        .map(item => item.splicer)
        .slice(1)
        .join(' ');
      const nameMappingFields = formValue.value[1].value.map(item => item.field).join(' ');
      const nameMappingSplicers = formValue.value[1].value
        .map(item => item.splicer)
        .slice(1)
        .join(' ');

      const versionValue = formValue.value[2].value.filter((item, index) => {
        return index == '0' ? !!item.field : !!item.field && !!item.splicer;
      });
      const versionMappingFields = versionValue.map(item => item.field).join(' ');
      const versionMappingSplicers = versionValue
        .map(item => item.splicer)
        .filter(item => item)
        .join(' ');

      let params = {
        userId: commonParams.value?.user_id,
        data: {
          eid,
          codeMappingFields,
          codeMappingSplicers,
          nameMappingFields,
          nameMappingSplicers,
          versionMappingFields,
          versionMappingSplicers,
        },
        ...commonApi().system.getData.params,
      };
      const result = await useHttp({
        url: config.saveApiUrl,
        method: 'post',
        params,
      });
      confirmLoading.value = false;
      if (result.code == 200) {
        message.success(result.msg);
        modalVisible.value = false;
        emit('refreshTable');
      } else {
        message.error(result.msg);
      }
    };

    return {
      t,
      modalVisible,
      confirmLoading,
      formValue,
      options,
      splicerEnum,
      showModal,
      filterOption,
      montage,
      deleteRow,
      handleOk,
      saveNameMapping,
    };
  },
});
</script>

<style lang="less" scoped>
.fixHeight {
  margin-bottom: 190px;
  display: flex;
  align-items: center;
}

.button-list {
  width: 98px;
  .ant-btn {
    padding: 0 6px;
  }
}
</style>
