<template>
  <div class="network-component">
    <div class="form-item mt-8">
      <label>
        {{ modelValue.type === 'subscribe' ? $t('数据获取') : $t('发送到') }}
      </label>
      <t-select-input
        v-if="mode"
        v-model:inputValue="modelValue.name"
        :value="modelValue.name"
        :placeholder="$t('我的数据发送')"
        allow-input
        clearable
        v-model:popup-visible="popupVisible"
        @focus="popupVisible = true"
        @blur="popupVisible = false"
        @input-change="onInput"
        @clear="
          modelValue.name = undefined;
        "
      >
        <template #panel>
          <ul style="padding: 4px">
            <li class="hover-background item"  @click="() => {onSelect({protocol:'http',name:'HTTP'}); protocolChange('http') }">
                HTTP
            </li>
            <li class="hover-background item"  @click="() => {onSelect({protocol:'websocket',name:'Websocket'}); protocolChange('websocket')}">
                Websocket
            </li>
            <li class="hover-background item"  @click="() => {onSelect({protocol:'mqtt',name:'MQTT'});protocolChange('mqtt')}">
                MQTT
            </li>
            <t-divider style="border-top: 1px solid var(--color-border-input);"></t-divider>
            <li v-if="hasIot" class="hover-background item"  @click="() => onSelect({protocol:'iot',name:'物联网平台'})">
                物联网平台
            </li>
            <li
              class="hover-background item"
              style="line-height: 1.5; padding: 8px; border-radius: 2px"
              v-for="(item, i) in networkList"
              :key="item.url"
              @click="() => onSelect(item)"
            >
              名称: {{ item.name }}
              <div v-if="item.url" class="desc">地址: {{ item.url }}</div>

              <!-- <span class="del" @click.stop="onDelNetWork(item, i)">
                <delete-icon />
              </span> -->
            </li>
            <li
              v-if="networkList.length >= 10"
              style="line-height: 1.5; padding: 8px; border-radius: 2px"
              :key="-1"
            >
              <div class="desc">...</div>
            </li>
            <li v-if="!networkList.length" style="line-height: 1.5; padding: 8px; border-radius: 2px" :key="-1">
              <div class="desc">{{$t('暂无数据')}}</div>
            </li>
          </ul>
        </template>
      </t-select-input>
      <t-input v-else v-model="modelValue.name" :placeholder="$t('名称')"></t-input>
    </div>
    <template v-if="modelValue.protocol&&modelValue.protocol!=='iot'">
    <!-- <div v-if="!modelValue.unmodifiable"  class="form-item mt-8">
      <label>通信方式</label>
      <t-select
        v-model="modelValue.protocol"
        placeholder="MQTT"
        @change="protocolChange"
      >
        <t-option key="mqtt" value="mqtt" label="MQTT" />
        <t-option key="websocket" value="websocket" label="Websocket" />
        <t-option key="http" value="http" label="HTTP" />
      </t-select>
    </div> -->
    <div v-if="!modelValue.unmodifiable"  class="form-item mt-8">
      <label>{{$t('URL地址')}}</label>
      <t-input
        :format="urlFormat"
        :placeholder="
          modelValue.protocol !== 'http'
            ? isSafeProtocol()
              ? $t('必须是wss协议')
              : $t('必须是ws协议')
            : $t('请输入')
        " v-model="modelValue.url"></t-input>
    </div>
    <template v-if="modelValue.protocol === 'websocket'&&modelValue.options">
      <div v-if="!modelValue.unmodifiable" class="form-item mt-8">
        <label>protocols</label>
        <t-input v-model="modelValue.options.protocols" />
      </div>
    </template>
    <template v-else-if="modelValue.protocol === 'http'">
      <div class="form-item mt-8">
        <label>{{$t('请求方式')}}</label>
        <t-select :disabled="modelValue.unmodifiable" v-model="modelValue.method" @change="httpMethodChange">
          <t-option key="GET" value="GET" label="GET" />
          <t-option key="POST" value="POST" label="POST" />
        </t-select>
      </div>
      <div v-if="modelValue.type === 'subscribe'" class="form-item mt-8">
        <label>{{$t('请求间隔')}}</label>
        <t-input-number theme="column" v-model="modelValue.interval" :placeholder="$t('默认1000 ms')"></t-input-number>
      </div>
      <div class="form-item mt-8">
        <label>{{$t('请求头')}}</label>
        <!-- <t-textarea
          v-model="modelValue.headers"
          :autosize="{ minRows: 3, maxRows: 5 }"
          placeholder="请输入"
        /> -->
        <!-- <CodeEditor
          :json="true"
          :language="'json'"
          v-model="modelValue.headers"
          class="mt-4"
          style="height: 50px"
        /> -->
        <t-button
          class="ml-8"
          shape="square"
          variant="outline"
          @click="showJsonModal()"
        >
          <ellipsis-icon slot="icon" />
        </t-button>
      </div>
      <!-- <div class="form-item mt-8 desc">
        <label></label>
        支持设置动态参数，例如：{"Authorization": "Bearer ${token}"}
      </div> -->
      <div v-if="!mode && modelValue.method === 'POST'" class="form-item mt-8">
        <label>{{$t('请求体')}}</label>
        <!-- <t-textarea
          v-model="modelValue.body"
          :autosize="{ minRows: 3, maxRows: 5 }"
          placeholder="请输入"
        /> -->
        <CodeEditor
          :json="true"
          :language="'json'"
          v-model="modelValue.body"
          class="mt-4"
          style="height: 50px"
        />
      </div>
      <div
        v-if="!mode && modelValue.method === 'POST'"
        class="form-item mt-8 desc"
      >
        <label></label>
        {{$t('支持设置动态参数')}}，{{$t('例如')}}：{"value": "${value}"}
      </div>
    </template>
    <template v-else-if="modelValue.protocol === 'mqtt'">
      <template  v-if="modelValue.options&&!modelValue.unmodifiable">
      <div class="form-item mt-8">
        <label>Client Id</label>
        <t-input v-model="modelValue.options.clientId" />
      </div>
      <div class="form-item mt-8">
        <label>{{$t('自动生成')}}</label>
        <t-switch class="mt-8 ml-8" v-model="modelValue.options.customClientId" size="small"></t-switch>
      </div>
      <div class="form-item mt-8">
        <label>{{$t('用户名')}}</label>
        <t-input v-model="modelValue.options.username"></t-input>
      </div>
      <div class="form-item mt-8">
        <label>{{$t('密码')}}</label>
        <t-input v-model="modelValue.options.password"></t-input>
      </div>
      </template>
      <div class="form-item mt-8">
        <label>Topics</label>
        <t-input v-model="modelValue.topics" />
      </div>
    </template>
    </template>
    <!-- <div class="form-item mt-8" v-if="mode">
      <label> </label>
      <div>
        <t-button @click="onSave">{{$t('保存到我的数据发送')}}</t-button>
      </div>
    </div> -->
  </div>
  <JsonModal v-model:visible="codeDialog.visible" v-model:data="codeDialog.data" :options="headersOptions" tips='支持设置动态参数，例如：{"Authorization": "Bearer ${token}"}' @change="getJsonData" />
</template>

<script lang="ts" setup>
import { onBeforeMount, ref, getCurrentInstance, reactive } from 'vue';
import axios from 'axios';
import { debounce } from '@/services/debouce';
import { MessagePlugin } from 'tdesign-vue-next';
import CodeEditor from '@/views/components/common/CodeEditor.vue';
import { DeleteIcon } from 'tdesign-icons-vue-next';
import { transformData } from '@/services/utils';
import { deepClone } from '@meta2d/core';
import { EllipsisIcon } from 'tdesign-icons-vue-next';
import JsonModal from '@/views/components/common/JsonModal.vue';

const { modelValue, mode } = defineProps<{
  modelValue: any;
  mode?: any;
}>();
const { proxy } = getCurrentInstance();
const $t = proxy.$t

const emit = defineEmits(['update:modelValue', 'change']);
const popupVisible = ref<boolean>(false);
const networkList = ref<any[]>([]);

onBeforeMount(() => {
  modelValue.id = modelValue.id || modelValue._id;
  if (mode) {
    getNetworks();
  }
});

const protocolChange = (protocol: string) => {
  if (protocol === 'http') {
    Object.assign(modelValue, {
      httpTimeInterval: 1000,
      headers: '',
      method: 'GET',
      body: '',
    });
  } else if (protocol === 'websocket') {
    // modelValue.url = '';
  } else {
    Object.assign(modelValue, {
      options: {
        clientId: '',
        username: '',
        password: '',
        customClientId: false,
      },
    });
  }
};

const httpMethodChange = (method: string) => {
  if (method === 'GET') {
    modelValue.body = undefined;
  }
};

const onSave = async () => {
  emit('update:modelValue', modelValue);
  emit('change', modelValue);

  let ret: any;
  const data = transformData(modelValue,'toNetwork');
  // 保存到我的数据源
  if (modelValue.id) {
    ret = await axios.post(`/api/data/datasource/update`, data);
  } else {
    ret = await axios.post(`/api/data/datasource/add`, data);
  }

  if (ret) {
    MessagePlugin.success($t('保存成功！'));
  }
};

const onInput = (text: string) => {
  debounce(getNetworks, 300);
};

const hasIot = ref(false);

// 请求我的数据源接口
const getNetworks = async () => {
  let arr = [];
  meta2d.store.data.networks?.forEach((network)=>{
     if(['mqtt','websocket','http'].includes(network.protocol)&&network.method!=="POST"){
        let net:any = deepClone(network);
        if(net.protocol === 'http'){
          net.method = 'POST'
        }
        net.unmodifiable = true;
        net.type = '';
        net.value ='';
        net.tem_index='';
        net.label = '';
        arr.push(net);
     }
  });
  if(meta2d.store.data.iot?.tree?.length){
    hasIot.value = true;
  }
  networkList.value =arr;// deepClone(meta2d.store.data.networks);
  return;
  const body: any = {
    type: modelValue.type,
    projection: "id,data,name,type",
  };
  if (modelValue.name) {
    body.name = modelValue.name;
  }
  const ret: any = await axios.post(`/api/data/datasource/list`, body, {
    params: {
      current: 1,
      pageSize: 10,
    },
  });
  if (ret?.list) {
    const list = [];
    for (const item of ret.list) {
      item.id = item.id || item._id;
      list.push(transformData(item,'toMetaNetwork'));
    }
    networkList.value = list;
  }
};

const onSelect = (item: any) => {
  for (let key in modelValue) {
    if (modelValue.hasOwnProperty(key)) {
      delete modelValue[key];
    }
  }
  Object.assign(modelValue, item);
  popupVisible.value = false;
};

const onDelNetWork = async (item: any, i: number) => {
  const ret: any = await axios.post(`/api/data/datasource/delete`, {
    id: item._id || item.id,
  });
  if (ret) {
    networkList.value.splice(i, 1);
  }
};

const isSafeProtocol = () => {
  return document.location.protocol === 'https:' ? true : false;
};

const urlFormat = (val) => {
  if (modelValue.protocol === 'mqtt') {
    let reg = /^ws\:.*/;
    if (isSafeProtocol()) {
      reg = /^wss\:.*/;
    }
    if (reg.test(val)) {
      return val;
    } else {
      return '';
    }
  } else {
    return val;
  }
};

const codeDialog = reactive({
  visible:false,
  data:null
});

const showJsonModal = () => {
  codeDialog.visible = true;
  codeDialog.data = modelValue.headers;
};

const getJsonData = (data) => {
  modelValue.headers = data;
  codeDialog.visible = false;
};

const headersOptions = [{
  label: 'Authorization',
  value: 'Authorization',
}]

</script>
<style lang="postcss" scoped>
.network-component {
}
</style>
