<template>
  <t-dialog
    v-model:visible="props.visible"
    header="JSON值"
    :width="470"
    @close="close"
    @confirm="confirm"
  >
    <t-tabs v-model="tabValue" @change="tabChange">
      <t-tab-panel :value="1" label="简单模式">
        <div class="mt-8">
          <div class="flex mt-4 one-data" v-for="(d, i) in simpleData">
            <t-select-input
              class="input-key"
              v-if="props.options?.length"
              placeholder="可自定义输入"
              v-model:inputValue="d.key"
              :value="d.keyLabel"
              v-model:popupVisible="d.keyPopupVisible"
              allow-input
              clearable
              @clear="d.keyLabel = undefined"
              @focus="d.keyPopupVisible = true"
              @blur="d.keyPopupVisible = false"
              @input-change="onKeyInput(d)"
            >
              <template #panel>
                <ul style="padding: 8px 12px">
                  <li
                    v-for="item in props.options"
                    :key="item.value"
                    @click="
                      d.key = item.value;
                      d.keyLabel = item.label;
                      d.keyPopupVisible = false;
                    "
                  >
                    {{ item.label }}
                  </li>
                </ul>
              </template>
            </t-select-input>
            <t-input v-else class="input-key" v-model="d.key" />
            <t-input class="input-value" v-model="d.value" />
            <div class="flex operation">
              <add-circle-icon class="hover ml-4" @click="addData(i)" />
              <minus-circle-icon class="hover ml-4" @click="delData(i)" />
            </div>
          </div>
        </div>
      </t-tab-panel>
      <t-tab-panel :value="2" label="JSON模式">
        <template #label>
          JSON模式
          <t-tooltip v-if="props.tips" :content="props.tips" placement="top">
            <HelpCircleIcon class="ml-4" />
          </t-tooltip>
        </template>
        <CodeEditor
          :key="codeUpdateKey"
          :json="true"
          :language="'json'"
          v-model="json"
          style="height: 300px"
        />
      </t-tab-panel>
    </t-tabs>
  </t-dialog>
</template>

<script lang="ts" setup>
import { ref, toRaw, onMounted, watch } from 'vue';
import CodeEditor from '@/views/components/common/CodeEditor.vue';
import {
  AddCircleIcon,
  MinusCircleIcon,
  HelpCircleIcon,
} from 'tdesign-icons-vue-next';
import { s8 } from '@/services/random';

const props = defineProps<{
  visible: boolean;
  data: any;
  options?: any[];
  tips?: string;
}>();
const emit = defineEmits(['update:visible', 'change']);
const activedProp = ref([]);

const simpleData = ref([]);

const json = ref({});
const codeUpdateKey = ref(s8());
watch(
  () => props.visible,
  () => {
    if (!props.data) {
      json.value = {};
      simpleData.value = [{ key: '', value: '' }];
    }
    json.value = JSON.parse(JSON.stringify(props.data));
    if (json.value && !Array.isArray(json.value)) {
      simpleData.value = objToArr(json.value);
    }
    if (!simpleData.value?.length) {
      simpleData.value = [{ key: '', value: '' }];
    }
    if (tabValue.value === 2) {
      codeUpdateKey.value = s8();
    }
  }
);

const tabChange = (val) => {
  if (val === 1) {
    simpleData.value = objToArr(json.value);
    if (!simpleData.value?.length) {
      simpleData.value.push({ key: '', value: '' });
    }
  } else if (val === 2) {
    json.value = arrToObj(simpleData.value);
  }
};

const addData = (index) => {
  simpleData.value.splice(index + 1, 0, { key: '', value: '' });
};

const delData = (index) => {
  if (index === 0) {
    simpleData.value[0].key = '';
    simpleData.value[0].value = '';
  } else {
    simpleData.value.splice(index, 1);
  }
};

function close() {
  emit('update:visible', false);
}

const tabValue = ref(1);

const arrToObj = (arr) => {
  return arr.reduce((accumulator, current) => {
    if (current.key) {
      accumulator[current.key] = current.value;
    }
    return accumulator;
  }, {});
};

const objToArr = (obj) => {
  return Object.entries(obj).map(([key, value]) => ({
    key: key,
    value: value,
    label: key,
    keyLabel: key,
  }));
};

const confirm = () => {
  if (tabValue.value === 1) {
    json.value = arrToObj(simpleData.value);
  }
  emit('change', json.value);
};

const onKeyInput = (item: any) => {
  item.keyLabel = item.key;
};
</script>

<style lang="postcss" scoped>
.t-tab-panel {
  height: 300px;
  overflow-y: hidden;
}

:deep(.t-input) {
  border-color: transparent;
  &:hover {
    border-color: var(--color-primary);
  }
}

.input-key {
  width: 140px;
  :deep(.t-input) {
    width: 140px;
  }
}

.one-data {
  .operation {
    display: none;
    justify-content: center;
    align-items: center;
    color: var(--td-text-color-secondary);
  }
  &:hover {
    .operation {
      display: flex;

      height: 30px;
    }
  }
}
</style>
