<template>
  <div>
    <MomTable
      ref="MomTable"
      row-key="id"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryParam"
      :query-param-item="queryFormItem"
      :action-buttons="actionButtons"
      :total="total"
      :page.sync="page"
      :show-enable-flag="true"
      :mega-extend="{
        rowIndex: false,
        rowAction: {
          width: 150,
        },
      }"
      @beforeSearch="beforeSearch"
      @search="searchPageData"
      @add="handleAdd"
      @edit="handleEdit"
      @delete="handleDelete"
      @enable="
        (record) =>
          handleStatus(
            { status: 'Y', id: record.id },
            'ENABLED',
            'ENABLED_DATA_INFO',
            'ENABLE_SUCCESS'
          )
      "
      @disable="
        (record) =>
          handleStatus(
            { status: 'N', id: record.id },
            'DISABLED',
            'DISABLED_DATA_INFO',
            'DISABLE_SUCCESS'
          )
      "
    >
      <a-row slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('ROLE_MANAGEMENT:ADD')"
          @click="() => handleAdd()"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
      </a-row>
      <div slot="enableFlag" slot-scope="text, record">
        <span v-if="record.enableFlag == 'Y'" class="text-success">
          {{ getAttrValue(enableFlagList, text) }}
        </span>
        <span v-else class="text-error">
          {{ getAttrValue(enableFlagList, text) }}
        </span>
      </div>
    </MomTable>

    <MegaDrawer
      :visible="drawerVisible"
      :title="isEdit ? $t('EDIT') : $t('ADD')"
      width="480px"
      @close="handleCloseDrawer"
      @ok="handleOk"
    >
      <template slot="main">
        <a-form-model
          ref="addForm"
          :model="form"
          :rules="rules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
        >
          <a-form-model-item
            v-show="form.parentCategoryName"
            :label="$t('SUP_CATEGORY')"
            prop="parentCategoryName"
          >
            <a-input v-model="form.parentCategoryName" disabled />
          </a-form-model-item>
          <a-form-model-item
            prop="categoryCode"
            allow-clear
            :label="$t('CATEGORY_CODE')"
          >
            <a-input
              v-model="form.categoryCode"
              :placeholder="$t('PLACEENTER')"
            />
          </a-form-model-item>
          <a-form-model-item
            prop="categoryName"
            allow-clear
            :label="$t('CATEGORY_NAME')"
            :placeholder="$t('PLACEENTER')"
          >
            <a-input v-model="form.categoryName" />
          </a-form-model-item>
          <a-form-model-item
            prop="seq"
            allow-clear
            :label="$t('ORDER')"
            :placeholder="$t('PLACEENTER')"
          >
            <a-input v-model="form.seq" />
          </a-form-model-item>
          <a-form-model-item :label="$t('REMARK')" prop="">
            <a-textarea
              v-model="form.remark"
              allow-clear
              :placeholder="$t('PLACEENTER')"
              :auto-size="{ minRows: 2, maxRows: 6 }"
            />
          </a-form-model-item>
        </a-form-model>
      </template>
    </MegaDrawer>
  </div>
</template>

<script>
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import { deleteLeafArray } from "@mega-apps/utils";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: { MegaDrawer },
  data() {
    return {
      enableFlagList: [],
      // 表格的配置项
      tableColumns: [
        {
          dataIndex: "categoryName",
          sorter: false,
          minWidth: 300,
          title: () => this.$t("CATEGORY_NAME"), // 分类名称
        },
        {
          dataIndex: "categoryCode",
          sorter: false,
          minWidth: 320,
          title: () => this.$t("CATEGORY_CODE"), // 分类编码
        },
        {
          dataIndex: "remark",
          sorter: false,
          minWidth: 320,
          title: () => this.$t("REMARK"), // 备注
        },
        {
          dataIndex: "seq",
          sorter: false,
          width: 80,
          title: () => this.$t("ORDER"), // 顺序
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          width: 80,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy", // 更新人
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "updateTime", // 更新时间
          sorter: false,
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
        },
      ],
      tableData: [],
      page: 1, // 页码
      total: 0, // 每页个数
      // 查询的表单的配置项
      queryParam: {
        categoryName: "",
        categoryCode: "",
      },
      actionButtons: ["add", "edit", "delete"],

      drawerVisible: false,
      isEdit: false,

      form: {
        id: undefined,
        superLevel: undefined,
        categoryCode: undefined,
        categoryName: undefined,
        seq: "1",
        remark: undefined,
        parent: {
          id: undefined,
          categoryName: undefined,
        },
      },
    };
  },
  computed: {
    // 表格搜索配置
    queryFormItem() {
      return this.$observable("queryFormItem", {
        categoryName: {
          itemType: "input",
          label: () => this.$t("CATEGORY_NAME"), // 分类编码
        },
        categoryCode: {
          itemType: "input",
          label: () => this.$t("CATEGORY_CODE"), // 分类名称
        },
      });
    },
    rules() {
      return {};
    },
  },
  methods: {
    beforeSearch() {
      return Promise.all([this.getDictByCode("DIC:COMMON:ENABLE_FLAG")]).then(
        ([enableStatus]) => {
          this.enableFlagList = enableStatus?.data?.data || [];
        }
      );
    },
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: true,
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .get(
              `${ApiConstant.PREFIX_CORE}/api/flowable/category/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 后台分页查询
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/flowable/category/tree`, {
          params: {
            ...params,
            size: undefined,
            page: undefined,
          },
        })
        .then((res) => {
          deleteLeafArray(res.data.data, "children");
          this.tableData = res.data.data;
        });
    },
    // 点击新增
    handleAdd(row) {
      this.form.id = undefined;
      this.form.superLevel = undefined;
      this.form.categoryCode = undefined;
      this.form.categoryName = undefined;
      let seq = this.tableData.length
        ? `${Number(this.tableData[this.tableData.length - 1].seq) + 1}`
        : "1";
      if (row && row.children) {
        seq = `${Number(row.children[row.children.length - 1].seq) + 1}`;
      } else if (row) {
        seq = "1";
      }
      this.form.seq = seq;
      this.form.remark = undefined;
      this.form.parentId = row?.id || undefined;
      this.form.parentCategoryName = row?.categoryName || undefined;
      this.drawerVisible = true;
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      Object.keys(this.form).forEach((key) => {
        this.form[key] = row[key];
      });
      this.drawerVisible = true;
    },
    // 点击表格行内的删除
    handleDelete({ id }) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/flowable/category/${id}`)
            .then(() => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 关闭弹框
    handleCloseDrawer() {
      this.$refs.addForm.clearValidate();
      this.drawerVisible = false;
    },
    // 保存
    handleOk() {
      const req = { ...this.form };
      delete req.parentCategoryName;
      if (this.form.id) {
        this.$axios
          .put(`${ApiConstant.PREFIX_CORE}/api/flowable/category`, req)
          .then(() => {
            this.$message.success(this.$t("EDIT_SUCCESS"));
            this.drawerVisible = false;
            this.$refs.MomTable?.query();
          });
      } else {
        this.$axios
          .post(`${ApiConstant.PREFIX_CORE}/api/flowable/category`, req)
          .then(() => {
            this.$message.success(this.$t("ADD_SUCCESS"));
            this.drawerVisible = false;
            this.$refs.MomTable?.query();
          });
      }
    },
  },
};
</script>
<style lang="less">
.icon-defult {
  font-weight: 600;
}
</style>
