<template>
  <div class="H5Editor">
    <van-popup
      v-model:show="leftEle"
      position="left"
      :style="{
        width: '600px',
        'background-color': '#f3f3f3',
        height: '100%',
      }"
    >
      <component
        v-if="H5Editor && leftEle"
        :is="H5EditorObj[H5Editor.type]"
        :item="H5Editor"
        :index="H5Editor.index"
      ></component>
    </van-popup>
    <div class="H5Editor_center">
      <div class="pageClient">
        <div class="page">
          <div
            class="pageMain"
            :style="{
              width: page.width + 'px',
              height: page.height ? page.height + 'px' : undefined,
              ...backgroundStyle(),
            }"
          >
            <div
              class="showList"
              v-for="(item, index) in hoversList[selectPage].components || []"
              :key="index"
            >
              <h5-image
                v-if="item.type === 'image'"
                :item="item"
                :index="index + ''"
                @addComponent="addComponent"
              ></h5-image>
              <!-- @saveParagraph="text => saveParagraph(text, index)" -->
              <h5-paragraph
                v-if="item.type === 'paragraph'"
                :item="item"
                :index="index + ''"
                @addComponent="addComponent"
              ></h5-paragraph>
              <h5-from-component
                v-if="item.type === 'fromComponent'"
                :index="index + ''"
                :item="item"
                @addComponent="addComponent"
              >
                <template
                  v-for="(v, i) in item.child_list || []"
                  :key="createKey(i)"
                >
                  <h5-van-field
                    v-if="v.type === 'van-field'"
                    :item="v"
                    :index="index + '-' + i"
                    @click="
                      () =>
                        selectComponent(
                          { ...v, leftEle: true },
                          index + '-' + i
                        )
                    "
                    @addComponent="addComponent"
                  ></h5-van-field>
                  <h5-van-buttom
                    v-if="v.type === 'van-buttom'"
                    :index="index + '-' + i"
                    :item="v"
                    @click="
                      () =>
                        selectComponent(
                          { ...v, leftEle: true },
                          index + '-' + i
                        )
                    "
                    @addComponent="addComponent"
                  ></h5-van-buttom>
                </template>
              </h5-from-component>
            </div>
          </div>
        </div>
      </div>
      <el-button-group class="saveGroup">
        <el-button type="primary" @click="savePageFunc">保存修改</el-button>
      </el-button-group>

      <el-dialog v-model="showpage" title="保存页面">
        <el-form :model="pageconfig">
          <el-form-item label="页面名称">
            <el-input v-model="pageconfig.name" />
          </el-form-item>
          <el-form-item label="页面描述">
            <el-input v-model="pageconfig.desc" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="savePage"> 保存 </el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog
        v-model="dialogVisible"
        :title="
          '请选择向' +
          (visbileData.type == 'bottom' ? '下' : '上') +
          '方添加的组件'
        "
        width="50vw"
      >
        <el-table :data="visbileData.list || []">
          <el-table-column property="title" label="组件名称">
            <template #default="scope">
              <span
                v-text="
                  scope.row.title
                    ? scope.row.title
                    : scope.row.attr
                    ? scope.row.attr.label
                    : scope.row.type
                "
              ></span>
            </template>
          </el-table-column>
          <el-table-column property="address" label="操作">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="() => addComponentItem(scope.row)"
              >
                添加
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
    <div class="H5Editor_right">
      <div v-for="(item, index) in hoversList" :key="item.url">
        <el-image
          @click="() => selectPageFunc(index, item)"
          :class="{ selectPage: selectPage === index }"
          :src="item.url"
          :fit="item.background_mode || 'fill'"
        />
        <div class="title">第 {{ index + 1 }} 页</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, provide } from 'vue';
import { useRoute } from 'vue-router';
import { createTemplateList, getComponentsList } from '../../api/index';
import { ElMessage } from 'element-plus';

// 中间显示模块组件
import H5Image from './components/H5Editor/img.vue';
import H5Paragraph from './components/H5Editor/paragraph.vue';
import H5FromComponent from './components/H5Editor/from.vue';
import H5VanField from './components/H5Editor/van_field.vue';
import H5VanButtom from './components/H5Editor/van_buttom.vue';

// 左侧编辑模块组件
import H5ImgEditor from './components/H5EditorLeft/imgEditor';
import H5VanFieldLeft from './components/H5EditorLeft/vanField';
import H5VanButtomLeft from './components/H5EditorLeft/vanButtom';
import H5ParagraphLeft from './components/H5EditorLeft/paragraph';

const H5EditorObj = {
  H5ImgEditor,
  H5VanFieldLeft,
  H5VanButtomLeft,
  H5ParagraphLeft,
};
const H5EditorObjEle = {
  image: 'H5ImgEditor',
  'van-field': 'H5VanFieldLeft',
  'van-buttom': 'H5VanButtomLeft',
  paragraph: 'H5ParagraphLeft',
  fromComponent: 'H5ParagraphLeft',
};

const dialogVisible = ref(false);
const visbileData = ref({});
const H5Editor = ref({});
const leftEle = ref(false);
const route = useRoute();
const item = JSON.parse(route.query.item || '{}');
const selectPage = ref(0);
const hoversList = ref(JSON.parse(JSON.stringify(item.hoversList)) || []);
const page = ref({ width: 375, height: 0 });
document.title = item.title;

const selectPageFunc = (index = 0) => {
  selectPage.value = index;
};
const selectComponent = (v, i) => {
  const type = H5EditorObjEle[v.type];
  H5Editor.value = { item: v, type, index: i };
  leftEle.value = v.leftEle || false;
};

const addComponent = (type, componentTyep, index) => {
  getComponentsList({}).then(r => {
    const li = r || [];
    const list = [];
    for (let i = 0; i < li.length; i++) {
      const v = li[i];
      if (componentTyep != 'van-field') {
        list.push(v);
        continue;
      } else if (componentTyep == 'van-field' && v.type == 'fromComponent') {
        for (let o = 0; o < v.child_list.length; o++) {
          const item = v.child_list[o];
          item.type == componentTyep && list.push(item);
        }
        break;
      }
    }
    dialogVisible.value = true;
    visbileData.value = {
      type,
      index,
      list,
    };
  });
};
const addComponentItem = r => {
  const row = JSON.parse(JSON.stringify(r));
  const indexs = visbileData.value.index.split('-');
  const page =
    hoversList.value
      ? hoversList.value[selectPage.value]
      : { components: [] };
  let i = visbileData.value.type === 'top' ? 0 : 1;
  if (indexs.length == 1) {
    page.components.splice(indexs[0] - 0 + i, 0, row);
  } else {
    page.components[indexs[0]].child_list.splice(indexs[1] - 0 + i, 0, row);
  }
  hoversList.value[selectPage.value] = page;
  dialogVisible.value = false;
};

// 查看页面大小，
const img = new Image();
img.src = hoversList.value[selectPage.value].background_url || '';

img.onload = function () {
  page.value.height = (this.height / this.width) * page.value.width;
};

const backgroundStyle = () => {
  const back = hoversList.value[selectPage.value].background_url;
  const color = /^#|^rgb/g.test(back);
  if (color)
    return {
      'background-color': back,
    };
  return {
    'background-image': 'url(' + back + ')',
  };
};

// 保存数据
// const saveParagraph = (paragraph, index) => {
//   console.log(paragraph, index);
// };

// 防止组件不刷新生成自定义key
const createKey = i => {
  return i + Date.now();
};

const showpage = ref(false);
const pageconfig = ref({
  name: '',
  desc: '',
});
const savePageFunc = () => {
  showpage.value = true;
  pageconfig.value.name = item.title;
  pageconfig.value.desc = item.h5Desc;
};

const savePage = () => {
  const data = {
    title: pageconfig.value.name,
    h5Desc: pageconfig.value.desc,
    hoversList: JSON.stringify(hoversList.value),
  };
  if (item.operateId) data.operateId = item.operateId;
  if (item.templateId) data.templateId = item.templateId;
  createTemplateList({
    data,
  }).then(() => {
    showpage.value = false;
    pageconfig.value.name = '';
    pageconfig.value.desc = '';
    ElMessage.success('保存成功');
  });
};

// provide 传递方法
provide('starEditorFormwork', (value, i) => {
  selectComponent(value, i);
});

provide('saveComponents', value => {
  const vList = value.index.toString().split('-');
  const list = JSON.parse(JSON.stringify(hoversList.value));
  if (vList.length == 1) {
    list[selectPage.value].components[vList[0]] = value.item;
  } else {
    // 2层组件
    list[selectPage.value].components[vList[0]].child_list[vList[1]] =
      value.item;
  }
  hoversList.value = list;
  leftEle.value = false;
  //   保存修改
});

provide('deleteItemComponents', value => {
  const vList = value.toString().split('-');
  const list = JSON.parse(JSON.stringify(hoversList.value));
  if (vList.length == 1) {
    list[selectPage.value].components.splice(vList[0], 1);
  } else {
    // 2层组件，只删除里层
    list[selectPage.value].components[vList[0]].child_list.splice(vList[1], 1);
  }
  hoversList.value = list;
  leftEle.value = false;
  //   删除组件
});
</script>

<style scoped>
.H5Editor_right .el-image {
  width: 184px;
  height: 280px;
  margin: 0 auto;
  display: block;
  border: 3px solid #fff;
}
.H5Editor {
  background-color: #d0cfd8;
  height: 100%;
  min-width: 1200px;
}

.H5Editor_center,
.H5Editor_right {
  display: inline-block;
  height: 100%;
}

.H5Editor_center {
  width: calc(100% - 300px);
  position: relative;
}

.H5Editor_center .pageClient {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 15px 5px;
  /* background-color: #000; */
  border-radius: 1em;
}

.H5Editor_center .page {
  width: 375px;
  height: 667px;
  background-color: #fff;
  overflow: auto;
}

.H5Editor_center .pageMain {
  min-height: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.H5Editor_right {
  overflow-y: auto;
  padding: 1em;
  width: 300px;
  background-color: #f3f3f3;
}

.H5Editor_right .selectPage {
  border: 3px solid #409eff;
}

.H5Editor_right .title {
  text-align: center;
  color: #333;
  padding: 8px 0;
  font-size: 14px;
}

.showList {
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0);
  position: relative;
}

.saveGroup {
  position: absolute;
  right: 2em;
  top: 1em;
}
</style>
