<template>
  <div>
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :action-buttons="actionButtons"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :show-util-operator="true"
      :total="total"
      :page.sync="page"
      :show-enable-flag="true"
      :auto-adaptive-width="false"
      @search="searchPageData"
      @beforeSearch="beforeSearch"
      @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'
          )
      "
    >
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('PAGE_DEV:ADD')"
          type="primary"
          @click="handleEdit()"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('PAGE_DEV:EXPORT')"
          class="btn__green-1"
          icon="to-top"
          :disabled="!tableData.length"
          @click="handleExportExcel"
        >
          {{ $t("EXPORT") }}
        </a-button>
        <a-button
          v-if="hasAuth('WAREHOUSE_CATEGORY_MANAGEMENT:DELETE')"
          type="danger"
          icon="delete"
          @click="() => handleDelete()"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <template slot="enableFlag" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ getAttrValue(enableFlagList, text) }}
        </span>
      </template>
      <template slot="pageIcon" slot-scope="text">
        <Icon v-if="text" :type="text" :size="18" />
      </template>
    </MomTable>
    <MegaDrawer
      :visible.sync="drawerVisible"
      :title="isAdd === true ? $t('ADD') : $t('EDIT')"
      width="520"
      @close="close"
    >
      <a-form-model
        slot="main"
        ref="ruleForm"
        layout="vertical"
        :model="ruleForm"
        :rules="rules"
      >
        <a-form-model-item :label="$t('PAGE_CODE')" prop="pageCode">
          <a-input
            v-model="ruleForm.pageCode"
            :disabled="!isAdd"
            :placeholder="$t('PLACEENTER')"
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('PAGE_NAME')" prop="pageName">
          <a-input
            v-model="ruleForm.pageName"
            :placeholder="$t('PLACEENTER')"
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('ICON')" prop="pageIcon">
          <MegaIconList v-model="ruleForm.pageIcon" :key-value="5" />
        </a-form-model-item>

        <a-form-model-item
          :label="$t('WHETHER_SINGLE_LAYOUT')"
          prop="singleComponent"
        >
          <a-radio-group v-model="ruleForm.singleComponent">
            <a-radio
              v-for="item in yOrNList"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</a-radio
            >
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item :label="$t('REMARK')" prop="remark">
          <a-input
            v-model="ruleForm.remark"
            allow-clear
            :placeholder="$t('PLACEENTER')"
          ></a-input>
        </a-form-model-item>
      </a-form-model>

      <div slot="footer" class="drawer-footer">
        <a-button type="primary" :loading="confirmLoading" @click="save">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="close">
          <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
        </a-button>
      </div>
    </MegaDrawer>
  </div>
</template>
<script>
import {
  Drawer as MegaDrawer,
  Icon,
  IconList as MegaIconList,
} from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { exportExcel } from "@/utils";

export default {
  components: {
    MegaDrawer,
    Icon,
    MegaIconList,
  },
  data() {
    return {
      enableFlagList: [],
      loading: false,
      yOrNList: [
        {
          label: this.$t("YES"),
          value: "Y",
        },
        {
          label: this.$t("NO"),
          value: "N",
        },
      ],
      isAdd: true,
      drawerVisible: false,
      ruleForm: {
        pageCode: "",
        pageName: "",
        pageIcon: undefined,
        singleComponent: "Y",
        remark: "",
      },
      queryForm: {
        pageCode: "",
        pageName: "",
      },
      tableData: [],
      page: 1, // 页码
      total: 0,
      actionButtons: [
        (h, { record }) =>
          this.hasAuth("PAGE_DEV:EDIT") && (
            <span
              class="text-primary cursor-pointer"
              title={this.$t("MODIFY")}
              onClick={() => this.handleEdit(record)}>
              <Icon type="icon-edit-edit" />
            </span>
          ),
        (h, { record }) =>
          this.hasAuth("PAGE_DEV:DESIGN") && (
            <span
              class="text-primary cursor-pointer"
              title={this.$t("PAGE_DESIGN")}
              onClick={() => this.handleDesign(record)}>
              <Icon type="icon-edit-b-pencil-ruler" />
            </span>
          ),
        (h, { record }) =>
          this.hasAuth("PAGE_DEV:DELETE") && (
            <span
              class="text-error cursor-pointer"
              title={this.$t("DELETE")}
              onClick={() => this.handleDelete(record)}>
              <Icon type="icon-edit-delete" />
            </span>
          ),
      ],
      confirmLoading: false,
      flag: true,
      editId: "",
      selectedRowKeys: [],
    };
  },

  computed: {
    queryFormItem() {
      return this.$observable("queryFormItem", {
        pageCode: {
          label: () => this.$t("PAGE_CODE"), // 页面编码
        },
        pageName: {
          label: () => this.$t("PAGE_NAME"), // 页面名称
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    tableColumns() {
      return this.$observable("tableColumns", [
        {
          dataIndex: "pageCode",
          width: 200,
          sorter: false,
          ellipsis: true,
          title: () => this.$t("PAGE_CODE"), // 页面编码
        },
        {
          dataIndex: "pageName",
          width: 200,
          ellipsis: true,
          sorter: false,
          title: () => this.$t("PAGE_NAME"), // 页面名称
        },
        {
          dataIndex: "pageIcon",
          sorter: false,
          title: () => this.$t("ICON"),
          width: 90,
          scopedSlots: { customRender: "pageIcon" },
        },
        {
          dataIndex: "remark",
          sorter: false,
          ellipsis: true,
          title: () => this.$t("REMARK"), // 备注
        },
        {
          dataIndex: "enableFlag",
          width: 120,
          sorter: false,
          title: () => this.$t("STATE"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
        },
      ]);
    },
    rules() {
      return {
        pageCode: [this.validateFieldLength(0, 16)],
        pageName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          this.validateFieldLength(1, 50),
        ],
        pageIcon: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        remark: [this.validateFieldLength(0, 16)],
      };
    },
  },
  methods: {
    beforeSearch() {
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        this.enableFlagList = res?.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: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/idewebpage/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleExportExcel() {
      const params = {
        page: this.page,
        size: this.$store.state.pagination.pageSize,
        ...this.queryForm,
      };
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/idewebpage/export`,
        method: "get",
        params,
        responseType: "blob",
      }).then((res) => {
        exportExcel(res.data, `${this.$t("PAGE_RESOURCES")}.xls`);
      });
    },

    searchPageData(params) {
      const p = {
        ...params,
        ...this.queryForm,
      };
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/idewebpage/search`, {
          params: p,
        })
        .then((res) => {
          const { records, total } = res.data.data;
          this.total = total;
          this.tableData = records;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    handleEdit(r) {
      if (r) {
        this.flag = false;
        this.isAdd = false;
        this.editId = r.id;
        this.loading = true;
        this.$axios
          .get(`${ApiConstant.PREFIX_CORE}/api/idewebpage/get-by-id/${r.id}`)
          .then((res) => {
            const { data } = res.data;
            this.ruleForm.singleComponent = data.singleComponent;
            this.ruleForm.remark = data.remark;
            this.ruleForm.pageCode = data.pageCode;
            this.ruleForm.pageName = data.pageName;
            this.ruleForm.pageIcon = data.pageIcon;
            this.loading = false;
            this.drawerVisible = true;
          })
          .catch(() => {
            this.confirmLoading = false;
          });
      } else {
        this.flag = true;
        this.isAdd = true;
        this.drawerVisible = true;
      }
    },
    save() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.flag) {
            this.confirmLoading = true;
            const p = { ...this.ruleForm };
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/idewebpage`, p)
              .then(() => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.close();
                this.$refs.MomTable?.query();
                this.confirmLoading = false;
              })
              .catch(() => {
                this.confirmLoading = false;
              });
          } else {
            this.confirmLoading = true;
            const p = { id: this.editId, ...this.ruleForm };
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/idewebpage`, p)
              .then(() => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.close();
                this.$refs.MomTable?.query();
                this.confirmLoading = false;
              })
              .catch(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },
    close() {
      this.drawerVisible = false;
      this.ruleForm.remark = "";
      this.ruleForm.singleComponent = "Y";
      this.ruleForm.pageCode = "";
      this.ruleForm.pageName = "";
      this.ruleForm.pageIcon = "";
    },
    handleDelete(r) {
      if (r || this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okType: "warning",
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            if (r) {
              this.$axios
                .delete(`${ApiConstant.PREFIX_CORE}/api/idewebpage/${r.id}`)
                .then(() => {
                  this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
                  this.$refs.MomTable?.query();
                });
            } else {
              this.$axios
                .delete(
                  `${ApiConstant.PREFIX_CORE}/api/idewebpage/batch-delete`,
                  { params: { ids: this.selectedRowKeys.join(",") } }
                )
                .then(() => {
                  this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
                  this.$refs.MomTable?.query();
                  this.selectedRowKeys = [];
                });
            }
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    handleDesign(row) {
      this.$router.push({
        path: "/upms/devCenter/tools/page-design",
        query: {
          id: row.id,
        },
      });
    },
  },
};
</script>
