<template>
  <div>
    <el-card class="el-card">
      <el-form
        :inline="true"
        :model="query"
        class="query-form"
        size="mini"
      >
        <el-row>
          <el-form-item class="query-form-item" label="模板名称:">
            <el-input v-model="query.name" placeholder="模板名称" style="width: 100%" clearable></el-input>
          </el-form-item>
          <el-form-item class="query-form-item" label="模板类型:">
            <el-select v-model="query.module" placeholder="模板类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="标签" value="0"></el-option>
              <el-option label="报表" value="1"></el-option>
              <el-option label="业务单据" value="2"></el-option>
              <el-option label="扫码单据" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
              <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
              <el-button type="primary" icon="el-icon-plus" @click="handleAddForm()">新增模板</el-button>
            </el-button-group>
          </el-form-item>
        </el-row>
      </el-form>
      <el-table :data="list" style="width: 100%" border>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="模板名称" prop="name"></el-table-column>
        <el-table-column label="模板类型">
          <template slot-scope="scope">
            {{ moduleNameMap[scope.row.module] }}
          </template>
        </el-table-column>
<!--        <el-table-column label="更新时间" prop="update_time"></el-table-column>-->

        <!--                <el-table-column label="表格行数" prop="rowCount" width="100"></el-table-column>-->
        <!--                <el-table-column label="二维码数量" prop="qrcodeCount" width="125"></el-table-column>-->
        <el-table-column label="备注" prop="remark"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click.native="handleForm(scope.$index, scope.row)"
            >编辑
            </el-button
            >
            <el-button
              type="text"
              @click.native="deleteTemplate(scope.row)"
            >删除
            </el-button
            >
            <el-button
              type="text"
              @click="jumpDl(scope.row)"
            >模板下载
            </el-button
            >
            <el-button
              type="text"
              @click="previewPdf(scope.row)"
            >预览
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="query.page"
        :limit.sync="query.limit"
        @pagination="getList"
      />
    </el-card>


    <!--表单-->
    <el-dialog
      v-if="formVisible"
      :title="formMap[formName]"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="45%"
      top="5vh"
    >
      <el-form :model="formData" :rules="formRules" ref="dataForm">
        <el-row :gutter="20" class="el-row" type="flex">
          <el-col :span="22" class="el-col" type="flex">
            <el-form-item prop="name" label="模板名称:" label-width="100px">
              <el-input v-model="formData.name" auto-complete="off" :disabled="false"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="el-row" type="flex">
          <el-col :span="22" class="el-col" type="flex">
            <el-form-item prop="module" label="模板类型:" label-width="100px">
              <el-select v-model="formData.module" @change="isCleck"  placeholder="模板类型" style="width: 100%" >
                <el-option label="标签" value="0" ></el-option>
                <el-option label="报表" value="1"></el-option>
                <el-option label="业务单据" value="2"></el-option>
                <el-option label="扫码单据" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

<!--        <el-row :gutter="20" class="el-row" type="flex" v-show="formData.module==2">-->
<!--          <el-col :span="22" class="el-col" type="flex">-->
<!--            <el-form-item prop="bussinessType" label="单据类型:" label-width="100px">-->
<!--              <el-radio-group v-model="formData.bussinessType">-->
<!--                <el-radio :label=1>业务单</el-radio>-->
<!--                <el-radio :label=2>出入库单</el-radio>-->
<!--              </el-radio-group>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->

<!--        <el-row :gutter="20" class="el-row" type="flex" v-show="formData.module==2">-->
<!--          <el-col :span="22" class="el-col" type="flex">-->
<!--            <el-form-item prop="bussinessStatus" label="单据状态:" label-width="100px">-->
<!--              <el-checkbox-group v-model="formData.bussinessStatusList">-->
<!--                <el-checkbox label=3>待校验</el-checkbox>-->
<!--                <el-checkbox label=5>待核对</el-checkbox>-->
<!--                <el-checkbox label=10>待审核</el-checkbox>-->
<!--                <el-checkbox label=7>已审核</el-checkbox>-->
<!--              </el-checkbox-group>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->


        <el-row :gutter="20">
          <el-col :span="22">
            <el-form-item label="jasper模板:" label-width="100px" prop="jasper">
              <el-upload
                class="upload-demo"
                style="width: 100%"
                ref="uploadJasper"
                :action="this.uploadUrl"
                :limit="1"
                :headers="headers"
                :on-exceed="uploadHandleExceed"
                accept=".jasper"
                :on-change="uploadOnchange"
                :on-success="uploadHandleSuccess"
                :auto-upload="true"
                :file-list="fileList"

              >
                <el-button slot="trigger" size="small" type="primary" :disabled="uploadDisabled">选取文件
                </el-button>
                <!--                               <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
                <div slot="tip" class="el-upload__tip" v-if="formData.path==''">只能上传 jasper 文件，且不超过 10
                  MB
                </div>
                <div slot="tip" class="el-upload__tip">{{ formData.path }}</div>

              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="22">
            <el-form-item label="jrxml模板:" prop="jrxml" label-width="100px">
              <el-upload
                class="upload-demo"
                ref="uploadJrxml"
                :action="this.uploadJrxmlUrl"
                :headers="headers"
                :limit="1"
                :on-exceed="uploadJrxmlHandleExceed"
                accept=".jrxml"
                :on-change="uploadJrxmlOnchange"
                :on-success="uploadJrxmlHandleSuccess"
                :file-list="jrxmlFileList"
                :auto-upload="true">
                <el-button slot="trigger" size="small" type="primary" :disabled="uploadDisabled">选取文件
                </el-button>
                <div slot="tip" class="el-upload__tip" v-if="formData.jrxmlPath==null">只能上传 jrxml
                  文件，且不超过 10 MB
                </div>
                <div slot="tip" class="el-upload__tip">{{ formData.jrxmlPath }}</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="22" class="el-col" type="flex">
            <el-form-item label="备注:" label-width="100px">
              <el-input type="textarea" v-model="formData.remark" rows=3></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="hideForm">取消</el-button>
        <el-button
          type="primary"
          @click.native="submitUpload()"
          :loading="formLoading"
        >提交
        </el-button
        >
      </div>
      <div style="margin-top: 18px ;  color: #F71616;">
        <span>提示：模板字体支持宋体，华文宋体，微软雅黑&nbsp;</span>
      </div>
    </el-dialog>

    <!--    模块选择模板    -->
    <el-dialog
      title="选择模板"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="moduleFormVisible"
      v-if="moduleFormVisible"
      :before-close="moduleHideForm"
      width="45%"
      top="5vh"
    >
      <el-form ref="singleTable">
        <el-table v-loading="selectTemplateLoading" :data="selectTemplateList" style="width: 100%"
                  highlight-current-row
                  @current-change="moduleSelectHandleCurrentChange">
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column label="模板名称" prop="name" width="200"></el-table-column>
          <el-table-column label="备注" prop="remark"></el-table-column>
        </el-table>

        <el-pagination
          :page-size="selectTemplateQuery.limit"
          @current-change="moduleHandleCurrentChange"
          layout="prev, pager, next"
          :total="selectTemplateTotal"
        >
        </el-pagination>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="moduleHideForm">取消</el-button>
        <el-button
          type="primary"
          @click.native="moduleSubmitSelectTemplate()"
          :loading="moduleFormLoading"
        >确定
        </el-button
        >
      </div>
    </el-dialog>


    <el-dialog
      title="字段说明"
      :visible.sync="centerDialogVisible"
      width="80%"
      center>
      <span style="white-space: pre-wrap;">{{ currentRow }}</span>
      <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  systemPDFTemplateList,
  systemPDFTemplateSave,
  systemPDFTemplateDeleteById,
  systemPDFModuleList,
  systemPDFModuleSave,
  getSystemPDFModules
} from "@/api/system/systemPDFTemplate";
import store from "@/store";
import {saveAs} from 'file-saver';
import {demoPrint} from "@/api/system/itextpdf";

const formJson = {
  id: "",
  name: "",
  type: "2",
  module: null,
  param: "",
  path: "",
  jrxmlPath: null,
  rowCount: 10,
  qrcodeCount: 1,
  remark: "",
  bussinessType:null,
  bussinessStatusList:[],
};
const moduleFormJson = {
  id: "",
  templateId: 0,
};
export default {
  data() {
    return {
      BASE_URL: process.env.VUE_APP_BASE_API,
      query: {
        name: "",
        module: null,
        page: 1,
        limit: 10
      },
      headers: {},
      list: [],
      total: 0,
      moduleQuery: {
        name: "",
        page: 1,
        limit: 20
      },
      currentRow: null,
      moduleList: [],
      moduleNameList: [],
      moduleTotal: 0,
      selectTemplateQuery: {
        name: "",
        module: null,
        page: 1,
        limit: 20
      },
      centerDialogVisible: false,
      selectTemplateList: [],
      selectTemplateTotal: 0,
      selectTemplateLoading: false,
      moduleSelectQuery: {
        name: "",
        page: 1,
        limit: 20
      },
      moduleSelectList: [],
      moduleSelectTotal: 0,
      loading: true,
      index: null,
      formName: null,
      moduleFormName: null,
      formMap: {
        add: "模板管理-新增",
        update: "模板管理-编辑"
      },
      formLoading: false,
      formVisible: false,
      moduleFormLoading: false,
      moduleFormVisible: false,
      formData: formJson,
      moduleFormData: moduleFormJson,
      formRules: {
        name: [
          {required: true, message: "请输入模板名称", trigger: "blur"}
        ],
        module: [
          {required: true, message: "请选择模板类型", trigger: "blur"}
        ],
        // jasper: [
        //   {required: true, message: "请上传jasper文件", trigger: "blur"}
        // ],
        // jrxml: [
        //   {required: true, message: "请上传jrxml文件", trigger: "blur"}
        // ]

      },
      deleteLoading: false,
      uploadUrl: "",
      uploadJrxmlUrl: "",
      fileList: [],
      jrxmlFileList: [],
      uploadDisabled: false,
      moduleLoading: false,
      moduleNameMap: {0: "标签", 1: "报表", 2: "业务单据",3: "扫码单据"},
    };
  },
  methods: {
    onReset() {
      this.$router.push({
        path: ""
      });
      this.query = {
        name: "",
        module: null,
        page: 1,
        limit: 10
      };
      this.getList();
    },
    isCleck(){
      if(this.formData.module!="2"){
        this.formData.bussinessStatusList=[];
        this.formData.bussinessType=null;
      }
    },
    onSubmit() {
      this.query.page = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.query.page = val;
      this.getList();
    },
    moduleHandleCurrentChange(val) {
      this.moduleQuery.page = val;
      this.getModuleList();
    },
    getList() {
      this.loading = true;
      systemPDFTemplateList(this.query)
        .then(response => {
          this.loading = false;
          this.list = response.data.list || [];
          this.total = response.data.total || 0;
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },

    moduleClick(row) {
      this.query = {
        module: row.id,
        page: 1,
        limit: 20
      };
      this.getList();
    },
    jumpDl(row) {
      this.handleDownload(this.BASE_URL + "/udiwms/donwload/file?fileName=" + row.jrxmlPath, row.name + ".jrxml");
    },


    previewPdf(row) {
      let query = {id: row.id};
      demoPrint(query).then((response) => {
        //将pdf文件转换为url。
        const binaryData = [];
        binaryData.push(response);
        //获取blob链接。
        let url = window.URL.createObjectURL(
          new Blob(binaryData, {type: "application/pdf"})
        );
        this.loading = false;
        window.open(url);//打开新标签页，预览pdf。
      }).catch(() => {
        this.loading = false;
      });
    },

    handleDownload(url, name) {
      this.getBlob(url).then(blob => {
        saveAs(blob, name);
      })
      return false;
    },
    getBlob(url) {
      return new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };
        xhr.send();
      })
    },

    getModuleList() {
      this.moduleLoading = true;
      systemPDFModuleList(this.moduleQuery)
        .then(response => {
          this.moduleLoading = false;
          this.moduleList = response.data.list || [];
          this.moduleTotal = response.data.total || 0;
        })
        .catch(() => {
          this.moduleLoading = false;
          this.moduleList = [];
          this.moduleTotal = 0;
        });
    },
    // 刷新表单
    resetForm() {
      // if (this.$refs["dataForm"]) {
      //     // 清空验证信息表单
      //     this.$refs["dataForm"].clearValidate();
      //     // 刷新表单
      //     this.$refs["dataForm"].resetFields();
      //     this.fileList = null;
      //     this.jrxmlFileList = null;
      //     this.getList();
      // }
      // 清空验证信息表单
      this.$refs["dataForm"].clearValidate();
      // 刷新表单
      this.$refs["dataForm"].resetFields();
      this.fileList = null;
      this.jrxmlFileList = null;
      this.getList();
    },
    // 隐藏表单
    hideForm() {
      // 更改值
      this.formVisible = !this.formVisible;
      return true;
    },
    moduleHideForm() {
      this.moduleFormVisible = !this.moduleFormVisible;
      this.selectTemplateQuery.module = null;
      return true;
    },
    moduleSelectTemplate(row) {
      this.moduleFormData = {
        id: row.id,
        templateId: row.templateId,
      };
      this.moduleFormVisible = true;
      this.selectTemplateQuery = {
        name: "",
        module: row.id,
        page: 1,
        limit: 20
      };
      this.selectTemplateGetList();
    },
    selectTemplateGetList() {
      console.log(this.selectTemplateQuery)
      this.selectTemplateLoading = true;
      systemPDFTemplateList(this.selectTemplateQuery)
        .then(response => {
          this.selectTemplateLoading = false;
          this.selectTemplateList = response.data.list || [];
          this.selectTemplateTotal = response.data.total || 0;
        })
        .catch(() => {
          this.selectTemplateLoading = false;
          this.selectTemplateList = [];
          this.selectTemplateTotal = 0;
        });
    },
    previewTemplate(row) {
      console.log(row)
    },
    showFieldExpain(row) {

      this.currentRow = row.fieldExplain.replace('\\\n', '<br>');
      this.centerDialogVisible = true;
      // const {href} = this.$router.resolve({//打开新窗口页面
      //     path: '/showText',
      //     query: {
      //         content: row.fieldExplain
      //     }
      // })
      // window.open(href, '_blank')
    },
    // 显示表单
    handleForm(index, row) {
      this.formVisible = true;
      this.formData = JSON.parse(JSON.stringify(formJson));
      this.fileList = [];
      this.jrxmlFileList = [];

      if (row !== null) {
        this.formData = Object.assign({}, row);
        this.formData.module = row.module + "";
      }
      this.index = index;
      this.formName = "update";
      this.uploadDisabled = true;
      // this.fileList.push(this.formData.path);
      // this.jrxmlFileList.push(this.formData.jrxmlPath)
    },


    handleAddForm(row) {
      this.formVisible = true;
      this.formData = JSON.parse(JSON.stringify(formJson));
      // this.fileList = [];
      this.formName = "add";
      this.uploadDisabled = false;
    },
    templateConfig(row) {

    },
    submitUpload() {
      if (this.$refs.uploadJasper.uploadFiles.length < 1 && !this.uploadDisabled) {
        this.$message.warning(`请选择jasper文件`);
        return
      }
      if (this.$refs.uploadJrxml.uploadFiles.length < 1 && !this.uploadDisabled) {
        this.$message.warning(`请选择jrxml文件`);
        return
      }
      console.log(this.formName)
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.submitTemplate();
        }
      });
    },
    uploadHandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    uploadOnchange(file, fileList) {
      let fileName = file.name;
      let uid = file.uid
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (lastName.toLowerCase() !== ".jasper") {
        this.$message.error("上传文件只能是 jasper 格式");
        for (let i = 0; i < fileList.length; i++) {//从list删除
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
        return;
      }
      // 限制上传文件的大小
      const isLt = file.size / 1024 / 1024 / 30 <= 1;
      if (!isLt) {
        this.$message.error("上传文件大小不能超过 30MB");
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
      }
      return isLt;
    },
    uploadHandleSuccess(response, file, fileList) {
      console.log(response)
      if (response.code === 20000) {
        this.formData.path = response.data.path;
        // this.submitTemplate();
      } else {
        this.$message.error("上传失败：" + response.message);
      }
    },

    uploadJrxmlHandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    uploadJrxmlOnchange(file, fileList) {
      let fileName = file.name;
      let uid = file.uid
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (lastName.toLowerCase() !== ".jrxml") {
        this.$message.error("上传文件只能是 jrxml 格式");
        for (let i = 0; i < fileList.length; i++) {//从list删除
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
        return;
      }
      // 限制上传文件的大小
      const isLt = file.size / 1024 / 1024 / 30 <= 1;
      if (!isLt) {
        this.$message.error("上传文件大小不能超过 30MB");
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
      }
      return isLt;
    },
    uploadJrxmlHandleSuccess(response, file, fileList) {
      console.log(response)
      if (response.code === 20000) {
        this.formData.jrxmlPath = response.data.path;
        // this.submitTemplate();
      } else {
        this.$message.error("上传失败：" + response.message);
      }
    },


    submitTemplate() {
      console.log(this.formData)
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.formLoading = true;
          let data = Object.assign({}, this.formData);
          data.name = data.name.trim();
          systemPDFTemplateSave(data, this.formName)
            .then(response => {
              this.formLoading = false;
              if (response.code !== 20000) {
                this.$message.error(response.message);
                return false;
              }
              this.$message.success("操作成功");
              this.formVisible = false;
              this.getList();
            })
            .catch(() => {
              this.formLoading = false;
            });
        }
      });
    },
    deleteTemplate(row) {
      this.$confirm("此操作将永久删除该模板, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let query =
          {
            id: row.id,
            path: row.path
          };
        systemPDFTemplateDeleteById(query)
          .then(response => {
            console.log(response)
            if (response.code === 20000) {
              this.$message.success(response.data);
              // 刷新表单
              // this.resetForm();
              this.getList();
            } else {
              this.$message.error(response.message);
            }
          })
          .catch(() => {

          })
      }).catch(() => {

      });
    },
    moduleSelectSetCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row);
    },
    moduleSelectHandleCurrentChange(val) {
      this.moduleFormData.templateId = val.id;
      console.log(val)
      console.log(this.moduleFormData)
    },
    moduleSubmitSelectTemplate() {

      this.moduleFormLoading = true;
      let data = Object.assign({}, this.moduleFormData);
      this.moduleFormName = 'update';
      systemPDFModuleSave(data, this.moduleFormName)
        .then(response => {
          this.moduleFormLoading = false;
          if (response.code !== 20000) {
            this.$message.error(response.message);
            return false;
          }
          this.$message.success("操作成功");
          this.moduleFormVisible = false;
          if (this.moduleFormName === "add") {
            // 向头部添加数据
            if (response.data && response.data.id) {
              data.id = response.data.id;
              this.moduleList.unshift(data);
            }
          } else {
            this.moduleList.splice(this.index, 1, data);
          }
          this.getModuleList();
        })
        .catch(() => {
          this.moduleFormLoading = false;
        });
    },
    getPDFModuleNameList() {
      getSystemPDFModules()
        .then((response) => {
          this.moduleNameList = response.data.list;
          // this.moduleNameMap = {};
          // this.moduleNameList.forEach((obj, index) => {
          //     console.log(obj)
          //     this.moduleNameMap[obj.id] = obj.name;
          // });
          console.log(this.moduleNameMap)
        })
        .catch(() => {
        });
    },
  },
  filters: {
    paramStatusFilterType(paramStatus) {
      const paramStatusTypeMap = {
        0: "gray",
        1: "success"
      };
      return paramStatusTypeMap[paramStatus];
    },
    paramStatusFilterName(paramStatus) {
      const paramStatusNameMap = {
        1: "订单详情",
        2: "配货管理-打印订单"
      };
      return paramStatusNameMap[paramStatus];
    }
  },
  mounted() {
  },
  created() {
    this.getList();
    this.getPDFModuleNameList();
    this.getModuleList();
    this.uploadUrl = this.BASE_URL + "/udiwms/upload/pdf/template/jasper";
    this.uploadJrxmlUrl = this.BASE_URL + "/udiwms/upload/pdf/template/jrxml";
    this.headers = {
      ADMINID: this.$store.getters.adminId,
      ADMINTOKEN: this.$store.getters.token,
    };
  }
};
</script>

<style type="text/scss" lang="scss">
</style>
