<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
            v-perms="'ipAccount:index:add'"
            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"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, resolveDirective, toRefs } from "vue";
import type { FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  type FieldValues,
  type PlusColumn,
  PlusDialogForm,
  PlusPage,
  PlusPageInstance,
  useTable
} from "plus-pro-components";
import {
  addOrEditIpAccount,
  deleteIpAccount,
  getIpAccountList,
  switchIpAccountStatus
} from "@/api/system/ipAccount";
import { isString } from "@pureadmin/utils";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { useRouter } from "vue-router";

defineOptions({
  name: "IpAccountIndex"
});

const router = useRouter();

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

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

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

const handleTableChange = (values: FieldValues) => {
  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 switchIpAccountStatus(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: "账户号",
    tableColumnProps: {
      showOverflowTooltip: true
    },
    prop: "accNo"
  },
  {
    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",
    tableColumnProps: {
      showOverflowTooltip: true
    },
    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;
}

const state = reactive<State>({
  dialogVisible: false,
  detailsVisible: false,
  confirmLoading: false,
  selectedIds: [],
  isCreate: false,
  form: {},
  rules: {
    accNo: [{ required: true, message: "请输入账户号", trigger: "blur" }]
  }
});

const columns: PlusColumn[] = [
  {
    label: "账户号",
    prop: "accNo",
    valueType: "input",
    fieldProps: {
      disabled: computed(() => !state.isCreate),
      maxlength: 32
    }
  },
  {
    label: "状态",
    prop: "status",
    valueType: "switch",
    fieldProps: {
      activeValue: "normal",
      inactiveValue: "disable"
    }
  },
  {
    label: "备注",
    prop: "remark",
    valueType: "input",
    fieldProps: {
      type: "textarea",
      rows: 3,
      maxlength: 200,
      showWordLimit: true
    }
  }
];

// 创建
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 addOrEditIpAccount(params);
      if (res.code === 200) {
        ElMessage.success("新增成功");
        confirmLoading.value = false;
        dialogVisible.value = false;
        refresh();
      } else {
        ElMessage.error(res.msg);
      }
    } finally {
      confirmLoading.value = false;
    }
  } else {
    // 编辑
    try {
      let params = form.value;
      let res = await addOrEditIpAccount(params);
      if (res.code === 200) {
        ElMessage.success("修改成功");
        confirmLoading.value = false;
        dialogVisible.value = false;
        refresh();
      } else {
        ElMessage.error(res.msg);
      }
    } finally {
      confirmLoading.value = false;
    }
  }
};

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

const { buttons } = useTable();

const perms = resolveDirective("perms");

buttons.value = [
  {
    // 修改
    text: "修改",
    code: "edit",
    // props v0.1.16 版本新增函数类型
    props: {
      type: "primary"
    },
    onClick(params) {
      form.value = params.row;
      state.isCreate = false;
      state.dialogVisible = true;
    },
    directives: [[perms, "ipAccount:index:edit"]]
  },
  {
    // 修改
    text: "管理接口",
    code: "interface",
    // props v0.1.16 版本新增函数类型
    props: {
      type: "primary"
    },
    onClick(val) {
      console.log("handleClick", val.row.accNo);
      let params = {
        accNo: val.row.accNo,
        accountId: val.row.id
      };
      Object.keys(params).forEach(param => {
        if (!isString(params[param])) {
          params[param] = params[param].toString();
        }
      });
      // 保存信息到标签页
      useMultiTagsStoreHook().handleTags("push", {
        path: `/ipAccount/ipAccountInterface`,
        name: "IpAccountInterface",
        query: params,
        meta: {
          title: `Token管理`,
          // 如果使用的是非国际化精简版title可以像下面这么写
          // title: `No.${index} - 详情信息`,
          // 最大打开标签数
          dynamicLevel: 1
        }
      });
      // 路由跳转
      router.push({ name: "IpAccountInterface", query: params });
    },
    directives: [[perms, "ipAccount:index:interface"]]
  },
  {
    // 删除
    text: "删除",
    code: "delete",
    // props v0.1.16 版本新增计算属性支持
    props: computed(() => ({ type: "danger" })),
    confirm: {
      options: {
        draggable: true,
        message: "确定删除此数据吗？"
      }
    },
    onConfirm: async params => {
      try {
        let res = await deleteIpAccount(params.row.id);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          refresh();
        } else {
          ElMessage.error(res.msg);
        }
      } catch (e) {
        ElMessage.error("删除失败");
      }
    },
    directives: [[perms, "ipAccount:index:remove"]]
  }
];

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