<template>
    <div>

        <el-card class="el-card">

            <el-form
                :inline="true"
                :model="moduleQuery"
                class="query-form"
                size="mini"
            >
                <el-row>
                    <el-form-item class="query-form-item">
                        <el-input v-model="moduleQuery.name" placeholder="功能名称"></el-input>
                    </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="search" @click="onSubmit">查询</el-button>
                        </el-button-group>
                    </el-form-item>
                </el-row>
            </el-form>

            <el-table v-loading="moduleLoading" :data="moduleList" style="width: 100%"
                      @row-click="moduleClick" highlight-current-row
            >
                <el-table-column type="index" label="序号" width="50"></el-table-column>
                <el-table-column label="模板类型" width="150" prop="templateType">
                    <template slot-scope="scope">
                        {{ moduleTypeMap[scope.row.templateType] }}
                    </template>
                </el-table-column>
                <el-table-column label="功能名称" prop="name" width="250"></el-table-column>
                <el-table-column label="模板名称" width="250">
                    <template slot-scope="scope">
                        <p v-if="scope.row.templateName === null">
                            <el-button
                                type="primary"
                                size="mini"
                                :disabled="scope.row.templateType == 2"
                                @click.native.stop="moduleSelectTemplate(scope.row)"
                            >选择模板
                            </el-button
                            >
                        </p>
                        <p v-if="scope.row.templateName !== null">
                            <el-button
                                type="primary"
                                :disabled="scope.row.templateType == 2"
                                size="mini"
                                @click.native.stop="moduleSelectTemplate(scope.row)"
                            >{{ scope.row.templateName }}
                            </el-button
                            >
                        </p>
                    </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark"></el-table-column>
                <el-table-column label="操作" fixed="right" width="250">
                    <template slot-scope="scope">
                        <!--                        <el-button-->
                        <!--                            type="text"-->
                        <!--                            size="small"-->
                        <!--                            :disabled="scope.row.templateName === undefined || scope.row.templateName === null || scope.row.templateName === ''"-->
                        <!--                            @click.native="handleForm(scope.$index, scope.row)"-->
                        <!--                        >预览-->
                        <!--                        </el-button-->
                        <!--                        >-->
                        <el-button
                            type="text"
                            size="small"
                            @click.native="showFieldExpain(scope.row)"
                        >字段说明
                        </el-button
                        >
                        <el-button
                            type="text"
                            size="small"
                            @click="jumpDl(scope.row)"
                        >初始模板下载
                        </el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                :page-size="moduleQuery.limit"
                @current-change="moduleHandleCurrentChange"
                layout="prev, pager, next"
                :total="moduleTotal"
            >
            </el-pagination>
        </el-card>

        <el-card class="el-card">
            <el-table v-loading="loading" :data="list" style="width: 100%">
                <el-table-column label="序号" type="index" show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="业务类型" prop="localActionName" show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="模板名称" width="200">
                    <template slot-scope="scope">
                        <p v-if="scope.row.templateName === null">
                            <el-button
                                type="primary"
                                size="mini"
                                @click.native.stop="busSelectTemplate(scope.row)"
                            >选择模板
                            </el-button
                            >
                        </p>
                        <p v-if="scope.row.templateName !== null">
                            <el-button
                                type="primary"
                                size="mini"
                                @click.native.stop="busSelectTemplate(scope.row)"
                            >{{ scope.row.templateName }}
                            </el-button
                            >
                        </p>
                    </template>
                </el-table-column>
                <el-table-column label="打印方式" prop="remark1" show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.printType" placeholder="打印方式">
                            <el-option label="批次号" :value=0></el-option>
                            <el-option label="条码清单" :value=1></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="备注字段1" prop="remark1" show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-input :disabled="scope.$index !== currentCheckIndex" v-model="scope.row.remark1"
                                  placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="备注字段2" prop="remark1" show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-input :disabled="scope.$index !== currentCheckIndex" v-model="scope.row.remark2"
                                  placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="备注字段3" prop="remark1" show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-input :disabled="scope.$index !== currentCheckIndex" v-model="scope.row.remark3"
                                  placeholder="请输入"></el-input>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="150" prop="price" fixed="right">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="small"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑
                        </el-button>
                        <el-button
                            type="text"
                            size="small"
                            @click="handleSave(scope.$index, scope.row)"
                        >保存
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog
                title="接口参数设置"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :visible.sync="modifyDetailDialogVisible"
                width="70%"
                v-if="modifyDetailDialogVisible"
            >
                <modifyDetailDialog :inputDetailQuery="inputDetailQuery"></modifyDetailDialog>
                <div style="text-align: center">
                    <el-button type="primary" size="small" icon="search" @click="onDetailModifySubmit"
                    >提交
                    </el-button
                    >
                    <el-button type="primary" size="small" icon="search" @click="cancelDialog"
                    >取消
                    </el-button
                    >
                </div>
            </el-dialog>
            <el-pagination
                :page-size="moduleQuery.limit"
                @current-change="handlePageChange"
                layout="prev, pager, next"
                :total="total"
            ></el-pagination>


            <div style="margin-top: 18px ;  color: #F71616;">
                <span>重要提示：本页功能仅供技术提供方修改&nbsp;</span>
            </div>
        </el-card>
        <!--表单-->
        <el-dialog
            :title="formMap[formName]"
            :visible.sync="formVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :before-close="hideForm"
            width="85%"
            top="5vh"
        >
            <el-form :model="formData" :rules="formRules" ref="dataForm">

                <el-form-item label="模板名称" prop="name">
                    <el-input v-model="formData.name" auto-complete="off" :disabled="false"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="formData.remark" rows=6></el-input>
                </el-form-item>

                <el-row :gutter="20">
                    <el-col :span="4">
                        <div class="ao-text">
                            <span>选择jasper模板：</span>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="">
                            <el-upload
                                class="upload-demo"
                                ref="upload"
                                :action="this.uploadUrl"
                                :on-preview="uploadHandlePreview"
                                :on-remove="uploadHandleRemove"
                                :limit="1"
                                :headers="headers"
                                :on-exceed="uploadHandleExceed"
                                accept=".jasper"
                                :on-change="uploadOnchange"
                                :on-success="uploadHandleSuccess"
                                :on-error="uploadHandleError"
                                :file-list="fileList"
                                :auto-upload="false">
                                <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">只能上传 jasper 文件，且不超过 2 MB</div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <div class="ao-text">
                            <span>所属模块：</span>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item prop="module">
                            <el-select v-model="formData.module" placeholder="所属模块">
                                <el-option
                                    v-for="item in moduleNameList"
                                    :key="item.idStr"
                                    :label="item.name"
                                    :value="item.idStr"
                                ></el-option>
                            </el-select>
                        </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>
        </el-dialog>

        <!--    模块选择模板    -->
        <el-dialog
            title="选择模板"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :visible.sync="moduleFormVisible"
            :before-close="moduleHideForm"
            width="70%"
            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="40%"
            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, updateDetailRel,
    getSystemPDFModules, moduleDetail, updatePdfRelData
} from "../../../api/param/systemPDFTemplate";
import {saveAs} from 'file-saver';
import {BASE_URL, SERVER_IP} from "../../../config/app";

const formJson = {
    id: "",
    name: "",
    type: "2",
    module: "1",
    param: "",
    path: "",
    rowCount: 10,
    qrcodeCount: 1,
    remark: "",
};
const moduleFormJson = {
    id: "",
    templateId: 0,
};
export default {
    data() {
        return {
            query: {
                templateType: null,
                moduleId: null,
                name: "",
                page: 1,
                limit: 20
            },
            headers: {},
            list: [],
            total: 0,
            moduleQuery: {
                name: "",
                page: 1,
                limit: 20
            },
            currentRow: null,
            moduleList: [],
            moduleNameList: [],
            moduleTotal: 0,
            selectTemplateQuery: {
                busRlId: null,
                name: "",
                module: null,
                page: 1,
                limit: 20
            },
            centerDialogVisible: false,
            selectTemplateList: [],
            selectTemplateTotal: 0,
            selectTemplateLoading: false,
            moduleSelectQuery: {
                name: "",
                page: 1,
                limit: 20
            },
            moduleSelectList: [],
            moduleSelectTotal: 0,
            loading: false,
            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"}
                ]
            },
            currentCheckIndex: -1,
            deleteLoading: false,
            uploadUrl: "",
            fileList: [],
            uploadDisabled: false,
            moduleLoading: false,
            moduleTypeMap: {0: "标签", 1: "报表", 2: "单据"},
        };
    },
    methods: {
        onReset() {
            this.$router.push({
                path: ""
            });
            this.moduleQuery = {
                templateType: null,
                moduleId: null,
                name: "",
                page: 1,
                limit: 20
            };
            this.getModuleList();
        },
        onSubmit() {
            this.getModuleList();
        },
        handleCurrentChange(val) {
            this.query.page = val;
            this.getList();
        },
        moduleHandleCurrentChange(val) {
            this.moduleQuery.page = val;
            this.getModuleList();
        },
        getList() {
            // this.loading = true;
            moduleDetail(this.query)
                .then(response => {
                    this.loading = false;
                    this.list = response.data || [];
                })
                .catch(() => {
                    this.loading = false;
                    this.list = [];
                });
        },

        moduleClick(row) {
            this.query = {
                templateType: row.templateType,
                moduleId: row.id,
                page: 1,
                limit: 20
            };
            this.getList();
        },

        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();
            })
        },

        jumpDl(row) {
            console.log(BASE_URL);
            console.log(row.templateDlUrl + "----" + SERVER_IP);
            this.handleDownload(BASE_URL + "/udiwms/donwload/file?fileName=" + row.templateDlUrl, row.name + ".jrxml");
        },
        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.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 = {
                module: row.templateType,
                name: "",
                page: 1,
                limit: 20
            };
            this.selectTemplateGetList();
        },

        busSelectTemplate(row) {
            this.moduleFormData = {
                id: row.id,
                templateId: row.templateId,
            };
            this.moduleFormVisible = true;
            this.selectTemplateQuery = {
                module: row.templateType,
                busRlId: row.id,
                type: 1,
                name: "",
                page: 1,
                limit: 20
            };
            console.log("this.selectTemplateQuery.busRlId =" + this.selectTemplateQuery.busRlId);

            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 = [];
            if (row !== null) {
                this.formData = Object.assign({}, row);
                this.formData.module = row.module + "";
            }
            this.index = index;
            this.formName = "update";
            this.uploadDisabled = true;
        },


        handleAddForm(row) {
            this.formVisible = true;
            this.formData = {module: row.id + ""};
            this.fileList = [];
            this.formName = "add";
            this.uploadDisabled = false;
        },
        templateConfig(row) {

        },
        submitUpload() {
            if (this.$refs.upload.uploadFiles.length < 1 && !this.uploadDisabled) {
                this.$message.warning(`请选择jasper文件`);
            }
            console.log(this.formName)
            this.$refs["dataForm"].validate(valid => {
                if (valid) {
                    if (!this.uploadDisabled) {
                        this.$refs.upload.submit();
                    } else {
                        this.submitTemplate();
                    }
                }
            });
        },
        uploadHandleRemove(file, fileList) {
            console.log(file, fileList);
        },
        uploadHandlePreview(file) {
            console.log(file);
            console.log(this.fileList);
        },
        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 / 2 <= 1;
            if (!isLt) {
                this.$message.error("上传文件大小不能超过 2MB");
                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);
            }
        },
        uploadHandleError() {

        },
        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;
                            if (this.formName === "add") {
                                // 向头部添加数据
                                if (response.data && response.data.id) {
                                    data.id = response.data.id;
                                    this.list.unshift(data);
                                }
                            } else {
                                this.list.splice(this.index, 1, data);
                            }
                            // 刷新表单
                            this.resetForm();
                            this.getList();
                            this.getModuleList();
                        })
                        .catch(() => {
                            this.formLoading = false;
                        });
                }
            });
        },
        deleteTemplate(row) {
            this.$confirm("此操作将永久删除该模板, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                systemPDFTemplateDeleteById({id: row.id, path: row.path})
                    .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';
            if (this.selectTemplateQuery.type == 1) {


                console.log("this.selectTemplateQuery.busRlId =" + this.selectTemplateQuery.busRlId);
                let query = {
                    id: this.selectTemplateQuery.busRlId,
                    templateId: data.templateId,
                }
                updateDetailRel(query)
                    .then(response => {
                        this.moduleFormVisible = false;
                        this.moduleFormLoading = false;
                        if (response.code !== 20000) {
                            this.$message.error(response.message);
                            return false;
                        }
                        this.getList();
                    }).catch(() => {
                    this.moduleFormLoading = false;
                });
            } else
                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(() => {
                });
        },

        handleEdit(index, row) {
            this.currentCheckIndex = index;
            console.log(this.currentCheckIndex)
        },
        handleSave(index, row) {
            this.currentCheckIndex = -1;
            updateDetailRel(row).then((res) => {
                if (res.code == 20000) {
                    this.$message.success(res.data);
                }
            })
        },

    },
    filters: {
        paramStatusFilterType(paramStatus) {
            const paramStatusTypeMap = {
                0: "gray",
                1: "success"
            };
            return paramStatusTypeMap[paramStatus];
        },
        paramStatusFilterName(paramStatus) {
            const paramStatusNameMap = {
                1: "订单详情",
                2: "配货管理-打印订单"
            };
            return paramStatusNameMap[paramStatus];
        }
    },
    mounted() {
    },
    created() {
        this.getPDFModuleNameList();
        this.getModuleList();
        this.uploadUrl = BASE_URL + "/udiwms/upload/pdf/template";
        this.headers = {
            ADMIN_ID: store.getters.adminId,
            ADMIN_TOKEN: store.getters.token,
        };
    }
};
</script>

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