<template>
  <div class="box">
    <div class="title">打印模板设计器</div>
    <section>
      <div class="section">模板管理</div>
      <el-form :inline="true" :model="searchForm" size="small" label-width="80px" label-position="right">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="searchForm.name" clearable></el-input>
        </el-form-item>

        <el-form-item label="模板类型" prop="type">
          <el-select v-model="searchForm.type" clearable>
            <el-option v-for="(item, index) in typeArr" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="isDel">
          <el-select v-model="searchForm.isDel" clearable>
            <el-option v-for="(item, index) in isDelArr" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button size="mini" type="primary" @click="getList">查询模板</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tempList" style="width: 100%" size="mini" border>
        <el-table-column label="模板名称" prop="title"></el-table-column>
        <el-table-column label="模板类型">
          <template slot-scope="scope">
            <span>{{ getType(scope.row.type) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="模板状态">
          <template slot-scope="scope">
            <span>{{ getIsDel(scope.row.isDel) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="模板宽高">
          <template slot-scope="scope">
            <span>{{ scope.row.width + ' * ' + scope.row.height }}</span>
          </template>
        </el-table-column>
        <el-table-column label="纸张大小">
          <template slot-scope="scope">
            <span>{{ scope.row.pageWidth + 'mm * ' + scope.row.pageHeight + 'mm' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="right">
          <template slot="header">
            <el-button size="mini" type="primary" @click="openCreate">创建模板</el-button>
          </template>
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleEdit(scope.row)">设计</el-button>
            <el-button type="text" size="mini" @click="handlePreview(scope.row)">预览</el-button>
            <el-button type="text" size="mini" @click="handlePrint(scope.row)">打印</el-button>
            <el-button v-if="scope.row.isDel" type="text" size="mini" @click="handleRecover(scope.row)">恢复</el-button>
            <el-button v-if="!scope.row.isDel" type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text" size="mini" @click="handleCopy(scope.row)">复制新增</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="添加模板" :visible.sync="visible" width="310px">
        <el-form ref="form" :model="form" size="small" :rules="rules" label-width="80px">
          <el-form-item label="模板名称" prop="title">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="模板类型" prop="type">
            <el-select v-model="form.type">
              <el-option v-for="(item, index) in typeArr" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="模板宽度" prop="width">
            <el-input v-model="form.width"></el-input>
          </el-form-item>
          <el-form-item label="模板高度" prop="height">
            <el-input v-model="form.height"></el-input>
          </el-form-item>
          <el-form-item label="纸张宽度" prop="pageWidth">
            <el-input v-model="form.pageWidth"></el-input>
          </el-form-item>
          <el-form-item label="纸张高度" prop="pageHeight">
            <el-input v-model="form.pageHeight"></el-input>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="visible = false">取 消</el-button>
          <el-button type="primary" size="mini" @click="savaTemp">确 定</el-button>
        </div>
      </el-dialog>
    </section>
    <!-- <section v-if="false">
      <div class="section">模板打印测试</div>
      <el-form ref="printForm" :model="printForm" size="small" :rules="printRules" :inline="true">
        <el-form-item label="打印模板" prop="tempIndex">
          <el-select v-model="printForm.tempIndex">
            <el-option v-for="(item, index) in tempList" :key="index" :label="item.title" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测试数据" prop="data">
          <el-input type="textarea" style="width:520px" :rows="6" v-model="printForm.data"
            placeholder="数据模板对应的数据，数据格式为json对象"></el-input>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button size="mini" type="primary" @click="printPreview(1)">打印预览</el-button>
          </div>
          <div style="margin-top:10px">
            <el-button size="mini" type="success" @click="printPreview(2)">直接打印</el-button>
          </div>
        </el-form-item>
      </el-form>
    </section>
    <section v-if="false">
      <el-collapse>
        <el-collapse-item title="测试数据" name="1">
          <el-form ref="testData" :model="testData" size="small" :inline="true">
            <el-form-item label="出库数据">
              <el-input type="textarea" style="width:920px" :rows="8" v-model="testData.OutStock"
                placeholder="数据模板对应的数据，数据格式为json对象"></el-input>
            </el-form-item>
            <el-form-item label="入库数据">
              <el-input type="textarea" style="width:920px" :rows="8" v-model="testData.InStock"
                placeholder="数据模板对应的数据，数据格式为json对象"></el-input>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </section> -->
  </div>
</template>
<script>
import { Table, TableColumn, Dialog, MessageBox, Message } from 'element-ui'
import Vue from 'vue'
Vue.prototype.$confirm = (...args) => MessageBox.confirm(...args)
Vue.prototype.$message = Message
const baseUrl = process.env.VUE_APP_BASE_API;
import { OutStockData, InStockData } from '../data/test'
export default {
  data() {
    return {
      visible: false,
      tenantId: "",
      value: {},
      tempList: [],
      typeArr: [],
      searchForm: {
        name: '',
        type: '',
        isDel: ''
      },
      isDelArr: [
        { name: "正常", id: 0 },
        { name: "已删除", id: 1 },
      ],
      form: {
        title: '',
        type: '',
        width: '',
        height: '',
        pageWidth: '',
        pageHeight: ''
      },
      rules: {
        title: { required: true, message: '请输入模板名称' },
        type: { required: true, message: '请选择模板类型' },
        width: { required: true, message: '请输入模板宽度' },
        height: { required: true, message: '请输入模板高度' },
        pageWidth: { required: true, message: '请输入纸张宽度' },
        pageHeight: { required: true, message: '请输入纸张高度' },
      },
      printForm: {
        tempIndex: '',
        data: '',
      },
      printRules: {
        tempIndex: { required: true, message: '请选择模板' },
        data: { required: true, message: '请输入模板测试数据' },
      },
      testData: {
        OutStock: JSON.stringify(OutStockData),
        InStock: JSON.stringify(InStockData),
      },
    }
  },

  methods: {
    // 预览
    handlePreview(row) {
      console.log(row, 'row')
      if (row.tempItems) {
        this.$lodop.previewTemp(row)
      } else {
        this.$message.error("空模板无法预览，请先点击设计添加模板数据！")
      }
    },

    // 打印
    handlePrint(row) {
      console.log(row, 'row')
      if (row.tempItems) {
        this.$lodop.print(row)
      } else {
        this.$message.error("空模板无法打印，请先点击设计添加模板数据！")
      }
    },

    // 设计
    handleEdit(row) {
      console.log(row, 'row')
      // 初次新增时，没有tempItems(Arry)字段，需要手动添加
      if (!row.tempItems || !row.tempItems.length) {
        row.tempItems = []
      }
      this.$router.push({
        path: '/designer',
        query: {
          tenantId: this.tenantId,
          printData: row
        },
      })
    },

    // 恢复
    handleRecover(row) {
      console.log(row, 'row')
      this.deleteOrRecover(row, 0)
    },

    // 删除
    handleDelete(row) {
      console.log(row, 'row')
      this.$confirm('删除该模板？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteOrRecover(row, 1)
      }).catch(() => {

      });
    },

    deleteOrRecover(item, flag) {
      const data = {
        id: item.id,
        tenantId: this.tenantId,
        isDel: flag,
      }
      this.$axios.post(baseUrl + "/print/setTemplatesDel", data)
        .then(res => {
          console.log(res, 'res')
          if (res.data.code == 200) {
            this.$message.success(flag ? "删除成功！" : "恢复成功！")
            this.getData()
          } else {
            this.$message.error(flag ? "删除失败！" : "恢复失败！")
          }
        })
        .catch(err => {
          console.error(err);
          this.$message.error(flag ? "删除失败！" : "恢复失败！")
        });
    },

    getType(num) {
      let name
      this.typeArr.forEach(item => {
        if (item.id == num)
          name = item.name
      })
      return name
    },

    getIsDel(num) {
      let name
      this.isDelArr.forEach(item => {
        if (item.id == num)
          name = item.name
      })
      return name
    },

    //复制新增
    handleCopy(row) {
      const data = {
        id: row.id,
        tenantId: this.tenantId,
      }
      this.$axios.post(baseUrl + "/print/copyTemplates", data)
        .then(res => {
          if (res.data.code == 200) {
            this.$message.success("新增成功！")
            this.getData()
          } else {
            this.$message.error("新增失败！")
          }
        })
        .catch(err => {
          console.error(err);
          this.$message.error("新增失败！")
        });
    },

    // 新增
    openCreate() {
      this.visible = true
    },
    // 保存新增
    savaTemp() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = {
            tenantId: this.tenantId,
            title: this.form.title,
            type: this.form.type
          }
          this.addNewModel(data)
          this.visible = false
        }
      })
    },

    addNewModel(data) {
      this.$axios.post(baseUrl + "/print/saveTemplates", data)
        .then(res => {
          console.log(res, 'res')
          if (res.data.code == 200) {
            this.$message.success("新增成功！")
            this.getData()
          } else {
            this.$message.error("新增失败！")
          }
        })
        .catch(err => {
          console.error(err);
          this.$message.error("新增失败！")
        });
    },

    getData() {
      this.getPrintTypes()
      this.getList()
    },

    getPrintTypes() {
      this.$axios.get(baseUrl + "/print/types")
        .then(res => {
          console.log(res, 'res')
          this.typeArr = res.data.data
        })
        .catch(err => {
          console.error(err);
        });
    },

    getList() {
      const url = baseUrl +
        "/print/printTemplates?isDel=" +
        this.searchForm.isDel +
        "&name=" +
        this.searchForm.name +
        "&type=" +
        this.searchForm.type +
        "&tenantId=" +
        this.tenantId
      this.$axios.get(url)
        .then(res => {
          console.log(res, 'res')
          const arr = []
          res.data.data.forEach(item => {
            item.contentJson.isDel = item.isDel
            arr.push(item.contentJson)
          });
          this.tempList = arr
        })
        .catch(err => {
          console.error(err);
        });
    }
  },
  created() {
    Vue.use(Table)
    Vue.use(TableColumn)
    Vue.use(Dialog)
    this.tempList = []
    const tenantId = this.$route.query.tenantId
    if (tenantId) this.tenantId = tenantId
    this.getData()
  },
}
</script>
<style lang="scss" scoped>
.box {
  width: 1000px;
  margin: auto;
  padding: 10px 0;
  font-family: Arial, Helvetica, sans-serif;
}

.title {
  text-align: center;
  font-size: 24px;
  color: #1890ff;
  margin: 20px;
  font-weight: bold;
}

.section {
  font-size: 18px;
  color: #333333;
  padding: 10px 0;
}

.el-message-box {
  background-color: #1890ff;
}
</style>
