<template>
  <div class="print-template">
    <module-view :propConfig="config" ref="view" v-loading="load" @pagination="pagination" @onRefresh="getList" @resert="queryList" @search="queryList" 
    @modalHandle="modalHandle" @clickHandle="clickHandle" @detail="detail"/>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import {query,add,update,del} from '@/api/printTemplate'
// import byMonacoEditor  from '@/benyun/components/byMonacoEditor/byMonacoEditor.vue'
import {preview} from '@/api/print'
import EditInput from "./components/editInput.vue";

@Component({components:{}})
export default class PrintTemplate extends Vue {
  load=false;
  isSearch=false
  timeNum = 0;
  config:any={
    attr:{
      calculateH:true
    },
    search:{
      attr:{
        size:'small'
      },
      columns:[
        [{
          span:8,
          label:'模板名称',
          prop:'templateName',
          component:'by-input',
          compConfig:{
            attr:{
              clearable:true
            }
          }
        },{
          span:8,
          label:'模板引擎',
          prop:'templateEngine',
          component:'by-select',
          compConfig:{
            attr:{
              clearable:true,
              data:[{
                label:'freemarker',
                value:'freemarker'
              },{
                label:'thymeleaf',
                value:'thymeleaf'
              }]
            }
          }
        }]
      ]
    },
    tool:{
      tools:{
        search:true,
        refresh:true,
        add:true,
        delete:true
      }
    },
    table:{
      attr:{
        size:'mini',
        seq:true,
        checkbox:true
      },
      columns:[{
        title:'模板名称',
        isDetail:true,
        field:'templateName'
      },{
        title:'模板引擎',
        field:'templateEngine',
        width:130,
      },{
        title:'打印次数限制',
        field:'printLimit',
        width:130
      },{
        title:'创建时间',
        field:'createTime',
        width:140
      },{
        title:'操作',
        action:true,
        width:100,
        plugins:[{
          name:'删除',
          event:{
            click:(item:any) => {
              this.singleDel(item);
            }
          }
        }]
      }]
    },
    modal:{
      tool:{
        tools:{
          return:true,
          add:true
        },
        customTools:[{
          name: '预览', 
          icon: 'el-icon-view', 
          event:{
            click:() => {
              this.preView()
            }
          }
        }]
      },
      form:{
        attr:{
          size:'small',
          width:'1200px',
          rules:{
            templateName:[
              { required: true, message: '模版名称不能为空！', trigger: 'blur' }
            ],
            templateEngine:[
              { required: true, message: '请选择模板引擎！', trigger: 'change' }
            ],
            templateHtml:[
              { required: true, message: '模板内容不能为空！', trigger: 'change' }
            ],
            dataExample:[
              {validator: (rule:any, value:any, callback:Function) => {
                try {
                  if (value && typeof (JSON.parse(value)) === 'number') {
                    callback(new Error('输入项非JSON，请检查！'))
                  }else{
                    callback()
                  }
                } catch (e) {
                  callback(new Error('输入项非JSON，请检查！'))
                }
              }, trigger: 'blur' }
            ],
            printLimit:[
              {required: true, message: '打印次数限制不能为空！', trigger: 'blur'}
            ]
          }
        },
        columns:[
          [{
            label:'模版名称',
            prop:'templateName',
            component:'by-input',
            compConfig:{
              attr:{
                clearable:true
              }
            }
          }],
          [{
            label:'模板引擎',
            prop:'templateEngine',
            component:'by-select',
            compConfig:{
              attr:{
                clearable:true,
                data:[{
                  label:'freemarker',
                  value:'freemarker'
                },{
                  label:'thymeleaf',
                  value:'thymeleaf'
                }]
              }
            }
          },{
            label:'打印次数限制',
            labelWidth:'120px',
            prop:'printLimit',
            component:'by-input',
            compConfig:{
              attr:{
                clearable:true,
                type:'integer'
              }
            }
          }],
          [{
            label:'模板内容',
            prop:'templateHtml',
            component:EditInput,
          }],
          [{
            label:'示例数据',
            prop:'dataExample',
            component:'by-input',
            compConfig:{
              attr:{
                defaultValue:'{}',
                type:'textarea',
                rows:8
              }
            }
          }]
        ]
      }
    }
  }
  mounted(){
    // this.$nextTick(()=>{
      this.getList()
    // })
  }
  //预览
  preView(){
    let data = (this.$refs.view as any).getFormValue();
    if(!data.templateEngine){
      this.$message('模版引擎不能为空！')
      return
    }
    if(!data.templateHtml){
      this.$message('模版内容不能为空！')
      return
    }
    if(!data.dataExample){
      this.$message('示例数据不能为空！')
      return
    }
    this.load=true;
    const that:any = this;
    preview({
      templateEngine:data.templateEngine,
      templateHtml:data.templateHtml,
      templateData:data.dataExample,
      outType:'PDF'
    }).then((res:any) => {
      this.load=false;
      if(res.type === 'application/json'){
        const reader:any = new FileReader();
        reader.onload = function (){
          const d:any = JSON.parse(reader.result);
          if(d && d.msg){
            that.$message({
              message:d.msg,
              type:'error'
            })
          }
        }
        reader.readAsText(res);
        return
      }
      const blob = new Blob([res],{
        type: "application/pdf;chartset=UTF-8"
      })
      const qrUrl:any =(window as any).URL.createObjectURL(blob);
      (window as any).open(qrUrl);

      // const myWindow =(window as any).open(qrUrl);
      // myWindow.print();

    }).catch((err:any)=>{
      this.load=false;
    })
  }

  //单个删除
  singleDel(item:any){
    let data=[item.id];
    this.$confirm('此操作将永久删除“'+item.templateName+'”, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.del(data);
    }).catch(() => {});
  }
  //多个删除
  multipleDel(){
    let data = (this.$refs.view as any).getSelectData();
    if(data.length == 0){
      this.$message('请选择需要删除的数据！')
      return
    }
    let ids:Array<any>=[];
    let names='';
    for(const item of data){
      ids.push(item.id);
      if(names){
        names = names + ',' + item.templateName
      }else{
        names = item.templateName;
      }
    }
    this.$confirm('此操作将永久删除“'+names+'”, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.del(ids);
    }).catch(() => {});
  }
  //删除
  del(data:Array<any>){
    this.load = true;
    del({ids:data}).then(()=>{
      this.load = false;
      this.$message({
        message:'删除成功！',
        type:'success'
      })
      this.pagination();
    }).catch(()=>{
      this.load = false;
    })
  }
  //分页
  pagination(){
    if(this.isSearch){
      this.queryList();
    }else{
      this.getList()
    }
  }
  //列表请求（只有分页，不包含搜素条件）
  getList(){
    if(!this.$refs.view){
      if(this.timeNum > 5){
        return
      }
      setTimeout(()=>{
        this.getList()
      },500) 
      this.timeNum ++;
      return
    }
    this.isSearch = false;
    let data = (this.$refs.view as any).getPage();
    delete data.total;
    this.requestList(data);
  }
  //列表请求（包含分页和搜素条件）
  queryList(){
    this.isSearch = true;
    let data = (this.$refs.view as any).getQuery();
    delete data.total;
    this.requestList(data);
  }
  requestList(data:any){
    this.load = true;
    query(data).then((res:any) => {
      this.load = false;
      (this.$refs.view as any).setTableValue(res.data.records);
      let page = {
        pageNo: res.data.current, //当前页
        pageSize: res.data.size, //每页条数
        total: res.data.total //总条数
      };
      (this.$refs.view as any).setPage(page)

    }).catch(()=>{
      this.load = false;
    })
  }
  modalHandle(n:string){
    if(n == 'onAdd'){
      (this.$refs.view as any).getFormValidate(this.onAdd)
    }

    if(n == 'onSave'){
      (this.$refs.view as any).getFormValidate(this.onSave)
    }
  }
  //新增
  onAdd(){
    let value = (this.$refs.view as any).getFormValue();
    if(value){
      this.load = true;
      add(value).then((res:any)=>{
        this.load = false;
        this.$message({
          message:res.msg,
          type:'success'
        });
        (this.$refs.view as any).closeModal();
        this.getList();
      }).catch(()=>{
        this.load = false;
      })
    }
  }
  //保存
  onSave(){
    let data = (this.$refs.view as any).getFormValue();
    this.load = true;
    update(data).then((res:any) => {
      this.$message({
        message:res.msg,
        type:'success'
      });
      this.load = false;
      (this.$refs.view as any).closeModal();
      this.pagination();
    }).catch(()=>{
      this.load = false;
    })
  }
  clickHandle(n:string){
    if(n == 'onAdd'){
      this.config.modal.tool.tools.add = true;
      delete this.config.modal.tool.tools.save;
      (this.$refs.view as any).initFormTool();
    }
    if(n == 'onDelete'){
      this.multipleDel()
    }
  }
  //点击详情
  detail(){
    this.config.modal.tool.tools.save = true;
    delete this.config.modal.tool.tools.add;
    (this.$refs.view as any).initFormTool();
  }
}
</script>
<style lang="scss" scoped>
.print-template{
  height: 100%;
  width: 100%;
  overflow-y: hidden;
}
</style>