<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="hasAuth('LAYOUT_MGMT:ENABLED')"
      :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('LAYOUT_MGMT:ADD')"
          type="primary"
          @click="handleEdit()"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('LAYOUT_MGMT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handleDelete()"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <div slot="enableFlag" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ getAttrValue(enableFlagList, text) }}
        </span>
      </div>
    </MomTable>
    <MegaDrawer
      :visible="drawerVisible"
      :title="isAdd === true ? $t('ADD') : $t('EDIT')"
      width="760"
      destroy-on-close
      @close="close"
    >
      <template slot="main">
        <a-form-model
          ref="ruleForm"
          style="width: 400px"
          layout="vertical"
          :model="ruleForm"
          :rules="rules"
        >
          <a-form-model-item :label="$t('LAYOUT_CODE')" prop="layoutCode">
            <a-input
              v-model="ruleForm.layoutCode"
              :disabled="!isAdd"
              :placeholder="$t('PLACEENTER')"
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('LAYOUT_NAME')" prop="layoutName">
            <a-input
              v-model="ruleForm.layoutName"
              :placeholder="$t('PLACEENTER')"
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('LAYOUT_JSON')" prop="layoutJson">
            <a-textarea
              v-model="ruleForm.layoutJson"
              :auto-size="{ minRows: 15, maxRows: 20 }"
              :placeholder="$t('PLACEENTER')"
              @change="(e) => previewLayout(e.target.value)"
            />
          </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 class="lay-content">
          <div class="preview-title">{{ $t("LAYOUT_PREVIEW") }}:</div>
          <GenerateArea2 :layouts="layoutData" :gutter="16" />
        </div>
      </template>
      <footer slot="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>
      </footer>
    </MegaDrawer>
  </div>
</template>
<script>
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import GenerateArea2 from "@/components/grid/GenerateArea2";

export default {
  components: {
    GenerateArea2,
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      enableFlagList: [],
      loading: false,
      yOrNList: [
        {
          label: this.$t("YES"),
          value: "Y",
        },
        {
          label: this.$t("NO"),
          value: "N",
        },
      ],
      queryForm: {
        layoutCode: "",
        layoutName: "",
      },
      tableData: [],
      page: 1, // 页码
      total: 0,
      actionButtons: [
        (h, { record }) =>
          this.hasAuth("LAYOUT_MGMT: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("LAYOUT_MGMT:DELETE") && (
            <span
              class="text-error cursor-pointer"
              title={this.$t("DELETE")}
              onClick={() => this.handleDelete(record)}>
              <Icon type="icon-edit-delete" />
            </span>
          ),
      ],
      selectedRowKeys: [],
      selectedRows: [],

      isAdd: true,
      drawerVisible: false,
      confirmLoading: false,
      flag: true,
      editId: "",
      ruleForm: {
        layoutCode: "",
        layoutName: "",
        layoutJson: "",
        remark: "",
      },
      layoutData: [],
    };
  },

  computed: {
    queryFormItem() {
      return this.$observable("queryFormItem", {
        layoutCode: {
          label: () => this.$t("LAYOUT_CODE"), // 布局编码
        },
        layoutName: {
          label: () => this.$t("LAYOUT_NAME"), // 布局名称
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRows = selectedRows;
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    tableColumns() {
      return this.$observable("tableColumns", [
        {
          dataIndex: "layoutCode",
          width: 200,
          sorter: false,
          ellipsis: true,
          title: () => this.$t("LAYOUT_CODE"), // 编码
        },
        {
          dataIndex: "layoutName",
          width: 200,
          ellipsis: true,
          sorter: false,
          title: () => this.$t("LAYOUT_NAME"), // 名称
        },
        {
          dataIndex: "remark",
          sorter: false,
          ellipsis: true,
          title: () => this.$t("REMARK"), // 备注
        },
        {
          dataIndex: "enableFlag",
          width: 120,
          sorter: false,
          title: () => this.$t("STATE"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
        },
      ]);
    },
    rules() {
      return {
        layoutCode: [this.validateFieldLength(0, 16)],
        layoutName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          this.validateFieldLength(1, 50),
        ],
        layoutJson: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error(this.$t("PLACEENTER")));
              }
              if (value && !this.ifJSON(value)) {
                callback(new Error(this.$t("LAYOUT_JSON_VALIDATE")));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        remark: [this.validateFieldLength(0, 50)],
      };
    },
  },
  methods: {
    previewLayout(val) {
      try {
        this.layoutData = JSON.parse(val);
      } catch (error) {
        this.layoutData = [];
      }
    },
    layoutTypeDicConverter(value) {
      return value === "GRID" ? this.$t("LAYOUT_GRID") : "";
    },
    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/ideweblayout/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },

    searchPageData(params) {
      const p = {
        ...params,
        ...this.queryForm,
      };
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/ideweblayout/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/ideweblayout/get-by-id/${r.id}`)
          .then((res) => {
            const { data } = res.data;
            this.ruleForm.remark = data.remark;
            this.ruleForm.layoutCode = data.layoutCode;
            this.ruleForm.layoutName = data.layoutName;
            this.ruleForm.layoutJson = data.layoutJson;
            this.previewLayout(data.layoutJson);
            this.loading = false;
            this.drawerVisible = true;
          })
          .catch(() => {
            this.confirmLoading = false;
          });
      } else {
        this.flag = true;
        this.isAdd = true;
        this.drawerVisible = true;
        this.layoutData = [];
      }
    },
    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/ideweblayout`, 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/ideweblayout`, 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.layoutJson = "";
      this.ruleForm.layoutCode = "";
      this.ruleForm.layoutName = "";
    },
    handleDelete(r) {
      if (r || this.selectedRows.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/ideweblayout/${r.id}`)
                .then(() => {
                  this.$message.success(this.$t("DELETE_SUCCESS"));
                  this.$refs.MomTable?.query();
                });
            } else {
              const arr = this.selectedRows.map((item) => item.id);
              const str = arr.toString();

              this.$axios
                .delete(
                  `${ApiConstant.PREFIX_CORE}/api/ideweblayout/batch-delete`,
                  { params: { ids: str } }
                )
                .then(() => {
                  this.$message.success(this.$t("DELETE_SUCCESS"));
                  this.selectedRows = [];
                  this.$refs.MomTable?.query();
                });
            }
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .ant-drawer-body {
  display: flex;
}
.lay-content {
  flex: 1;
  width: 100%;
  padding: 0 10px 0 10px;
  flex-shrink: 0;
}
.layout-render-wraper {
  height: 100%;
  margin-bottom: 24px;
  border-radius: 4px;
  border: 16px solid #f0f2f5;
  cursor: pointer;
}
.preview-title {
  margin-bottom: 10px;
}
</style>
