<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 {
  addSystemDictType,
  deleteSystemDictType,
  getSystemDictById,
  getSystemDictList,
  refreshDictCache,
  updateSystemDictType
} from "@/api/system/dict";
import { computed, reactive, ref, resolveDirective, toRefs } from "vue";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash";

defineOptions({
  name: "Dict"
});

const router = useRouter();

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

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

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

// 搜索条件处理
const handleBeforeSearch = (values: any) => {
  let params = cloneDeep(values);
  if (params.daterange && params.daterange.length === 2) {
    Reflect.set(params, "params", {});
    Reflect.set(params.params, "beginTime", values.daterange[0]);
    Reflect.set(params.params, "endTime", values.daterange[1]);
  } else {
    Reflect.deleteProperty(params, "params");
  }
  return params;
};

const handleRefresh = async () => {
  try {
    let res = await refreshDictCache();
    if (res.code === 200) {
      ElMessage.success("刷新缓存成功");
      refresh();
    } else {
      ElMessage.error(res.msg);
    }
  } catch (e) {
    ElMessage.error("刷新缓存失败");
  }
};

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

const tableConfig: PlusColumn[] = [
  {
    label: "字典主键",
    prop: "dictId",
    valueType: "input",
    width: 100,
    hideInSearch: true
  },
  {
    label: "字典名称",
    prop: "dictName",
    valueType: "input"
  },
  {
    label: "字典类型",
    prop: "dictType",
    fieldProps: {
      showOverflowTooltip: true
    }
  },
  {
    label: "状态",
    prop: "status",
    valueType: "tag",
    fieldProps: value => ({
      type: value === "0" ? "primary" : "danger"
    }),
    fieldSlots: {
      default: ({ value }) => (value === "0" ? "正常" : "停用")
    },
    hideInSearch: true
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    fieldProps: {
      options: [
        { label: "正常", value: "0" },
        { label: "停用", value: "1" }
      ],
      clearable: true
    },
    hideInTable: true
  },
  {
    label: "备注",
    prop: "remark",
    valueType: "input",
    hideInSearch: true
  },
  {
    label: "创建时间",
    prop: "createTime",
    hideInSearch: true
  },
  {
    label: "创建时间",
    prop: "daterange",
    valueType: "date-picker",
    fieldProps: {
      type: "daterange",
      "range-separator": "至",
      "start-placeholder": "开始日期",
      "end-placeholder": "结束日期",
      valueFormat: "YYYY-MM-DD",
      style: { width: "100%" }
    },
    hideInTable: true
  }
];

const { buttons } = useTable();

// 权限
const perms = resolveDirective("perms");

buttons.value = [
  {
    // 修改
    text: "修改",
    code: "edit",
    // props v0.1.16 版本新增函数类型
    props: {
      type: "primary"
    },
    onClick(params) {
      getSystemDictById(params.row.dictId).then(res => {
        form.value = res.data;
        state.isCreate = false;
        state.dialogVisible = true;
      });
    },
    directives: [[perms, "system:dict: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 deleteSystemDictType(params.row.dictId);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          refresh();
        } else {
          ElMessage.error(res.msg);
        }
      } catch (e) {
        ElMessage.error("删除失败");
      }
    },
    directives: [[perms, "system:dict: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 = {
    status: "0"
  };
  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: {
    status: "0"
  },
  rules: {
    dictName: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
    dictType: [{ required: true, message: "请输入字典类型", trigger: "blur" }]
  }
});

const columns: PlusColumn[] = [
  {
    label: "字典名称",
    prop: "dictName",
    valueType: "input",
    placeholder: "请输入字典名称"
  },
  {
    label: "字典类型",
    prop: "dictType",
    valueType: "input",
    placeholder: "请输入字典类型"
  },
  {
    label: "状态",
    prop: "status",
    valueType: "radio",
    fieldProps: {
      options: [
        { label: "正常", value: "0" },
        { label: "停用", value: "1" }
      ]
    }
  },
  {
    label: "备注",
    prop: "remark",
    valueType: "textarea",
    placeholder: "请输入备注信息",
    colProps: { span: 24 }
  }
];

const handleSubmit = async () => {
  state.confirmLoading = true;
  try {
    let payload = cloneDeep(form.value);
    let res: any;
    if (state.isCreate) {
      res = await addSystemDictType(payload);
    } else {
      res = await updateSystemDictType(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"
      :pageInfoMap="{ page: 'pageNum', pageSize: 'pageSize' }"
      :beforeSearchSubmit="handleBeforeSearch"
      :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:dict:add'"
            size="default"
            type="success"
            @click="handleCreate"
          >
            新增
          </el-button>
          <el-button size="default" type="default" @click="handleRefresh">
            刷新缓存
          </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: 800, confirmLoading }"
      @confirm="handleSubmit"
    />
  </div>
</template>

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