<!--
  功能：功能描述  出入库报表
  作者：陶庆峰
-->
<template>
    <div class="vue-element-page-wrap" ref="tableContainer">
        <el-row class="page-search" justify="space-between" align="bottom">
            <el-form ref="queryFormRef" :model="queryParams" label-width="60px" label-position="left">
                <el-row :gutter="24" class="form-row">
                    <el-col :span="4">
                        <el-form-item label="开始时间" prop="FROMDATE">
                            <el-date-picker v-model="queryParams.FROMDATE" value-format="YYYYMMDD" type="date"
                                placeholder="Pick a day" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="结束时间" prop="TODATE">
                            <el-date-picker v-model="queryParams.TODATE" value-format="YYYYMMDD" type="date"
                                placeholder="Pick a day" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="page-search-btns">
                <el-button type="primary" @click="handleQueryInfo">搜索</el-button>
                <!--                <el-button type="primary" @click="exportExcel">导出</el-button>-->
                <!--                <el-button @click="resetQuery">重置</el-button>-->
            </div>
        </el-row>

        <div class="vue-element-page-table">
            <el-row :gutter="24" class="form-row">
                <el-col :span="18">
                    <el-table border v-loading="loading" :data="list" highlight-current-row row-key="id" :height="tableHeight"
                        style="width: 100%" @row-click="handle">
                        <template v-for="(col, index) in column" :key="index">
                            <el-table-column v-if="!col.hide" :label="col.header" :width="col.width"
                                show-overflow-tooltip>
                                <template #default="scope">
                                    <span>{{ scope.row[col.field] }}</span>
                                </template>
                            </el-table-column>
                        </template>
                    </el-table>
                </el-col>
                <el-col :span="6">
                    <el-input v-model="state.textarea" :rows="26" type="textarea" placeholder="Please input"
                        class="el-inputs" />
                </el-col>
            </el-row>
            <pagination v-if="page.total" :total="page.total" v-model:pageNumTo="page.pageNum"
                v-model:pageSizeTo="page.pageSize" @pagination="handleQuery" />
        </div>
    </div>
</template>

<script lang="ts">
export default {
    name: "InterfaceSendHistory",
};
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from "vue";
import { ElForm, ElMessageBox, ElTable } from 'element-plus'
import { getQueryPageList, getQueryList } from '@/api/common';
import exportDataToExcel from '@/utils/export-excel';
import { bTableHeight } from "../../../../composables/calcTableHeight";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(160);

const { proxy }: any = getCurrentInstance();
const queryFormRef = ref(ElForm);

const state = reactive({
    radio1: '出库',
    textarea: '',
    queryParams: {
        MATERIALSPECNAME: '',
        UNDOID: '',
        STOCKSTATE: '',
        ERPLOCATION: '',
        FROMDATE: '',
        TODATE: '',
        SITENAME: '',
        ERPFACTORY: '',
        SHIPREQUESTNAME: '',
        RECEIVEREQUESTNAME: '',
        REQUESTNAME: '',
    },
    page: {
        pageNum: 1,
        pageSize: 15,
        total: 0
    },

    loading: false,
    list: [],
    column: [] as any,
});

const { loading, list, column, queryParams, page } = toRefs(state)

onMounted(() => {
    state.column = [
        { header: "发送方", field: "SERVERNAME", hide: false, width: '300px' },
        { header: "接口名", field: "EVENTNAME", hide: false },
        { header: "发送报文", field: "MESSAGELOG", hide: false },
        { header: "发送者", field: "EVENTUSER", hide: false },
        { header: "发送结果", field: "RESULTMESSAGE2", hide: false },

    ]
    handleQuery()
    updateTableHeight();
    window.addEventListener('resize', handleResize);
});
function handleQueryInfo() {
  state.page.pageNum = 1
  handleQuery()
}
function handleQuery() {
    state.loading = true
    queryFormRef.value.validate((isValid: boolean) => {
        if (isValid) {
            state.list = []
            getQueryPageList({
                queryId: "InterfaceSendHistory",
                version: "WEB0001",
                params: {
                    FROMDATE: state.queryParams.FROMDATE,
                    TODATE: state.queryParams.TODATE
                },
                pageNum: state.page.pageNum,
                pageSize: state.page.pageSize,
            }).then((res: any) => {
              if(res.data.list.length == 0){

                ElMessageBox.alert('查无数据', '提醒框', {
                  confirmButtonText: 'OK',
                })
                state.loading = false
              } else {

                state.list = res.data.list;
                state.page.total = res.data.total;
                state.loading = false
              }
            });
        }
    });
}


function resetQuery() {
    queryFormRef.value.resetFields();
    handleQuery();
}

function handle(row: any, event: any, column: any) {
    state.textarea = formatJsonString(row.MESSAGELOG)
    console.log(state.textarea)
}


function formatJsonString(jsonString: any) {
    try {
        if (isJSON(jsonString)) {
            // 解析 JSON 字符串为 JavaScript 对象  
            const jsonObject = JSON.parse(jsonString);
            // 格式化并返回 JSON 字符串  
            return JSON.stringify(jsonObject, null, 2); // 第二个参数为 replacer 函数（这里用 null 表示使用默认），第三个参数为缩进级别  
        } else {
            return formatXml(jsonString)
        }

    } catch (error) {
        console.error('无法解析 JSON 字符串:', error);
        return jsonString; // 或者返回错误消息等  
    }
}
function isJSON(str: any) {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    }

}

function formatXml(xmlString: any, indent = '') {
    // 移除已有的空格和换行符  
    xmlString = xmlString.trim().replace(/>\s+</g, '>');

    // 查找所有的开始和结束标签  
    const startTagRegex = /<(\/?\w+)([^>]*)>/g;
    let formatted = '';
    let lastMatchEnd = 0;

    let match;
    while ((match = startTagRegex.exec(xmlString)) !== null) {
        // 添加文本（如果有）  
        formatted += xmlString.substring(lastMatchEnd, match.index);

        // 添加标签  
        const tagName = match[1];
        const attrs = match[2];

        // 如果是结束标签，则缩进减少  
        if (tagName.startsWith('/')) {
            indent = indent.slice(0, -2); // 假设每个级别缩进两个空格  
        }

        // 添加缩进和标签  
        formatted += `\n${indent}<${tagName}${attrs}>`;

        // 如果是开始标签，则缩进增加  
        if (!tagName.startsWith('/')) {
            indent += '  '; // 缩进增加两个空格  
        }

        lastMatchEnd = startTagRegex.lastIndex;
    }

    // 添加剩余的文本（如果有）  
    formatted += xmlString.substring(lastMatchEnd);

    // 移除尾部的多余换行符  
    formatted = formatted.trim();

    return formatted;
} 
</script>

<style scoped lang="scss">
.form-row {
    padding-right: 100px;
    margin-bottom: 7px;
}

.form-row2 {
    padding-right: 30px;
    margin-bottom: 30px;
}

.el-inputs {
    font-size: 0.8em;
    font-weight: bolder;
    width: 100%;
    margin: 0;
    padding: 0;
}
</style>