<template>
  <div class="app-container">
    <div class="filter-container">

      <el-input v-model="search.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>

      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreateAdd">
        增加版式定义
      </el-button>
      <div class="top-right-btn">
        <el-tooltip effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getTemplateInfo" />
        </el-tooltip>
      </div>
    </div>
    <el-table
      :data="tableData"
      v-loading="listLoading"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      default-expand-all>
      <el-table-column
        prop="templateName"
        label="版式名称">
      </el-table-column>
      <el-table-column
        label="版式规格"
      >
        <template slot-scope="{row}">
          {{row.width}}px * {{row.height}}px
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag v-if="row.status==0" type="success">
            正常
          </el-tag>
          <el-tag v-else="row.status==1" type="danger">
            禁用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="left" label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button @click="handleLook(row)" type="success" size="mini">
            查看版式
          </el-button>
          <el-button @click="handleUpdate(row)" type="primary" size="mini">
            编辑
          </el-button>
          <el-button @click="editStatus(row.id,'1')" type="danger" v-if="row.status==0" size="mini">
            禁用
          </el-button>
          <el-button @click="editStatus(row.id,'0')" v-else="row.status==1" size="mini">
            启用
          </el-button>

        </template>
      </el-table-column>

    </el-table>
    <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible" width="80%">
      <el-form label-width="130px" label-position="right">
        <el-form-item label="版式名称">
          <el-input v-model="form.templateName"></el-input>
        </el-form-item>
        <el-form-item label="版式长度">
          <el-input v-model="form.width"></el-input>
        </el-form-item>
        <el-form-item label="版式宽度">
          <el-input v-model="form.height"></el-input>
        </el-form-item>
        <el-form-item label="纸杯长度">
          <el-input v-model="form.itemWidth"></el-input>
        </el-form-item>
        <el-form-item label="纸杯宽度">
          <el-input v-model="form.itemHeight"></el-input>
        </el-form-item>
        <el-form-item label="版式列数">
          <el-input v-model="form.colCount" @change="rebuildRowDataList"></el-input>
        </el-form-item>
        <el-form-item label="版式行数">
          <el-input v-model="form.rowCount" @change="rebuildRowDataList"></el-input>
        </el-form-item>
        <el-form-item label="版式设置">
<!--          <el-button @click="innerVisible = true">元素设置</el-button>-->
          <el-table :show-header='headerState'  border :data="rowDataList" highlight-current-row>
            <el-table-column v-for="count in colNum" :key="count" align="center"  class="tableItem" >
              <template slot-scope="scope">
<!--                {{colNum}},-->
<!--                {{count}}-->
<!--                {{scope.row.colData[(index-1)]}}-->
                <el-input class="tableItemInput" v-model="scope.row.colData[count-1].width" placeholder="横向" @change="itemXChange(scope.$index,(count-1))"></el-input>
                <el-input class="tableItemInput" v-model="scope.row.colData[count-1].height" placeholder="纵向" @change="itemYChange(scope.$index,(count-1))"></el-input>
                <el-input class="tableItemInput" v-model="scope.row.colData[count-1].rotate" placeholder="角度" @change="itemRotateChange(scope.$index,(count-1))"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='1'?addBtn():editBtn()">确 定</el-button>
      </div>

    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="查看版式" :visible.sync="lookVisible" width="80%">

      <transition-group name="fade" tag="div" class="container" :style="{width:`${lookDiv.width}px`,height:`${lookDiv.height}px`}">
        <div
          class="item"
          v-for="(item,index) in lookDiv.itemList"
          :key="index"
          :style="{transform:`rotate(${item.itemRotate}deg)`,left:`${item.itemLeft}px`,top:`${item.itemTop}px`, width:`${lookDiv.itemWidth}px`,height:`${lookDiv.itemHeight}px`}">
          {{item.key}}
          <!--      <img :src="item.bgUrl" alt="">-->
        </div>
      </transition-group>
    </el-dialog>
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
  </div>
</template>

<script>
import { getCupPlateTemplateList, addCupPlateTemplate, getCupPlateTemplateInfoById, updateCupPlateTemplate } from '@/api/baseInfo/formatInfo.js'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import Pagination from '@/components/Pagination'

const form = {
  templateName: '', // 版式名称,
  width: '', // 版式长度，列表直接显示width*height，毫米单位,
  height: '', // 版式宽度，列表直接显示width*height，毫米单位,
  itemWidth: '', // 纸杯长度,
  itemHeight: '', // 纸杯宽度,
  colCount: 1, // 版式列数,
  rowCount: 1, // 版式行数,
  itemList: []// 元素数组、增加和修改时需要传入,
}

const tableItem = {
  key: '',
  width: '',
  height: '',
  rotate: ''
}
const templateItem = {
  itemLeft: '',
  itemTop: '',
  itemWidth: '',
  itemHeight: '',
  itemRotate: '',
  itemCol: '',
  itemRow: ''
}

export default {
  components: {
    Cancledialog, Pagination
  },
  // filters: {
  //   statusFilter(status) {
  //     const statusMap = {
  //       1: 'success',
  //       0: 'danger'
  //     }
  //     return statusMap[status]
  //   }
  // },
  data() {
    return {
      dialogStatus: 1, // 1增加，2修改
      dialogTitle: '',
      dialogVisible: false,

      lookVisible: false,

      search: {
        keyWord: ''
      },
      form: Object.assign([], form),

      confirmdialog: false,
      listLoading: false,
      tableData: [],

      colNum: 1,

      lookDiv: {},
      items: [
        { key: 1, width: '250px', height: '125px', top: '0', left: '0', rotate: '0' },
        { key: 2, width: '250px', height: '125px', top: '0', left: '240px', rotate: '180' },
        { key: 3, width: '250px', height: '125px', top: '0', left: '470px', rotate: '0' },
        { key: 4, width: '250px', height: '125px', top: '0', left: '700px', rotate: '180' },
        { key: 5, width: '250px', height: '125px', top: '120px', left: '0', rotate: '0' },
        { key: 6, width: '250px', height: '125px', top: '120px', left: '240px', rotate: '180' }
      ],

      // 元素设置参数
      headerState: false,
      rowDataList: [
        {
          id: '1',
          colData: [{
            key: 'col_1',
            width: '',
            height: '',
            rotate: ''
          }]
        }
      ],

      colDataList: [
        {
          key: '1',
          width: '',
          height: '',
          rotate: ''
        }
      ],
      dataItemList: []

    }
  },
  mounted() {
    this.getTemplateInfo()
  },
  methods: {
    // 获取列表
    getTemplateInfo() {
      const _that = this
      _that.listLoading = true
      const params = _that.search
      const data = {
        'params': JSON.stringify(params)
        // "page": JSON.stringify(page),
      }
      // console.log(data);
      getCupPlateTemplateList(data).then(response => {
        console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },

    // 增加版式定义
    handleCreateAdd() {
      const _that = this
      _that.form = Object.assign({}, form)
      _that.dialogTitle = '增加版式定义'
      _that.dialogStatus = '1'
      _that.dialogVisible = true
      _that.rowDataList = [
        {
          id: '1',
          colData: [{
            key: '1',
            width: '',
            height: '',
            rotate: ''
          }]
        }
      ]
      _that.colDataList = [
        {
          key: '1',
          width: '',
          height: '',
          rotate: ''
        }
      ]
      _that.rebuildRowDataList()
    },
    createList() {
      const _that = this
      const itemList = []
      const rowDataList = _that.rowDataList

      rowDataList.forEach((item, index) => {
        const data = item.colData
        console.log('itemRow', item)
        for (let i = 0; i < data.length; i++) {
          const template = JSON.parse(JSON.stringify(templateItem))
          template.itemLeft = data[i].width
          template.itemTop = data[i].height
          template.itemRotate = data[i].rotate
          template.itemCol = data[i].col
          template.itemRow = item.id
          itemList.push(template)
        }
      })
      _that.form.itemList = itemList
    },
    // 增加档案
    addBtn() {
      const _that = this
      _that.createList()

      console.log(_that.form)

      const info = JSON.stringify(_that.form)
      // console.log(info);
      // return;
      const data = {
        'plateTemplate': info
      }
      // console.log(data);
      // return

      addCupPlateTemplate(data).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '增加成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 唤起修改
    handleUpdate(row) {
      const _that = this

      _that.dialogTitle = '修改版式定义'
      _that.dialogVisible = true
      _that.dialogStatus = '2'
      const idPrint = row.id
      const data = {
        idTemplate: idPrint
      }
      // console.log(data);
      getCupPlateTemplateInfoById(data).then(res => {
        console.log(res)
        const data = res.data

        _that.form = {
          id: data.id,
          templateName: data.templateName,
          width: data.width,
          height: data.height,
          itemWidth: data.itemWidth,
          itemHeight: data.itemHeight,
          colCount: data.colCount,
          rowCount: data.rowCount,
          itemList: data.itemList
        }
        _that.colNum = data.colCount

        _that.dataItemList = data.itemList
        _that.parseItemList(_that.dataItemList)
        _that.rebuildRowDataList()
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 修改档案
    editBtn() {
      const _that = this
      _that.createList()
      const info = JSON.stringify(_that.form)
      const data = {
        'plateTemplate': info
      }
      // console.log(data);
      // return;

      updateCupPlateTemplate(data).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '修改成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 查看版式
    handleLook(row) {
      var _that = this
      _that.lookVisible = true

      const idPrint = row.id
      const data = {
        idTemplate: idPrint
      }
      // console.log(data);
      getCupPlateTemplateInfoById(data).then(res => {
        // console.log(res);
        const data = res.data
        _that.lookDiv = data
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 刷新变革
    tableRefresh() {
      // 刷新变革
      this.getTemplateInfo()
    },

    // 启用禁用
    editStatus(id, status) {
      const _that = this
      const printerTypeInfo = {
        id: id,
        status: status
      }
      const params = {
        'plateTemplate': JSON.stringify(printerTypeInfo)
      }

      const url = '/cup/voidCupPlateTemplate'
      _that.$refs.confirmDialog.updataClick(params, url)
    },

    // 搜索
    searchData() {
      this.getTemplateInfo()
    },

    rebuildRowDataList() {
      // console.log('渲染列表');
      var _that = this
      var colCount = _that.form.colCount
      var rowCount = _that.form.rowCount
      var rowList = _that.rowDataList
      // console.log(colCount);
      _that.colNum = Number(colCount)
      var oldColCount = 0
      if ((rowList) && (rowList.length > 0)) {
        oldColCount = rowList[0].colData.length
      }

      var oldRowCount = 0
      if ((rowList) && (rowList.length > 0)) {
        oldRowCount = rowList.length
      }

      if (rowCount < oldRowCount) {
        rowList.splice(rowList.length - (oldRowCount - rowCount), (oldRowCount - rowCount))
        // console.log(rowList);
      }

      if (rowCount > oldRowCount) {
        var newcolData = []
        // console.log('oldColCount',oldColCount);
        for (let i = 1; i <= oldColCount; i++) {
          newcolData.push(
            {
              key: i,
              width: '',
              height: '',
              rotate: ''
            })
        }
        // console.log('newcolData',newcolData);
        for (let i = 1; i <= rowCount - oldRowCount; i++) {
          rowList.push(
            {
              id: oldRowCount + i,
              colData: newcolData
            })
        }
      }

      if (colCount < oldColCount) {
        rowList.forEach(x => {
          x.colData.splice(x.colData.length - (oldColCount - colCount), (oldColCount - colCount))
        })
      }

      if (colCount > oldColCount) {
        rowList.forEach(x => {
          for (let i = 1; i <= colCount - oldColCount; i++) {
            x.colData.push(
              {
                key: oldColCount + i,
                width: '',
                height: '',
                rotate: ''
              })
          }
        })
      }

      // console.log('数据',rowList);
      _that.rowDataList = rowList
    },

    parseItemList(itemList) {
      // console.log(itemList);
      var _that = this
      const colDataList = []
      const rowDataList = []
      let i = 1

      itemList.forEach(item => {
        if (item.itemRow == 1) {
          colDataList.push({ key: String(i) })
          i++
        }
      })
      // console.log(rowDataList);

      var map = new Map()
      var newArr = []
      itemList.forEach((item, index) => {
        map.has(item.itemRow) ? map.get(item.itemRow).push(item) : map.set(item.itemRow, [item])
      })
      newArr = [...map.values()]
      // console.log(newArr);
      newArr.forEach((item, index) => {
        var rowData = {}
        rowData['id'] = index + 1
        rowData['colData'] = []
        item.forEach((child, j) => {
          rowData['colData'].push({
            key: child.itemCol,
            width: child.itemLeft,
            height: child.itemTop,
            rotate: child.itemRotate
          })
        })
        rowDataList.push(rowData)
      })

      // console.log('获取信息渲染',rowDataList);
      _that.colDataList = colDataList
      _that.rowDataList = rowDataList
    },

    // X方向同步
    // rowIndex为行坐标，colIndex为列坐标
    itemXChange(rowIndex, colIndex) {
      const _that = this
      if (rowIndex == 0) {
        const xNum = _that.rowDataList[0].colData[colIndex].width
        // console.log(xNum);
        _that.rowDataList.forEach((item, index) => {
          // console.log(item);
          if (index != 0) {
            item.colData[colIndex].width = xNum
          }
        })
      }
    },
    // y方向同步
    // rowIndex为行坐标，colIndex为列坐标
    itemYChange(rowIndex, colIndex) {
      const _that = this
      // 当第一列的y坐标输入
      if (colIndex == 0) {
        const YNum = _that.rowDataList[rowIndex].colData[0].height// 获取当前第一列输入的y坐标
        // console.log(YNum);
        // 对当前行的所有y坐标值赋值
        _that.rowDataList[rowIndex].colData.forEach((item, index) => {
          // console.log(item);
          if (index != 0) {
            item.height = YNum
          }
        })
      }
    },
    // 旋转角度同步
    // rowIndex为行坐标，colIndex为列坐标
    itemRotateChange(rowIndex, colIndex) {
      const _that = this
      if (rowIndex == 0) {
        const rotateNum = _that.rowDataList[0].colData[colIndex].rotate
        // console.log(rotateNum);
        _that.rowDataList.forEach((item, index) => {
          // console.log(item);
          if (index != 0) {
            item.colData[colIndex].rotate = rotateNum
          }
        })
      }
    }

  }
}
</script>

<style lang="scss" scoped>
  .filter-container {
    margin-bottom: 15px;
  }
  .container{
    position: relative;
    display:flex;
    flex-direction: column;
    padding: 0;
    margin: 40px;
    border: 1px solid #99a9bf;
    //transform:scale(0.35,0.35);
    //-ms-transform:scale(0.35,0.35); 	/* IE 9 */
    //-moz-transform:scale(0.35,0.35); 	/* Firefox */
    //-webkit-transform:scale(0.35,0.35); /* Safari 和 Chrome */
    //-o-transform:scale(0.35,0.35); 	/* Opera */
    transform-origin: 0 0;
  }
  .item {
    display: -webkit-box;
    -webkit-box-align: center;
    -webkit-box-pack: center;
    position: absolute;
    /*transition: all linear 0.3s;*/
    transition-timing-function:ease ;
    background: url("../../../assets/img/1.png") no-repeat;
    background-size: cover;
    border: 1px solid #42b983;
  }

  .tableItemInput{
    width: 30%;
  }
</style>
