<template>
  <div id="app-container" class="app-container">
    <el-menu
      default-active="2"
      :collapse="true"
      style="background-color:#fff;border-right:1px solid #e0e0e0"
    >
      <!-- <el-menu-item index="1" @click="index = 1">
        <i class="el-icon-menu"></i>
        <span slot="title">模板</span>
      </el-menu-item> -->
      <el-menu-item index="2" @click="index = 2">
        <i class="el-icon-document"></i>
        <span slot="title">文本</span>
      </el-menu-item>
      <el-menu-item index="3" @click="index = 3">
        <i class="el-icon-picture"></i>
        <span slot="title">图片</span>
      </el-menu-item>
      <el-menu-item index="4" @click="index = 4">
        <i class="el-icon-setting"></i>
        <span slot="title">背景色</span>
      </el-menu-item>
      <el-menu-item index="5" @click="saveAllTheme">
        <i class="el-icon-upload"></i>
        <span slot="title">导出</span>
      </el-menu-item>
    </el-menu>
    <div class="left-pane">
      <ul class="poster-ct" v-if="index == 1">
        <li
          @click="handleEditorClick(i)"
          v-for="(item, i) in editorList"
          :key="i"
          class="poster-item"
        >
          <div class="poster-order">
            {{ i + 1 }}
          </div>
          <div :class="{ active: item.active }" class="poster-img cursor-p">
            <widget-view
              :background="item.content.background"
              :widget-list="item.content.widgetList"
            >
            </widget-view>
          </div>
        </li>
      </ul>
      <single-upload
        v-model="imgSrc"
        @input="checkImg"
        v-if="index == 2"
      ></single-upload>
      <el-button
        style="width:80%"
        size="mini"
        v-if="index == 3"
        @click="clickParent"
      >
        添加文本
      </el-button>
      <div v-if="index == 4">
        <div style="display:flex;align-items: center;padding-left: 20px">
          <span style="margin-right:20px">背景色</span>
          <el-color-picker
            v-model="textColor"
            @change="checkTextCol"
            class="w-60"
            show-alpha
            size="mini"
          ></el-color-picker>
        </div>
        <div style="margin-top:20px">
          <div style="float:left;padding-left: 20px;margin-bottom:10px">
            背景图片
          </div>
          <single-upload v-model="bgImgSrc" @input="checkBgImg"></single-upload>
        </div>
      </div>
      <!-- <div class="bottom-ct">
        <el-button @click="showImgSelection = true" size="mini"
          ><i class="el-icon-plus"></i> 新建</el-button
        >
        <el-button size="mini">取消</el-button>
        <el-button @click="saveAllTheme" size="mini">保存</el-button>
      </div> -->
    </div>
    <div class="right-pane">
      <template v-for="(item, i) in editorList">
        <posterEditor
          ref="child"
          @resetData="setData"
          :order="i"
          :id="id"
          v-model="item.content"
          v-show="item.active"
          :key="i"
          :page="
            i === 0 ? { width: 620, height: 375 } : { width: 620, height: 375 }
          "
          @active="handleEditorClick(i, 'active')"
        ></posterEditor>
      </template>
    </div>
    <!-- <blankDialog :padding="24" :contentHeight="520" v-model="showImgSelection">
      <imageSelection
        :is-single="false"
        @cancel="showImgSelection = false"
        @success="handleImageSelection"
      ></imageSelection>
    </blankDialog> -->
    <div>
      <vue-canvas-poster
        v-show="true"
        :painting="painting"
        @success="success"
        @fail="fail"
      ></vue-canvas-poster>
    </div>
  </div>
</template>

<script>
import posterEditor from '@/components/poster-editor/index.vue';
import blankDialog from '@/components/blankDialog';
import imageSelection from '@/components/imageSelection';
import widgetView from '../widgetView';
import { findComponentsDownward } from '@/utils/assist';
import singleUpload from '@/components/Upload/singleUpload';
import { VueCanvasPoster } from 'vue-canvas-poster';
export default {
  components: {
    posterEditor,
    blankDialog,
    imageSelection,
    widgetView,
    singleUpload,
    VueCanvasPoster
  },
  data() {
    return {
      id: null,
      painting: {},
      imgArr: '',
      index: 2,
      textColor: '',
      imgSrc: '',
      bgImgSrc: '',
      showImgSelection: false,
      editorList: [],
      activeEditorIndex: -1
    };
  },
  methods: {
    success(e) {
      this.imgArr = e;
    },
    fail(e) {
      console.log(e);
    },
    setData() {
      this.editorList = [
        {
          name: '蜘蛛侠',
          active: false,
          content: {
            background: {
              color: '#fff',
              img: ''
            },
            material_uid: '79b5ff3f-ab9a-4384-9904-aa96338202d2',
            materialType: '__vue_devtool_undefined__',
            widgetList: [
              {
                label: '图片',
                type: 'img',
                content: this.imgArr,
                uuid: '32a' + +new Date(),
                active: false,
                style: {
                  top: 129,
                  left: 86,
                  height: 120,
                  width: 120,
                  align: { x: 0, y: 0 },
                  lineHeight: 14,
                  fontSize: 14,
                  background: 'rgba(0, 0, 0, 0)',
                  color: 'rgba(0, 0, 0, 1)',
                  letterSpacing: 0,
                  isOblique: false,
                  isBold: false,
                  zIndex: 1
                },
                setDataRange: {
                  box: {
                    show: true,
                    detail: {
                      top: true,
                      left: true,
                      height: true,
                      width: true,
                      background: false,
                      zIndex: true
                    }
                  },
                  content: {
                    show: false
                  },
                  innerStyle: {
                    show: false,
                    detail: {
                      align: true,
                      lineHeight: true,
                      fontSize: true,
                      color: true,
                      letterSpacing: true,
                      isOblique: true,
                      isBold: true
                    }
                  }
                }
              },
              {
                label: '文本',
                type: 'text',
                content: '提货须知',
                uuid: '32b' + +new Date(),
                active: false,
                style: {
                  top: 108,
                  left: 269,
                  height: 40,
                  width: 120,
                  align: { x: 0, y: 0 },
                  lineHeight: 14,
                  fontSize: 18,
                  background: 'rgba(0, 0, 0, 0)',
                  color: 'rgba(0, 0, 0, 1)',
                  letterSpacing: 0,
                  isOblique: false,
                  isBold: true,
                  zIndex: 1
                },
                setDataRange: {
                  box: {
                    show: true,
                    detail: {
                      top: true,
                      left: true,
                      height: true,
                      width: true,
                      background: false,
                      zIndex: true
                    }
                  },
                  content: {
                    show: false
                  },
                  innerStyle: {
                    show: false,
                    detail: {
                      align: true,
                      lineHeight: true,
                      fontSize: true,
                      color: true,
                      letterSpacing: true,
                      isOblique: true,
                      isBold: true
                    }
                  }
                }
              },
              {
                label: '文本',
                type: 'text',
                content: `&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1. 微信或者手机浏览器扫码提货卡二维码，填写姓名、手机号、邮寄地址，点击“我要提货”<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2. 一个手机号仅限验证一次，提交地址后即可失效<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3. 有问题请联系客服 0551-63442479`,
                uuid: '32c' + +new Date(),
                active: false,
                style: {
                  top: 142,
                  left: 268,
                  height: 155,
                  width: 345,
                  align: { x: 0, y: 0 },
                  lineHeight: 30,
                  fontSize: 16,
                  background: 'rgba(0, 0, 0, 0)',
                  color: 'rgba(0, 0, 0, 1)',
                  letterSpacing: 0,
                  isOblique: false,
                  isBold: false,
                  zIndex: 1
                },
                setDataRange: {
                  box: {
                    show: true,
                    detail: {
                      top: true,
                      left: true,
                      height: true,
                      width: true,
                      background: false,
                      zIndex: true
                    }
                  },
                  content: {
                    show: false
                  },
                  innerStyle: {
                    show: false,
                    detail: {
                      align: true,
                      lineHeight: true,
                      fontSize: true,
                      color: true,
                      letterSpacing: true,
                      isOblique: true,
                      isBold: false
                    }
                  }
                }
              }
            ]
          }
        }
      ];
      this.handleEditorClick(0);
    },
    clickParent() {
      this.$refs.child[0].addWidget('text');
    },
    checkImg(e) {
      const a = {
        // active: false,
        // name: +new Date(),
        path: e
        // uid: 'a04c' + +new Date()
      };
      this.$refs.child[0].beforeAddImgWidget(a);
    },
    checkBgImg(e) {
      this.$refs.child[0].changeBackground(e);
    },
    checkTextCol(e) {
      this.$refs.child[0].changeTextColor(e);
    },
    fn() {},
    getEditorList() {
      const noticeItem = localStorage.getItem('notice');
      if (noticeItem == 'null') {
        this.editorList = [
          {
            name: '蜘蛛侠',
            active: false,
            content: {
              background: {
                color: '#fff',
                img: ''
              },
              material_uid: '79b5ff3f-ab9a-4384-9904-aa96338202d2',
              materialType: '__vue_devtool_undefined__',
              widgetList: []
            }
          }
          // {
          //   name: '美国队长',
          //   active: false,
          //   content: {
          //     background: {
          //       color: '#fff',
          //       img: ''
          //     },
          //     material_uid: 'a32c6558-1130-4e45-8d0d-efc6f887be50',
          //     materialType: '__vue_devtool_undefined__',
          //     widgetList: []
          //   }
          // }
        ];
      } else {
        this.editorList = [
          {
            name: '蜘蛛侠',
            active: false,
            content: JSON.parse(noticeItem)
          }
        ];
      }
      this.handleEditorClick(0);
    },
    handleEditorClick(i) {
      if (this.activeEditorIndex > -1) {
        let oldItem = this.editorList[this.activeEditorIndex];
        this.$set(this.editorList, this.activeEditorIndex, {
          ...oldItem,
          active: false
        });
      }
      let newItem = this.editorList[i];
      this.$set(this.editorList, i, { ...newItem, active: true });
      this.activeEditorIndex = i;
    },
    deleteEditor(i, item) {
      this.$confirm('确认删除该海报?').then(async () => {
        if (item.uid) {
          await global.dataFactory.deleteThemePosterItem(item.uid);
        }
        this.editorList.splice(i, 1);
      });
    },
    // handleImageSelection(data) {
    //   this.editorList.push(
    //     ...data.map(v => {
    //       return {
    //         name: v.name,
    //         active: false,
    //         content: {
    //           background: v.path,
    //           material_uid: v.uid,
    //           materialType: v.expandType,
    //           widgetList: []
    //         }
    //       };
    //     })
    //   );
    //   if (this.activeEditorIndex < 0) {
    //     this.handleEditorClick(0);
    //   }
    //   this.showImgSelection = false;
    // },
    async saveAllTheme() {
      const editors = findComponentsDownward(this, 'posterEditor');
      const activeEditorIndex = this.activeEditorIndex;
      const listData = this.editorList.slice(0);
      const tasks1 = [];
      editors.forEach(async e => {
        tasks1.push({
          fn: e.uploadCurrentPosterShot,
          index: e.order
        });
      });
      while (tasks1.length) {
        let current = tasks1.shift();
        await current
          .fn((file, done) => {
            return new Promise(resolve => {
              // console.log('截图成功', file);
              done('file');
              resolve('file');
            });
          })
          .then(path => {
            listData[current.index].path = path;
          });
      }
      await Promise.all(tasks1);
      this.editorList = listData;
      /* const tasks2 = []
      let fnMap = {
        update: global.dataFactory.updateThemePoster,
        create: global.dataFactory.createThemePoster
      }
      this.editorList.forEach(e => {
        const fn = e.uid ? fnMap.update : fnMap.create
        const args = [{
          content: e.content,
          name: e.name,
          theme: this.theme,
          path: e.path
        }]
        if (e.uid) args.unshift(e.uid)
        tasks2.push(
          fn(...args)
        )
        console.log(args)
      })
      await Promise.all(tasks2)
      console.log('请求完成') */
      this.handleEditorClick(activeEditorIndex);
    },
    // 获取主题海报
    getThemePoster() {
      global.dataFactory
        .getThemePosterList({
          theme_id: this.theme
        })
        .then(res => {
          let data = res.data.data.results;
          data.forEach(v => {
            v.active = false;
          });
          if (data.length) {
            this.$nextTick(() => this.handleEditorClick(0));
          }
          this.editorList = data || [];
        });
    }
  },
  beforeCreate() {
    localStorage.removeItem('itemImg');
  },
  created() {
    this.getEditorList();
    const { id } = this.$route.query;
    this.id = id;
    this.painting = {
      width: '120px',
      height: '120px',
      background: '#eee',
      views: [
        {
          type: 'qrcode',
          content: 'http://golden.shangqie.cn/#/?id=' + id,
          css: {
            top: '0',
            left: '0',
            color: '#000',
            width: '120px',
            height: '120px'
          }
        }
      ]
    };
    console.log(this.painting.views[0].content);
  }
};
</script>
<style lang="scss" scoped>
/deep/.el-upload-list {
  display: none;
}
/deep/.el-upload {
  width: 80%;
}
#app-container {
  display: flex;
  background: #fff;
  .left-pane {
    position: relative;
    padding-top: 15px;
    width: 276px;
    min-width: 276px;
    text-align: center;
    background: rgb(255, 255, 255);
    .header {
      margin: 10px 0 10px;
      color: #2c2c2c;
    }
    .poster-ct {
      .poster-item {
        margin-bottom: 15px;
        position: relative;
        .remove {
          display: none;
          position: absolute;
          top: 8px;
          right: 36px;
          width: 24px;
          height: 24px;
          box-sizing: border-box;
          border-radius: 50%;
          background: white;
          border: 1px solid #f56c6c;
          color: #f56c6c;
          z-index: 9;
          transition: all 0.3s linear;
        }
        &:hover {
          .remove {
            display: block;
          }
        }
        .poster-order {
          position: absolute;
          left: 8px;
          top: 8px;
        }
        .poster-img {
          box-sizing: border-box;
          margin-left: 24px;
          width: 240px;
          height: 180px;
          &.active {
            outline: 2px solid #409eff;
          }
        }
        .poster-name {
          display: flex;
          justify-content: center;
          align-items: center;
          margin: 8px 0;
          height: 40px;
          text-align: center;
          .input {
            display: none;
            transition: all 0.2s linear;
          }
          .text {
            transition: all 0.2s linear;
          }
          &:hover {
            .text {
              display: none;
            }
            .input {
              display: block;
            }
          }
        }
      }
    }
    .bottom-ct {
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      top: 0;
      left: 0;
      width: 276px;
      height: 48px;
      background: rgb(223, 223, 223);
    }
  }
  .right-pane {
    flex: 1;
  }
}
</style>
