<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="{
        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 :label="$t('FORM_NAME')" prop="formName">
            <a-input v-model="form.formName" />
          </a-form-model-item>
          <a-form-model-item :label="$t('FORM_ID')" prop="formCode">
            <a-input v-model="form.formCode" />
          </a-form-model-item>
          <a-form-model-item :label="$t('PC_ADDRESS')" prop="pcUrl">
            <a-input v-model="form.pcUrl" />
          </a-form-model-item>
          <a-form-model-item :label="$t('MOBILE_ADDRESS')" prop="mobileUrl">
            <a-input v-model="form.mobileUrl" />
          </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: "formName",
          sorter: false,
          title: () => this.$t("FORM_NAME"), // 表单名称
        },
        {
          dataIndex: "formCode",
          sorter: false,
          title: () => this.$t("FORM_ID"), // 表单标识
        },
        {
          dataIndex: "pcUrl",
          sorter: false,
          title: () => this.$t("PC_ADDRESS"), // PC端地址
        },
        {
          dataIndex: "mobileUrl",
          sorter: false,
          title: () => this.$t("MOBILE_ADDRESS"), // 移动端地址
        },
        {
          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: {
        formName: "",
        formCode: "",
      },
      actionButtons: ["edit", "delete"],

      drawerVisible: false,
      isEdit: false,

      form: {
        id: undefined,
        formName: undefined,
        formCode: undefined,
        pcUrl: undefined,
        mobileUrl: undefined,
      },
    };
  },
  computed: {
    // 表格搜索配置
    queryFormItem() {
      return this.$observable("queryFormItem", {
        formName: {
          itemType: "input",
          label: () => this.$t("FORM_NAME"), // 表单名称
        },
        formCode: {
          itemType: "input",
          label: () => this.$t("FORM_ID"), // 表单标识
        },
      });
    },
    rules() {
      return {
        formName: [{ required: true, message: this.$t(""), target: "blur" }],
        formCode: [{ required: true, message: this.$t(""), target: "blur" }],
      };
    },
  },
  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/form/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/form/search`, { params })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 点击新增
    handleAdd() {
      this.form.id = undefined;
      this.form.formName = undefined;
      this.form.formCode = undefined;
      this.form.pcUrl = undefined;
      this.form.mobileUrl = undefined;
      this.isEdit = false;
      this.drawerVisible = true;
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      Object.keys(this.form).forEach((key) => {
        this.form[key] = row[key];
      });
      this.isEdit = true;
      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/form/${id}`)
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 关闭弹框
    handleCloseDrawer() {
      this.$refs.addForm.clearValidate();
      this.drawerVisible = false;
    },
    // 保存
    handleOk() {
      if (this.form.id) {
        this.$axios
          .put(`${ApiConstant.PREFIX_CORE}/api/flowable/form`, this.form)
          .then(() => {
            this.$message.success(this.$t("EDIT_SUCCESS"));
            this.drawerVisible = false;
            this.$refs.MomTable?.query();
          });
      } else {
        this.$axios
          .post(`${ApiConstant.PREFIX_CORE}/api/flowable/form`, this.form)
          .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>
