<template>
  <div class="page-design">
    <a-layout ref="PageDesign" class="page-design-wrapper">
      <a-layout class="page-design-container">
        <a-layout-content class="page-design-content">
          <!-- 根据布局数据渲染 -->
          <DesignArea
            ref="DesignArea"
            :layouts="layoutData.layoutData"
            :components="components"
            :multiple="multiple"
            :on-cp-inner-edit="onCpInnerEdit"
            :on-hide-cp-edit="closeCpEdit"
          />
        </a-layout-content>
        <a-layout-sider
          v-show="showCpEditArea"
          class="page-design-sider"
          :width="410"
        >
          <MegaForm
            ref="MegaForm"
            style="padding: 12px 14px"
            :query-param="cpAttrForm"
            :query-param-item="cpAttrFormItem"
          />

          <div class="sider-op">
            <a-button type="primary" @click="modifyCpAttr">
              <MegaIcon type="icon-cur-save_1" :size="18" />
              {{ $t("SAVE") }}
            </a-button>
            <a-button @click="cancelCpEditing">
              <MegaIcon type="icon-dir-f-rollback" :size="18" />
              {{ $t("CANCEL") }}
            </a-button>
          </div>
        </a-layout-sider>
      </a-layout>
    </a-layout>
    <div
      class="lay-list-drawer"
      :style="{
        left: visible ? 0 : '-229px',
        boxShadow: visible
          ? '0 0 20px 1px rgba(90, 104, 110, 0.3)'
          : '0 0 0 0 transparent',
      }"
    >
      <div class="lay-list-content">
        <GenerateArea2
          v-for="item in layList"
          :key="item.layoutName"
          :layouts="item.layoutData"
          :gutter="16"
          :class="{ active: layoutData.layoutName === item.layoutName }"
          @click.native="() => layoutChange(item)"
        />
      </div>
      <div class="lay-list-trigger" @click="toggleVisible">
        <div class="lay-list-trigger-text">
          <MegaIcon
            v-show="visible"
            type="icon-dir-f-double-left"
            :size="13"
          ></MegaIcon>
          <MegaIcon
            v-show="!visible"
            type="icon-dir-f-double-right"
            :size="13"
          ></MegaIcon>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Icon as MegaIcon, Form as MegaForm } from "@mega-design/ui-vue";
import cloneDeep from "lodash/cloneDeep";
import ApiConstant from "@/api/ApiConstant";
import { formatJson } from "@/utils/formatter";
import GenerateArea2 from "@/components/grid/GenerateArea2";
import DesignArea from "./DesignArea2.vue";

export default {
  components: {
    MegaIcon,
    MegaForm,
    DesignArea,
    GenerateArea2,
  },
  props: {
    layoutData: {
      type: Object,
      default: () => ({}),
    },
    components: {
      type: Array,
      default: () => [],
    },
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 所有布局数据列表
      layList: [],

      visible: true,

      showCpEditArea: false,
      editCpId: null,
      editCp: {
        layoutKey: undefined,
        id: undefined,
      },
      cpAttrForm: {}, // actived 组件属性列表
      cpAttrFormItem: {},
    };
  },
  created() {
    this.queryLayout();
  },
  methods: {
    queryLayout() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/ideweblayout/list`, {
          params: { enableFlag: "Y" },
        })
        .then((res) => {
          this.layList = res.data.data.map((item) => ({
            layoutName: item.layoutName,
            layoutData: formatJson(item.layoutJson) || [],
          }));
        });
    },
    closeCpEdit(cp) {
      if (cp === undefined) {
        this.showCpEditArea = false;
      } else if (cp && this.editCp?.id === cp?.id) {
        this.showCpEditArea = false;
      }
    },
    toggleVisible() {
      this.visible = !this.visible;
    },
    savePage() {
      // 获取布局和组件数据
      const cpsFn = this.$refs.DesignArea?.getPageData;
      return {
        layoutData: this.layoutData,
        components: cpsFn instanceof Function ? cpsFn() : [],
      };
    },
    layoutChange(layout) {
      if (this.components?.some((cps) => Boolean(cps.components.length))) {
        this.$confirm({
          title: this.$t("CONFIRM"),
          content: this.$t("DESIGN_AREA_CHANGE_TIP"),
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: true,
          onOk: () => {
            this.modifyLayoutData(layout);
          },
        });
      } else {
        this.modifyLayoutData(layout);
      }
    },
    modifyLayoutData(layout) {
      this.$set(this.layoutData, "layoutName", layout.layoutName);
      this.$set(this.layoutData, "layoutData", layout.layoutData);
      // 删除其他布局key中的组件列表
      this.components.forEach((cps) => {
        // eslint-disable-next-line no-param-reassign
        cps.components = [];
      });
      this.visible = false;
    },
    onCpInnerEdit(cp, layoutKey) {
      if (this.editCp.layoutKey === layoutKey && this.editCp.id === cp.id) {
        this.showCpEditArea = !this.showCpEditArea;
      } else {
        this.editCp.id = cp.id;
        this.editCp.layoutKey = layoutKey;
        this.showCpEditArea = true;
      }
      // 获取组件属性(和值)
      if (this.showCpEditArea) {
        this.$axios
          .get(
            `${ApiConstant.PREFIX_CORE}/api/idewebcomponent/get-by-id/${cp.id}`
          )
          .then((res) => {
            this.$set(this, "cpAttrForm", {});
            this.$set(this, "cpAttrFormItem", {});
            res.data.data.attributeList?.forEach(async (attr) => {
              let value =
                cp.attrs[attr.attrKey] || attr.defaultValue || undefined;
              if (["Float", "Integer"].includes(attr.attrValueType)) {
                value = Number(value || 0) || undefined;
              } else if (attr.attrValueType === "Boolean") {
                value = value === "true";
              } else if (attr.attrValueType === "Array") {
                try {
                  value = formatJson(value) || [];
                } catch (_err) {
                  value = [];
                }
              } else if (typeof value === "object") {
                value = value.trim();
              }
              this.$set(this.cpAttrForm, attr.attrKey, value);

              const formItem = {
                label: () => this.$t(attr.attrName),
                rules: [],
              };
              // itemType
              if (attr.inputMode !== "MANUAL") {
                formItem.itemType = "select";
                formItem.options = [];
                formItem.optionsProps = {
                  label: "label",
                  value: "value",
                };
              }
              if (["Float", "Integer"].includes(attr.attrValueType)) {
                formItem.itemType = "inputNumber";
              }
              // rules
              if (attr.attrMust === "Y") {
                formItem.rules.push("required");
              }
              // 请求
              if (attr.inputMode === "DICT") {
                try {
                  const response = await this.$axios.get(
                    `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/${attr.valueSource}`
                  );
                  formItem.options = response.data.data || [];
                } catch (_e) {}
              } else if (attr.inputMode === "INTERFACE") {
                try {
                  const response = await this.$axios.get(attr.valueSource);
                  formItem.options = response.data.data || [];
                } catch (_e) {}
              }

              this.$set(this.cpAttrFormItem, attr.attrKey, formItem);
            });
          });
      }
    },
    modifyCpAttr() {
      this.$refs.MegaForm?.$refs.MegaRuleForm.validate((valid) => {
        if (valid) {
          this.components.forEach((item, index) => {
            if (item.layoutKey === this.editCp.layoutKey) {
              item.components.forEach((e, i) => {
                if (e.id === this.editCp.id) {
                  this.$set(
                    this.components[index].components[i],
                    "attrs",
                    cloneDeep(this.cpAttrForm)
                  );
                }
              });
            }
          });
          this.showCpEditArea = false;
        }
      });
    },
    cancelCpEditing() {
      this.showCpEditArea = false;
    },
  },
};
</script>

<style lang="less" scoped>
.page-design {
  position: absolute;
  width: 100%;
  height: 100%;
  &-wrapper,
  &-container {
    position: relative;
    width: 100%;
    height: 100%;
    background-color: #fff;
    z-index: 10;
  }
  &-content {
    padding: 1px;
    background-image: url("data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' stroke='%23808080' stroke-width='1' stroke-dasharray='6%2c 6' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e");
  }
  &-sider {
    position: relative;
    background-color: #f4f7f9;
    padding-bottom: 60px;
    .sider-op {
      position: absolute;
      bottom: 12px;
      width: 100%;
      text-align: center;
    }
  }
  .lay-list-drawer {
    position: absolute;
    width: 228px;
    height: 100%;
    top: 0;
    z-index: 20;
    transition: all 0.3s;
    .lay-list-content {
      position: absolute;
      width: 100%;
      height: 100%;
      padding: 24px 34px;
      overflow-y: auto;
      background: #fff;
    }
    .layout-render-wraper {
      height: 90px;
      margin-bottom: 24px;
      border-radius: 4px;
      border: 16px solid #f0f2f5;
      cursor: pointer;
      &:last-of-type {
        margin-bottom: 0;
      }
      &.active::after {
        content: "";
        position: absolute;
        width: calc(100% + 32px + 20px);
        height: calc(100% + 32px + 20px);
        left: -26px;
        top: -26px;
        border: 2px dashed #006896;
      }
    }
    .lay-list-trigger {
      position: absolute;
      width: 32px;
      height: 107px;
      top: 50%;
      right: -31px;
      line-height: 107px;
      transform: translate(0, -50%);
      cursor: pointer;
      background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAABrCAYAAAAW5YBbAAA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haGHXEgT2h80vfH3d/vqX3//44PLV63cFhEqSBMfWKQYApahTsVaIUEoLd2Cxgg3tc7GrtgjARyHVqnX12+9vzFz76rtlTSdEsTS6psRpv1qEUoCFwUEG+5ycFfUstMZAQAxMXWd5Of/6xMT0F1XIQzxFiJieSNepb8E0j0I5FmXtm6Yl/78l2FKZUrk89+rYxKSwUAYLPUqZFqAcgwDhOC9DGVZkGYSF9gCUyhdeO5F+V/MocRKE1LNQpLHDh6mVRaxQQKytAGapNP/GyZNnPAIKuOKJtUHMCFEGtNRFxc5pHoUyLC62x4BZKs+PvHX6rEsoSRrYUzSNWq5LZA7+htlwyGE+QH02yjC2LgOmWbo4dnryrEdgq0AxT0zJquMQ2Mk2ctBugFLp4vETE1MSgGNPEzkol6lhvER0vQeCqMOqCEEMTsfWGVgzzY9G3h6fYmJwj5B4PElsmI5Gby/RH/fQfH4NNigIYjsBxk5NTjOEPQ4liCcpgSVZArj3ESzLMBP2G6BsWTRx4ACJPeqgbQd4tLb28ZvvpKUBhhRPLEg1zyMRQGQgMhAZiAxEBiIDkYHIQGQgMhAZiAxEBiIDkYHIQGQgMhAZiAxEBiID+2ZAnJg8eWCxr+cF2wHs+4lJqGdGcHAZ7qnZc3BuGPbJadhnx6WwT89D7R8QHRS51cLo+Kkz1/a7gyK0HpLwumhC6yMKrZNK9pItLc+Ovzf75b72koXWTRdmP2F4HZWh9pSG3lUbel9x6J3V4feWh91d/zw8XxDuExahP2MS+lM20FQY8nNG9fbU0J60+hc3lEw+MSdPswAAAABJRU5ErkJggg==");
      &-text {
        width: 18px;
        text-align: center;
      }
    }
  }
}
</style>

<style lang="less">
.page-design-sider {
  .ant-layout-sider-children {
    overflow-y: auto;
  }
}
</style>
