<template>
  <a-modal
    :visible="visible"
    title="新增API"
    width="820px"
    :confirm-loading="loading"
    @update:visible="handleUpdateVisible"
    @ok="handleSubmit"
  >
    <a-form
      :model="formState"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      ref="formRef"
    >
      <a-row>
        <a-col :span="12">
          <a-form-item label="命名空间" name="namespace">
            <a-input v-model:value="formState.namespace" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="模块" name="module">
            <a-input v-model:value="formState.module" /> </a-form-item
        ></a-col>

        <a-col :span="12">
          <a-form-item label="版本" name="version">
            <a-input v-model:value="formState.version" /> </a-form-item
        ></a-col>

        <a-col :span="12"
          ><a-form-item label="前缀" name="prefix">
            <a-input v-model:value="formState.prefix" /> </a-form-item
        ></a-col>

        <a-col :span="12">
          <a-form-item label="URL" name="url">
            <a-input v-model:value="formState.url" />
          </a-form-item>
        </a-col>

        <a-col :span="12"
          ><a-form-item label="请求方法">
            <a-select v-model:value="formState.method">
              <a-select-option
                v-for="method in Method_List"
                :key="method.value"
                :value="method.value"
              >
                {{ method.label }}</a-select-option
              >
            </a-select></a-form-item
          ></a-col
        >

        <template v-if="formState.params">
          <template v-for="(param, index) in formState.params" :key="index">
            <a-col :span="24">
              <a-form-item label="请求参数" :labelCol="{ span: 3 }">
                <a-space>
                  <a-input
                    v-model:value="param.key"
                    placeholder="请输入参数键值对的key值"
                    style="width: 289px"
                  />
                  -
                  <a-input
                    v-model:value="param.value"
                    placeholder="请输入参数键值对的value值"
                    style="width: 289px"
                  />
                  <a
                    class="btn-link"
                    v-if="
                      param.key &&
                      param.value &&
                      formState.params &&
                      index === formState.params.length - 1
                    "
                    @click="handleAddItem('params')"
                  >
                    <PlusCircleOutlined
                  /></a>
                  <a
                    class="btn-link"
                    v-if="formState.params && formState.params.length > 1"
                    @click="handleRemoveItem('params', index)"
                  >
                    <MinusCircleOutlined
                  /></a>
                </a-space>
              </a-form-item>
            </a-col>
          </template>
        </template>

        <template v-if="formState.headers">
          <template v-for="(header, index) in formState.headers" :key="index">
            <a-col :span="24">
              <a-form-item label="请求头" :labelCol="{ span: 3 }">
                <a-space>
                  <a-input
                    v-model:value="header.key"
                    placeholder="请输入请求头键值对的key值"
                    style="width: 289px"
                  />
                  -
                  <a-input
                    v-model:value="header.value"
                    placeholder="请输入请求头键值对的value值"
                    style="width: 289px"
                  />
                  <a
                    class="btn-link"
                    v-if="
                      header.key &&
                      header.value &&
                      formState.headers &&
                      index === formState.headers.length - 1
                    "
                    @click="handleAddItem('headers')"
                  >
                    <PlusCircleOutlined
                  /></a>
                  <a
                    class="btn-link"
                    v-if="formState.headers && formState.headers.length > 1"
                    @click="handleRemoveItem('headers', index)"
                  >
                    <MinusCircleOutlined
                  /></a>
                </a-space>
              </a-form-item>
            </a-col>
          </template>
        </template>

        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <a-select v-model:value="formState.status">
              <a-select-option
                v-for="status in Status_List"
                :key="status.value"
                :value="status.value"
              >
                {{ status.label }}</a-select-option
              >
            </a-select>
          </a-form-item></a-col
        >

        <a-col :span="24">
          <a-form-item label="响应结果" name="result" :labelCol="{ span: 3 }">
            <a-textarea v-model:value="formState.result" />
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="描述" name="desc" :labelCol="{ span: 3 }">
            <a-textarea v-model:value="formState.desc" type="textarea" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, PropType, watch, Ref } from "vue";
import { PlusCircleOutlined, MinusCircleOutlined } from "@ant-design/icons-vue";
import { Method_List, Status_List } from "../constants";
import { getAddEditFormRules } from "./rules";
import { useAddEditApi } from "../hooks/useAddEditApi";
import { IApi, Method, Status } from "../types";
import { obj2ArrUtil } from "@/utils";

export default defineComponent({
  name: "add-edit-api-modal",

  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    currentRow: {
      type: Object as PropType<IApi>,
    },
  },

  emits: ["update:visible", "update:currentRow", "success"],

  setup(props, { emit }) {
    const {
      formRef,
      loading,
      formState,
      handleAddItem,
      handleRemoveItem,
      handleSubmit,
    } = useAddEditApi(() => {
      handleUpdateVisible(false);
      emit("success");
    });
    /**
     * 关闭对话框
     */
    const handleUpdateVisible = (bool: boolean) => {
      emit("update:currentRow", undefined);
      emit("update:visible", bool);
    };

    const initPage = () => {
      const { currentRow } = props;
      if (currentRow) {
        const {
          _id,
          namespace,
          version,
          module,
          url,
          prefix,
          params,
          method,
          headers,
          result,
          status,
          desc,
        } = currentRow;
        Object.assign(formState, {
          _id,
          namespace,
          version,
          module,
          url,
          prefix,
          params: obj2ArrUtil(params),
          method,
          headers: obj2ArrUtil(headers),
          result,
          status,
          desc,
        });
      }
    };

    watch(
      () => props.visible,
      (value) => {
        if (value) {
          initPage();
        } else {
          Object.assign(formState, {
            _id: undefined,
            namespace: "", // 系统
            version: "", // 版本
            module: "", // 模块名
            url: "", // url
            prefix: "/", // 前缀（全局、局部） 默认是/
            params: [{ key: "", value: "" }], //参数及类型
            method: Method.GET, //请求方式
            headers: [{ key: "", value: "" }], //请求头（请求头可以全局设置、可以是局部的，局部权重大于全局的）
            result: "", //返回结果
            status: Status.NORMAL, // 状态（已删除（逻辑删除）、待废弃、废弃、正常）
            desc: "", // 描述
          });
          formRef.value!.resetFields();
        }
      }
    );

    return {
      formRef,
      loading,
      formState,
      handleSubmit,
      handleUpdateVisible,
      handleAddItem,
      handleRemoveItem,
      rules: getAddEditFormRules(),
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      Method_List,
      Status_List,
    };
  },

  components: {
    PlusCircleOutlined,
    MinusCircleOutlined,
  },
});
</script>
<style>
.btn-link {
  padding: 0 3px;
}
</style>
