<template>
    <div class="app-container">
        <el-form :model="filterForm" label-width="100px" style="margin-top: 30px;">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="同步记录主键">
                        <el-input v-model="filterForm.fid" placeholder="请输入同步记录主键" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="唯一标识">
                        <el-input v-model="filterForm.queueId" placeholder="请输入唯一标识" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="金蝶标识">
                        <el-input v-model="filterForm.sFormId" placeholder="请输入金蝶标识" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="4" style="text-align: center;">
                    <el-button type="primary" @click="onConfirm">筛选</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-divider />
        <div style="margin: 20px 0">
            <el-space :size="30">
                <!-- <el-button type="primary" icon="Refresh" @click="handleErrorManual">重置同步</el-button> -->
                <!-- <el-button type="primary" icon="Finished" @click="handleCheck">校验</el-button> -->
                <el-button :type="flag === 1 ? 'info' : 'primary'" icon="SwitchButton" @click="handleOpen">启用同步
                </el-button>
                <el-button :type="flag === 1 ? 'primary' : 'info'" icon="CircleClose" @click="handleClose">关闭同步
                </el-button>
                <el-button type="primary" icon="RefreshRight" @click="handleManual">手动同步</el-button>
                <el-upload v-model:file-list="uploadData.fileList" :action="uploadData.action"
                    :headers="uploadData.headers" accept=".tmp" :show-file-list="false" style="width: 100px;"
                    :on-success="handleSuccess">
                    <el-button type="primary">导入lic文件</el-button>
                </el-upload>
                <div v-show="macAddress" style="font-size: 14px; color: #ccc;">
                    mac地址：
                    {{ macAddress }}
                </div>
            </el-space>
        </div>
        <el-table :data="monitoringData" v-loading="loading" border stripe @filter-change="filterChange">
            <el-table-column prop="status" label="同步状态" :filters="[
                { text: '未同步', value: '0' },
                { text: '同步中', value: '1' },
                { text: '同步失败', value: '2' },
            ]" :filter-multiple="false" filter-placement="bottom-end" align="center" width="135px">
                <template #default="scope">
                    <el-tag type="info" v-show="scope.row.status === 0">未同步</el-tag>
                    <el-tag type="parmary" v-show="scope.row.status === 1">同步中</el-tag>
                    <el-tag type="danger" v-show="scope.row.status === 2">同步失败</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="dataId" label="数据内码" align="center" />
            <el-table-column prop="entryId" label="数据分录内码" align="center" />
            <el-table-column prop="fid" label="主键" align="center" />
            <el-table-column prop="queueId" label="唯一标识" align="center" />
            <el-table-column prop="sFormId" label="金蝶标识" align="center" />
            <el-table-column prop="message" label="错误原因" align="center">
                <template #default="scope">
                    <el-tooltip class="box-item" effect="dark" placement="left" popper-class="tooltip-class">
                        <template #content>
                            <textarea v-model="scope.row.message" class="paperview-input-text" rows="10" cols="30"
                                readonly>
                            </textarea>
                        </template>
                        <span style="white-space: nowrap">{{ scope.row.message }}</span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" />
            <el-table-column label="操作" align="center" width="155px">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div style="margin-top: 20px">
            <el-pagination v-model:currentPage="pageData.currentPage" v-model:page-size="pageData.pageSize"
                :page-sizes="[10, 15, 20]" layout="->, total,sizes, prev, pager, next, jumper" :total="pageData.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" hide-on-single-page />
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { store } from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus';
import { getSMonitoring, deleteSMonitoring } from '@/services/api/systemApi/synchronousMonitoring'
import {
    getStart,
    getManual,
    getOff,
    getabnormal,
    getSRecords,
    importFile,
    getMacAddress
} from "@/services/api/systemApi/synchronization/synchronizationAPI";

const loading = ref(true)
const uploadData = reactive({
    fileList: undefined,
    action: '/integrate/api/lic/info/file/import',
    headers: { Authorization: sessionStorage.getItem("token") }
})

const monitoringData = ref()
const filterForm = ref({
    fid: '',
    queueId: '',
    sFormId: '',
    status: <any>'',
})

const pageData = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10
})

const macAddress = ref()

// 1、 启动 0、 关闭
const flag = ref()

// 筛选
const onConfirm = () => {
    store.commit('search/setMonitoringSearch', filterForm.value)
    initSMonitoring(
        pageData.currentPage,
        pageData.pageSize,
        filterForm.value.fid,
        filterForm.value.queueId,
        filterForm.value.sFormId,
        filterForm.value.status
    )
}

const handleSuccess = (res: any, uploadFile: any, uploadFiles: any) => {
    if (res.code === 200) {
        ElMessage({ type: 'success', message: '导入成功！' })
    }
    else return ElMessage({ type: 'error', message: res.message })
}

// 同步筛选
const filterChange = (value: any) => {
    let i = ''
    Object.values(value).forEach((e: any) => {
        i = e[0]
    })
    filterForm.value.status = i;
    initSMonitoring(
        pageData.currentPage,
        pageData.pageSize,
        filterForm.value.fid,
        filterForm.value.queueId,
        filterForm.value.sFormId,
        filterForm.value.status
    )
};

// 每页新条数
const handleSizeChange = (val: number) => {
    pageData.pageSize = val
    initSMonitoring(
        pageData.currentPage,
        pageData.pageSize,
        filterForm.value.fid,
        filterForm.value.queueId,
        filterForm.value.sFormId,
        filterForm.value.status
    )
};
// 新页数
const handleCurrentChange = (val: number) => {
    pageData.currentPage = val
    initSMonitoring(
        pageData.currentPage,
        pageData.pageSize,
        filterForm.value.fid,
        filterForm.value.queueId,
        filterForm.value.sFormId,
        filterForm.value.status
    )
};

const initSRecords = () =>
    getSRecords().then((res: any) => flag.value = res.data.status)


initSRecords()

const handleDelete = (id: number) => {
    ElMessageBox.confirm(
        '确定删除该字段?',
        '配置',
        { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
            deleteSMonitoring(id).then((res: any) => {
                if (res.code === 200) {
                    initSMonitoring()
                    ElMessage({ type: 'success', message: '删除成功' })
                }
            })
        }).catch(() => { return false })
}

const handleErrorManual = async () => {
    const res: any = await getabnormal()
    if (res.code === 200) {
        ElMessage({ type: 'success', message: '重置同步成功' })
    }
};

// 开启自动同步 
const handleOpen = async () => {
    // if (isDisabled.value === true) return;
    const res: any = await getStart();
    if (res.code === 200) {
        initSRecords()
        setTimeout(() => {
            initSMonitoring(
                pageData.currentPage,
                pageData.pageSize,
                filterForm.value.fid,
                filterForm.value.queueId,
                filterForm.value.sFormId,
                filterForm.value.status
            )
        }, 1000);
        return ElMessage({ type: "success", message: "自动启动成功" });
    }
};

// 关闭自动同步
const handleClose = async () => {
    const res: any = await getOff();
    if (res.code === 200) {
        initSRecords()
        setTimeout(() => {
            initSMonitoring(
                pageData.currentPage,
                pageData.pageSize,
                filterForm.value.fid,
                filterForm.value.queueId,
                filterForm.value.sFormId,
                filterForm.value.status
            )
        }, 1000);
        return ElMessage({ type: "success", message: "关闭成功" });
    }
};
// 手动同步
const handleManual = async () => {
    const res: any = await getManual()
    if (res.code === 200) {
        initSRecords()
        setTimeout(() => {
            initSMonitoring(
                pageData.currentPage,
                pageData.pageSize,
                filterForm.value.fid,
                filterForm.value.queueId,
                filterForm.value.sFormId,
                filterForm.value.status
            )
        }, 1000);
        ElMessage({ type: 'success', message: '手动同步成功' })
    }
};


const handleMacAddress = () => {
    getMacAddress().then((res: any) => {
        if (res.code === 200) {
            macAddress.value = res.data
        }
    })
}
handleMacAddress()


// 监控数据
const initSMonitoring = (
    pageNo?: number,
    pageSize?: number,
    fid?: string,
    queueId?: string,
    sFormId?: string,
    status?: number
) => {
    getSMonitoring(pageNo, pageSize, fid, queueId, sFormId, status).then((res: any) => {
        if (res.code === 200) {
            console.log(res);
            loading.value = false
            pageData.total = res.data.total
            monitoringData.value = res.data.records
        }
    })
}

onMounted(() => initSMonitoring(pageData.currentPage, pageData.pageSize))

const initfilter = () => {
    let data: any = store.state.search.monitoringSearch
    setTimeout(() => {
        filterForm.value = data
        initSMonitoring(
            pageData.currentPage,
            pageData.pageSize,
            filterForm.value.fid,
            filterForm.value.queueId,
            filterForm.value.sFormId,
            filterForm.value.status
        )
    }, 50)
}
initfilter()
</script>

<style scoped>
.paperview-input-text {
    border: 0;
    color: #fafcff;
    background-color: #303133;
}
</style>