<template>
  <div class="page bg padding border page-full Ipt-2" style="position: relative;">
    <el-tabs v-model="activeName">
      <el-tab-pane :label="form.id ? '编辑服务器' : '新建服务器'" name="first">
        <el-collapse v-model="activeViewName">
          <el-collapse-item title="基本信息" name="1">
            <div class="collapse-wrap">
              <el-form style="width: 600px;margin: 0 auto;" :model="form" label-width="98px">
                <el-form-item label="名称">
                  <el-input v-model="form.name" show-word-limit maxlength="20" placeholder="请填写名称" />
                </el-form-item>
                <el-form-item label="类型">
                  <el-select v-model="form.types" placeholder="请选择类型">
                    <el-option v-for="dict in network_server_type" :key="dict.value" :label="dict.label" :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="form.types == 'tcp'" label="粘拆包规则">
                  <el-select @change="initData" v-model="stickValue" placeholder="请选择类型">
                    <el-option v-for="dict in stick_type" :key="dict.value" :label="dict.label" :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="form.types == 'tcp' && stickValue">
                  <el-form-item v-if="stickValue == '分隔符'" class="flex-column" label="分隔符">
                    <el-input v-model="stickData['delimit,omitempty']" placeholder="请填写分隔符" />
                  </el-form-item>
                  <el-form-item v-if="stickValue == '自定义脚本'" class="flex-column" label="自定义脚本">
                    <el-input v-model="stickData['custom,omitempty']" placeholder="请填写自定义脚本" />
                  </el-form-item>
                  <el-form-item v-if="stickValue == '固定长度'" class="flex-column" label="固定长度">
                    <el-input type="number" v-model="stickData['fixedLen,omitempty']" placeholder="请填写固定长度" />
                  </el-form-item>
                  <el-form-item v-if="stickValue == '长度字段'" class="flex-column" label="长度">
                    <el-input type="number" v-model="stickData['len,omitempty']['len']" placeholder="请填写长度" />
                  </el-form-item>
                  <el-form-item v-if="stickValue == '长度字段'" class="flex-column" label="偏移量">
                    <el-input type="number" v-model="stickData['len,omitempty']['offset']" placeholder="请填写偏移量" />
                  </el-form-item>
                  <el-form-item v-if="stickValue == '长度字段'" class="flex-column" label="大小端">
                    <el-select v-model="stickData['len,omitempty']['endian']" placeholder="请选择大小端">
                      <el-option label="大端" value="大端" />
                      <el-option label="小端" value="小端" />
                    </el-select>
                  </el-form-item>
                </el-form-item>
                <el-form-item label="地址">
                  <el-input v-model="form.addr" placeholder="端口号" />
                </el-form-item>
                <el-form-item label="开启TLS">
                  <el-radio-group v-model="form.isTls" class="ml-4">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="form.isTls == 1" label="接入方式">
                  <el-select @change="authTypeChange" v-model="form.authType" placeholder="选择接入方式">
                    <el-option label="Basic" :value="1" />
                    <el-option label="AccessToken" :value="2" />
                    <el-option label="证书" :value="3" />
                  </el-select>
                  <el-form-item v-if="form.authType == 1" class="flex-column" label="用户名">
                    <el-input v-model="form.authUser" placeholder="请填写用户名" />
                  </el-form-item>
                  <el-form-item v-if="form.authType == 1" class="flex-column" label="密码">
                    <el-input v-model="form.authPasswd" placeholder="请填写密码" />
                  </el-form-item>
                  <el-form-item v-if="form.authType == 2" class="flex-column" label="Aceess Token">
                    <el-input v-model="form.accessToken" placeholder="请填写Aceess Token" />
                  </el-form-item>
                </el-form-item>
                <el-form-item v-if="form.isTls == 1 && form.authType == 3" label="选择证书">
                  <el-select v-model="form.certificateId" placeholder="请选择证书">
                    <el-option v-for="item in certificateList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="启用">
                  <el-switch :active-value="1" :inactive-value="0" v-model="form.status" />
                </el-form-item>
              </el-form>
            </div>
          </el-collapse-item>
          <el-collapse-item title="注册包" name="2">
            <el-form style="width: 600px;margin: 0 auto;" :model="form" label-width="98px">
              <el-form-item label="正则表达式">
                <el-input v-model="form.register.regex" placeholder="请填写名称" />
              </el-form-item>
            </el-form>
          </el-collapse-item>
          <el-collapse-item title="协议适配" name="3">
            <el-form style="width: 600px;margin: 0 auto;" :model="form" label-width="98px">
              <el-form-item label="协议">
                <el-select v-model="form.protocol.name" placeholder="请选择协议适配">
                  <el-option v-for="dict in messageData" :key="dict.types" :label="dict.title" :value="dict.name"></el-option>
                  <!-- 增加系统默认的mqtt选项 -->
                  <el-option label="Sagoo Mqtt" value="SagooMqtt"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="协议参数">
                <codeEditor class="params" ref="mirrorRef" :mode="resourceModalPro.mode" :content="resourceModalPro.content">
                </codeEditor>
              </el-form-item>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </el-tab-pane>
    </el-tabs>
    <div style="position: absolute;right:20px;top: 14px;">
      <el-button size="small" @click="$router.replace('/iotmanager/network/server')">取消</el-button>
      <el-button @click="submit" size="small" type="primary">提交</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup name="serverCreateOrEdit">
import { watch, onMounted, ref, getCurrentInstance, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import api from '/@/api/network';
import api2 from '/@/api/system';
import deviceApi from '/@/api/device'
import codeEditor from "/@/components/codeEditor/index.vue"

const { proxy } = getCurrentInstance() as any;
const route = useRoute();
const router = useRouter();
const { network_server_type } = proxy.useDict('network_server_type');
const stickValue = ref('');
const stickData = ref({
  "delimit,omitempty": "",
  "custom,omitempty": "",
  "fixedLen,omitempty": 0,
  "len,omitempty": {
    "len": 0,
    "offset": 0,
    "endian": ""
  }
});
const stick_type = ref([
  {
    label: "分隔符",
    value: "分隔符"
  },
  {
    label: "自定义脚本",
    value: "自定义脚本"
  },
  {
    label: "固定长度",
    value: "固定长度"
  },
  {
    label: "长度字段",
    value: "长度字段"
  }
]);
const resourceModalPro = ref({
  mode: '',
  content: ''
});
const messageData = ref([]);
const certificateList = ref([]);
const activeViewName = ref(['1', '2', '3']);
const form = ref<any>({
  id: '',
  // 名称
  name: '',
  // AccessToken
  accessToken: "",
  // 认证密码
  authPasswd: "",
  // 认证用户
  authUser: "",
  // 认证方式（1=Basic，2=AccessToken，3=证书）
  authType: 3,
  // 是否开启TLS
  isTls: 0,
  // 证书id
  certificateId: "",
  // 类型
  types: 'tcp',
  // 禁用
  status: false,
  // 地址
  addr: '',
  register: {
    regex: "^\w+$"
  },
  // 协议适配
  protocol: {
    name: "SagooMqtt",
    options: {}
  },
  // 心跳包
  heartbeat: {
    enable: false,
    hex: "",
    regex: "^\\w+$",
    text: "",
    timeout: 30
  },
  // 设备
  devices: []
})

const mirrorRef = ref();
const activeName = ref('first');
const getDetail = () => {
  const id = route.params && route.params.id;
  if(!id) return;
  api.server.getDetail({ "id": id }).then((res: any) => {
    const { id, isTls, authType, certificateId, authUser, authPasswd, accessToken, name, types, status, addr, register, protocol, heartbeat, devices, stick } = res
    form.value["id"] = id
    form.value["name"] = name
    form.value["types"] = types
    form.value["status"] = status
    form.value["isTls"] = isTls
    form.value["addr"] = addr
    form.value["authType"] = authType
    form.value["authUser"] = authUser
    form.value["authPasswd"] = authPasswd
    form.value["accessToken"] = accessToken
    form.value["certificateId"] = certificateId
    form.value["register"] = JSON.parse(register)
    form.value["protocol"] = JSON.parse(protocol)
    form.value["heartbeat"] = JSON.parse(heartbeat)
    form.value["devices"] = JSON.parse(devices)
    let stickInfo = JSON.parse(stick)
    if (stickInfo.len && stickInfo.len.endian) {
      stick.value["len,omitempty"] = stickInfo.len
    } else if (stickInfo.fixedLen) {
      stick.value["fixedLen,omitempty"] = stickInfo.fixedLen
    } else if (stickInfo.custom) {
      stick.value["custom,omitempty"] = stickInfo.custom
    } else if (stickInfo.delimit) {
      stick.value["delimit,omitempty"] = stickInfo.delimit
    }
    if (types == 'tcp') {
      if (stickData.value['delimit,omitempty']) {
        stickValue.value = '分隔符'
      } else if (stickData.value['custom,omitempty']) {
        stickValue.value = '自定义脚本'
      } else if (stickData.value['fixedLen,omitempty']) {
        stickValue.value = '固定长度'
      } else if (stickData.value['len,omitempty']) {
        stickValue.value = '长度字段'
      }
    }
    let jsonData = JSON.stringify(JSON.parse(protocol).options);
    resourceModalPro.value.content = JSON.stringify(JSON.parse(jsonData), null, 4);
    nextTick(() => {
      mirrorRef.value.setValue(resourceModalPro.value.content);
    })
  })
};
const submit = () => {
  if (!form.value.id) {
    delete form.value.id;
  }
  let params = {
    ...form.value,
    "stick": {
      ...stickData.value
    }
  }
  if (mirrorRef.value.getValue()) {
    params.protocol.options = eval("(" + mirrorRef.value.getValue() + ")")
  }
  if(params.id) {
    // editItem
    api.server.editItem(params).then(() => {
      ElMessage.success('修改成功')
      goBack()
    });
  }else {
    // addItem
    api.server.addItem(params).then(() => {
      ElMessage.success('添加成功')
      goBack()
    });
  }

};
const goBack = () => {
  router.go(-1);
}
const initData = () => {
  stickData.value = {
    "delimit,omitempty": "",
    "custom,omitempty": "",
    "fixedLen,omitempty": 0,
    "len,omitempty": {
      "len": 0,
      "offset": 0,
      "endian": ""
    }
  }
}

const authTypeChange = () => {
  if (form.value.authType == 1) {
    form.value.accessToken = '';
    form.value.certificateId = ''
  }
  if (form.value.authType == 2) {
    form.value.authUser = '';
    form.value.authPasswd = '';
    form.value.certificateId = '';
  }
  if (form.value.authType == 2) {
    form.value.authUser = '';
    form.value.authPasswd = '';
    form.value.accessToken = '';
  }
}

const getCertificateList = () => {
  api2.certificate.getList().then((res: any) => {
    certificateList.value = res.Info;
  })
}

const getMessageData = () => {
  deviceApi.product.getTypesAll({ types: 'protocol' }).then((res: any) => {
    messageData.value = res || [];
  });
}

watch(
  () => form.value.isTls,
  (value) => {
    if (value == 0) {
      form.value.authType = ""
      form.value.certificateId = ""
    }
  }
);

onMounted(() => {
  getMessageData();
  getCertificateList();
  getDetail();
});
</script>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  position: relative;
  padding-left: 20px;

  .el-collapse-item__arrow {
    margin: 0 !important;
    position: absolute;
    left: 0;
    right: 0;

  }
}

:deep(.el-input),
:deep(.el-input-number) {
  width: 500px;
}

:deep(.params) {
  width: 600px;
}

:deep(.flex-column) {
  display: flex;
  flex-direction: column;

  .el-form-item__label {
    justify-content: flex-start;
  }
}
</style>

