<script setup lang="ts">
import { isString } from "@pureadmin/utils";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { useRouter } from "vue-router";
import {
  type PlusColumn,
  PlusDialogForm,
  PlusPage,
  PlusPageInstance,
  useTable
} from "plus-pro-components";
import { computed, reactive, ref, resolveDirective, toRefs } from "vue";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash";
import {
  addBusinessSystem,
  deleteBusinessSystem,
  getBusinessSystem,
  getBusinessSystemList,
  updateBusinessSystem
} from "@/api/system/code";

defineOptions({
  name: "SystemCode"
});

const router = useRouter();

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

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

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

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

const tableConfig: PlusColumn[] = [
  {
    label: "系统名称",
    prop: "sysName",
    valueType: "input"
  },
  {
    label: "系统编码",
    prop: "sysCode",
    valueType: "input"
  },
  {
    label: "创建时间",
    prop: "createTime",
    hideInSearch: true
  }
];

const { buttons } = useTable();

const perms = resolveDirective("perms");

buttons.value = [
  {
    // 修改
    text: "修改",
    code: "edit",
    // props v0.1.16 版本新增函数类型
    props: {
      type: "primary"
    },
    onClick(params) {
      getBusinessSystem(params.row.sysId).then(res => {
        form.value = res.data;
        state.isCreate = false;
        state.dialogVisible = true;
      });
    },
    directives: [[perms, "system:code:edit"]]
  },
  {
    // 删除
    text: "删除",
    code: "delete",
    // props v0.1.16 版本新增计算属性支持
    props: computed(() => ({ type: "danger" })),
    show: (row: any) => row.parentId !== 0,
    confirm: {
      options: {
        draggable: true,
        message: "确定删除此数据吗？"
      }
    },
    onConfirm: async params => {
      try {
        let res = await deleteBusinessSystem(params.row.sysId);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          refresh();
        } else {
          ElMessage.error(res.msg);
        }
      } catch (e) {
        ElMessage.error("删除失败");
      }
    },
    directives: [[perms, "system:code:remove"]]
  }
];

const handleClick = (val: number) => {
  console.log("handleClick", val);
  let params = {
    dictType: val
  };
  Object.keys(params).forEach(param => {
    if (!isString(params[param])) {
      params[param] = params[param].toString();
    }
  });
  // 保存信息到标签页
  useMultiTagsStoreHook().handleTags("push", {
    path: `/system/dict-data/index`,
    name: "DictData",
    query: params,
    meta: {
      title: `字典数据`,
      // 如果使用的是非国际化精简版title可以像下面这么写
      // title: `No.${index} - 详情信息`,
      // 最大打开标签数
      dynamicLevel: 1
    }
  });
  // 路由跳转
  router.push({ name: "DictData", query: params });
};

const handleCreate = () => {
  console.log("handleCreate");
  form.value = {};
  state.isCreate = true;
  state.dialogVisible = true;
};

interface State {
  dialogVisible: boolean;
  detailsVisible: boolean;
  confirmLoading: boolean;
  selectedIds: number[];
  isCreate: boolean;
  form: Record<string, any>;
  rules: Record<string, any>;
}

const state = reactive<State>({
  dialogVisible: false,
  detailsVisible: false,
  confirmLoading: false,
  selectedIds: [],
  isCreate: true,
  form: {},
  rules: {
    sysName: [{ required: true, message: "请输入系统名称", trigger: "blur" }],
    sysCode: [{ required: true, message: "请输入系统编码", trigger: "blur" }]
  }
});

const columns: PlusColumn[] = [
  {
    label: "系统名称",
    prop: "sysName",
    valueType: "input"
  },
  {
    label: "系统编号",
    prop: "sysCode",
    valueType: "input"
  }
];

const handleSubmit = async () => {
  state.confirmLoading = true;
  try {
    let payload = cloneDeep(form.value);
    let res: any;
    if (state.isCreate) {
      res = await addBusinessSystem(payload);
    } else {
      res = await updateBusinessSystem(payload);
    }
    if (res.code === 200) {
      ElMessage.success(state.isCreate ? "新增成功" : "修改成功");
      state.dialogVisible = false;
      refresh();
    } else {
      ElMessage.error(res.msg);
    }
  } catch (e) {
    ElMessage.error(state.isCreate ? "新增失败" : "修改失败");
  } finally {
    state.confirmLoading = false;
  }
};

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

<template>
  <div>
    <PlusPage
      ref="plusPageInstance"
      :columns="tableConfig"
      :request="getList"
      :pagination="false"
      :table="{
        actionBar: { buttons, type: 'link', width: 140 },
        adaptive: { offsetBottom: 50 }
      }"
      :search="{
        showNumber: 3
      }"
    >
      <template #plus-cell-dictType="scoped">
        <el-button type="text" @click="handleClick(scoped.row.dictType)">{{
          scoped.row.dictType
        }}</el-button>
      </template>
      <template #table-title>
        <el-row class="button-row">
          <el-button
            v-perms="'system:code: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,
        rowProps: { gutter: 20 },
        colProps: { span: 12 }
      }"
      :dialog="{ title: dialogTitle + '字典', width: 600, confirmLoading }"
      @confirm="handleSubmit"
    />
  </div>
</template>

<style scoped lang="scss"></style>
