<template>
  <div>
    <PlusPage
      ref="plusPageInstance"
      :columns="tableConfig"
      :request="getList"
      :is-card="true"
      :search="{
        labelWidth: 100,
        showNumber: 3
      }"
      :table="{
        actionBar: { buttons, type: 'link', width: 180 },
        adaptive: { offsetBottom: 50 },
        onFormChange: handleTableChange
      }"
      :pageInfoMap="{ page: 'pageNum', pageSize: 'pageSize' }"
    >
      <template #table-title>
        <el-row class="button-row">
          <el-button size="default" type="success" @click="handleCreate">
            新增
          </el-button>
        </el-row>
      </template>
    </PlusPage>
    <!-- 弹窗编辑 -->
    <PlusDialogForm
      ref="dialogForm"
      v-model="form"
      v-model:visible="dialogVisible"
      :form="{
        columns,
        labelPosition: 'right',
        labelWidth: 100,
        rules
      }"
      :dialog="{ title: dialogTitle + '菜单', width: 600, confirmLoading }"
      @confirm="handleSubmit"
      @close="handleClose"
    />
    <PlusDialog
      v-model="detailsVisible"
      :hasFooter="false"
      title="接口配置"
      width="500"
    >
      <PlusDescriptions
        :column="24"
        :columns="descriptionsColumns"
        :data="descriptionsData"
      />
    </PlusDialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, toRefs } from "vue";
import type { FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  type FieldValues,
  type PlusColumn,
  PlusDescriptions,
  PlusDialog,
  PlusDialogForm,
  PlusPage,
  PlusPageInstance,
  useTable
} from "plus-pro-components";
import {
  addOrEditIpInterface,
  deleteIpInterface,
  getIpInterfaceList,
  switchIpInterfaceStatus
} from "@/api/system/ipInterface";

defineOptions({
  name: "IpInterfaceIndex"
});

const plusPageInstance = ref<PlusPageInstance | null>(null);

const getList = async (query: Record<string, any>) => {
  let res = await getIpInterfaceList(query);
  return {
    data: res.list,
    total: res.total
  };
};

// 重新请求列表接口
const refresh = () => {
  plusPageInstance.value?.getList();
};

const handleTableChange = (values: any) => {
  console.log(values);
  ElMessageBox.confirm("确定修改此数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        let data = {
          id: values.row.id,
          status: values.row.status
        };
        let res = await switchIpInterfaceStatus(data);
        if (res.code === 200) {
          ElMessage.success("修改成功");
        } else {
          ElMessage.error(res.msg);
        }
      } catch (e) {
        ElMessage.error("修改失败");
      }
    })
    .finally(() => {
      refresh();
    });
};

const dialogTitle = computed(() => (state.isCreate ? "新增" : "编辑"));

// 表格数据
const tableConfig: PlusColumn[] = [
  {
    label: "接口名称",
    prop: "interfaceName"
  },
  {
    label: "接口编码",
    prop: "interfaceNo",
    hideInSearch: true
  },
  {
    label: "接口厂商",
    prop: "manufacturer",
    hideInSearch: true
  },
  {
    label: "状态",
    prop: "status",
    valueType: "switch",
    fieldProps: {
      activeValue: "normal",
      inactiveValue: "disable"
    },
    editable: true,
    hideInSearch: true
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    options: [
      { label: "正常", value: "normal" },
      { label: "停用", value: "disable" }
    ],
    hideInTable: true
  },
  {
    label: "备注",
    prop: "remark",
    hideInSearch: true
  },
  {
    label: "创建时间",
    prop: "addTime",
    valueType: "time-picker",
    hideInSearch: true
  },
  {
    label: "创建人",
    prop: "addUserName",
    hideInSearch: true
  }
];

/*--------------------表单--------------------*/

// 表单实例
const dialogForm = ref(null);

interface State {
  dialogVisible: boolean;
  detailsVisible: boolean;
  confirmLoading: boolean;
  selectedIds: number[];
  isCreate: boolean;
  form: {};
  rules: FormRules;
  descriptionsData: {};
}

const state = reactive<State>({
  dialogVisible: false,
  detailsVisible: false,
  confirmLoading: false,
  selectedIds: [],
  isCreate: false,
  form: {},
  rules: {
    interfaceName: [
      { required: true, message: "请输入接口名称", trigger: "blur" }
    ],
    interfaceNo: [
      { required: true, message: "请输入接口编码", trigger: "blur" }
    ],
    manufacturer: [
      { required: true, message: "请输入接口厂商", trigger: "blur" }
    ],
    interfaceConfig: [
      { required: true, message: "请输入接口配置", trigger: "blur" }
    ]
  },
  descriptionsData: {}
});

const columns: PlusColumn[] = [
  {
    label: "接口名称",
    prop: "interfaceName",
    valueType: "input",
    fieldProps: {
      clearable: true
    }
  },
  {
    label: "接口编码",
    prop: "interfaceNo",
    valueType: "input",
    fieldProps: {
      clearable: true
    }
  },
  {
    label: "接口厂商",
    prop: "manufacturer",
    valueType: "input",
    fieldProps: {
      clearable: true
    }
  },
  {
    label: "状态",
    prop: "status",
    valueType: "radio",
    fieldProps: {
      options: [
        { label: "正常", value: "normal" },
        { label: "停用", value: "disable" }
      ]
    }
  },
  {
    label: "接口配置",
    prop: "interfaceConfig",
    valueType: "textarea",
    fieldProps: {
      rows: 4
    }
  },
  {
    label: "备注",
    prop: "remark",
    valueType: "textarea",
    fieldProps: {
      rows: 4
    }
  }
];

const descriptionsColumns: PlusColumn[] = [
  {
    label: "接口配置",
    prop: "interfaceConfig",
    valueType: "copy",
    descriptionsItemProps: {
      span: 24,
      className: "break-all"
    }
  }
];

// 创建
const handleCreate = (): void => {
  form.value = {
    status: "normal"
  };
  state.isCreate = true;
  state.dialogVisible = true;
};

const handleSubmit = async (values: FieldValues) => {
  console.log(values, "Submit");
  confirmLoading.value = true;
  if (state.isCreate) {
    try {
      let params = form.value;
      let res = await addOrEditIpInterface(params);
      if (res.code === 200) {
        ElMessage.success("新增成功");
        confirmLoading.value = false;
        dialogVisible.value = false;
      } else {
        ElMessage.error(res.msg);
      }
    } finally {
      confirmLoading.value = false;
      refresh();
    }
  } else {
    // 编辑
    try {
      let params = form.value;
      let res = await addOrEditIpInterface(params);
      if (res.code === 200) {
        ElMessage.success("修改成功");
        confirmLoading.value = false;
        dialogVisible.value = false;
        refresh();
      } else {
        ElMessage.error(res.msg);
      }
    } finally {
      confirmLoading.value = false;
      refresh();
    }
  }
};

const handleClose = () => {
  console.log(dialogForm.value.formInstance);
};

// 参数预期管理
const normalizeParams = (params: Record<string, any>) => {
  return {
    interfaceName: params.interfaceName ?? null,
    interfaceNo: params.interfaceNo ?? null,
    manufacturer: params.manufacturer ?? null,
    status: params.status ?? null,
    remark: params.remark ?? null,
    interfaceConfig: params.interfaceConfig ?? null,
    id: params.id ?? null
  };
};

const { buttons } = useTable();

buttons.value = [
  {
    // 修改
    text: "修改",
    code: "edit",
    // props v0.1.16 版本新增函数类型
    props: {
      type: "primary"
    },
    onClick(params) {
      // form.value = params.row;
      Object.assign(form.value, normalizeParams(params.row));
      state.isCreate = false;
      state.dialogVisible = true;
    }
  },
  {
    // 修改
    text: "查看配置",
    code: "config",
    // props v0.1.16 版本新增函数类型
    props: {
      type: "primary"
    },
    onClick(val) {
      console.log(val);
      detailsVisible.value = true;
      descriptionsData.value = {
        interfaceConfig: val.row.interfaceConfig
      };
    }
  },
  {
    // 删除
    text: "删除",
    code: "delete",
    // props v0.1.16 版本新增计算属性支持
    props: computed(() => ({ type: "danger" })),
    confirm: {
      options: {
        draggable: true,
        message: "确定删除此数据吗？"
      }
    },
    onConfirm: async params => {
      try {
        let res = await deleteIpInterface(params.row.id);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          refresh();
        } else {
          ElMessage.error(res.msg);
        }
      } catch (e) {
        ElMessage.error("删除失败");
      }
    }
  }
];

const {
  form,
  confirmLoading,
  rules,
  dialogVisible,
  detailsVisible,
  descriptionsData
} = toRefs(state);
</script>
