<template>
    <div class="fullHeight">
        <div class="searchBox whiteBlock">
            <el-form>
                <el-form-item>
                    <!-- v-permission="{ key: 'datavalidation_staffmanualcheck', menuPath: '/project/labor/dataValidation' }" -->
                    <!-- 人员手动校验 -->
                    <el-button type="primary" @click="onStaffIsCarManualCheck(1)">
                        人员手动校验
                    </el-button>
                    <!-- 车辆手动校验 -->
                    <el-button @click="onStaffIsCarManualCheck(2)" type="primary">
                        车辆手动校验
                    </el-button>
                    <!-- 批量同步 -->
                    <el-button @click="onBatchSynchronization()" type="primary">
                        批量同步
                    </el-button>
                    <el-button type="warning" plain @click="resetForm()">
                        {{ $t("message.personnelPosition.beaconManage.refresh") }}
                    </el-button>
                    <el-tooltip class="item" effect="light" placement="bottom-start">
                        <i class="el-icon-question"></i>
                        <div style="font-size: 14px" slot="content">
                            <p>
                                定时任务:每天凌晨做ISC与平台的人员组织信息、人员基本信息、人脸照片、车辆基本信息数据比对，返<br />回所有比对结果，手动批量同步，同步成功后删除记录。
                            </p>
                            <p style="margin-top: 6px">
                                人员手动校验:定时任务数据校验网络超时无法进行时，使用手动校验ISC与平台的人员组织信息、人员基<br />本信息、人脸照片返回所有比对结果，手动批量同步，同步成功后删除记录。
                            </p>
                            <p style="margin-top: 6px">
                                车辆手动校验:定时任务数据校验网络超时无法进行时，使用手动校验ISC与平台的车辆基本信息，返回所<br />有比对结果，手动批量同步，同步成功后删除记录。
                            </p>
                        </div>
                    </el-tooltip>
                </el-form-item>
            </el-form>
        </div>
        <div class="table_wrap whiteBlock">
            <el-tabs v-model="activeName" @tab-click="handleClick" style="padding: 0 15px">
                <el-tab-pane label="人员组织" name="1"></el-tab-pane>
                <el-tab-pane label="人员信息" name="2"></el-tab-pane>
                <el-tab-pane label="人员照片" name="3"></el-tab-pane>
                <el-tab-pane label="车辆信息" name="4"></el-tab-pane>
            </el-tabs>
            <el-table ref="multipleTable" class="tables" row-key="id" :data="tableList" @selection-change="handleSelectionChange">
                <el-table-column align="center" type="selection" width="55" :reserve-selection="true">
                </el-table-column>
                <el-table-column show-overflow-tooltip v-if="activeName == '1'" align="center" prop="orgName"
                    label="组织名称"></el-table-column>
                <el-table-column show-overflow-tooltip v-else-if="activeName == '2' || activeName == '3'" align="center"
                    prop="workerName" label="人员姓名"></el-table-column>
                <el-table-column show-overflow-tooltip v-else-if="activeName == '4'" align="center" prop="carNumber"
                    label="车牌号"></el-table-column>
                <el-table-column show-overflow-tooltip v-if="activeName == '2' || activeName == '3'" align="center" prop="idCard"
                    label="身份证号"></el-table-column>
                <el-table-column align="center" label="ISC校验结果">
                    <template slot-scope="scope">
                        <div :class="scope.row.existIsc == 1 ? 'refreshbtn' : 'unrefreshbtn'">
                            {{ scope.row.existIsc == 1 ? "存在" : "不存在" }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="平台校验结果">
                    <template slot-scope="scope">
                        <div :class="
                            scope.row.existMyPlatform == 1 ? 'refreshbtn' : 'unrefreshbtn'
                        ">
                            {{ scope.row.existMyPlatform == 1 ? "存在" : "不存在" }}
                        </div>
                        <!-- scope.row -->
                    </template>
                </el-table-column>
                <el-table-column align="center" label="同步结果">
                    <template slot-scope="scope">
                        <el-button class="synchronization" disabled :type="scope.row.syncResult == 1 ? 'info' : 'danger'">{{
                            scope.row.syncResult == 1 ? "未同步" : "同步失败"
                        }}</el-button>
                        <!-- <el-button class="synchronization" disabled type="danger">同步失败</el-button>
                        <el-button class="synchronization" disabled type="success">同步成功</el-button> -->
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                        <!-- unrefreshbtn -->
                        <div @click="onHikvisionSync(scope.row.id)"
                            :class="scope.row.syncResult == 1 ? 'refreshbtn' : 'unrefreshbtn'" class="accessory">
                            <i class="el-icon-refresh"></i>
                            {{ scope.row.syncResult == 1 ? "同步" : "重试" }}
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pagerBox" @size-change="sizeChange" @current-change="currentChange"
                :current-page="pagInfo.pageNo" :page-sizes="pageSizeList" :page-size="pagInfo.pageSize"
                layout="total, sizes, prev, pager, next" :total="Number(pagInfo.total)" background></el-pagination>
        </div>
    </div>
</template>
<script>
import {
    getHikvisionExceptionApi,
    getHikvisionPageApi,
    getHikvisionSyncApi,
    getHikvisionManualCompareApi,
} from "@/assets/js/api/laborPerson";
import mqtt from "mqtt";
var client = null;
const options = {
    connectTimeout: 40000,
    clientId: "mqttjs_" + Math.random().toString(16).substr(2, 8),
    username: "root",
    password: "123456",
    clean: true,
};
export default {
    data() {
        return {
            pageSizeList: [],
            projectSn: "",
            activeName: "1", //tab切换
            pagInfo: {
                //公用分页
                pageNo: 1,
                pageSize: 10,
                total: 0,
            },
            tableList: [],
            multipleSelection: [],
            topicName: "topic",
            userId: "",
        };
    },
    created() {
        this.projectSn = this.$store.state.projectSn;
        this.getHikvisionException();
        this.pageSizeList = JSON.parse(JSON.stringify(this.$store.state.PAGESIZRS));
        // this.tableList = [
        //     {
        //         id: "1",
        //         name: "新地能源工程技术有限公司",
        //         workerName: "张三",
        //         syncResult: 1,
        //         idCard: "123456",
        //         carNumber: "G-320"
        //     },
        //     {
        //         id: "2",
        //         name: "新地能源工程技术有限公司",
        //         workerName: "李四",
        //         syncResult: 2,
        //         idCard: "1234567",
        //         carNumber: "G-320"
        //     },
        // ];
    },
    mounted() {
        this.userId = this.$store.state.userInfo.userId;
        this.topicName = this.$store.state.userInfo.scope;
        client = mqtt.connect(mqttUrl, options);
        this.mqttMSG();
    },
    methods: {
        // 监听mqtt下发信息然后刷新列表
        mqttMSG() {
            // mqtt连接   +"/#"  +workerId
            client.on("connect", (e) => {
                // console.log('连接成功:', this.topicName + this.userId)
                client.subscribe(this.topicName + this.userId, { qos: 0 }, (error) => {
                    if (!error) {
                        // console.log('订阅成功123')
                    } else {
                        console.log("订阅失败");
                    }
                });
            });
            // 接收消息处理
            client.on("message", (topic, message) => {
                console.log(message);
                this.getHikvisionPage();
            });
            // 断开发起重连
            // client.on("reconnect", (error) => {
            //   console.log("正在重连:", error);
            // });
            // 链接异常处理
            client.on("error", (error) => {
                console.log("连接失败:", error);
            });
        },
        // 批量同步 || 同步
        onBatchSynchronization() {
            if (this.multipleSelection.length == 0) {
                this.$message.warning("请选择需要同步的数据!");
                return;
            }

            console.log(this.multipleSelection);
            const ids = this.multipleSelection.map((item) => item.id).join(",");
            this.onHikvisionSync(ids);
        },
        onHikvisionSync(ids) {
            getHikvisionSyncApi({
                projectSn: this.projectSn,
                ids,
            }).then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.message);
                } else {
                    this.$message.error(res.result.msg);
                }
            });
        },
        // 选中状态
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 人员|车辆手动校验
        onStaffIsCarManualCheck(type) {
            getHikvisionManualCompareApi({
                projectSn: this.projectSn,
                type: type,
            }).then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.message);
                    this.getHikvisionPage();
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        // 校验是否弹窗
        getHikvisionException() {
            getHikvisionExceptionApi({
                projectSn: this.projectSn,
                type: Number(this.activeName),
            }).then((res) => {
                console.log(res);
                if (res.code == 200) {
                    this.getHikvisionPage();
                } else {
                    this.$message.error(res.result.msg);
                }
            });
        },
        //获取信息
        getHikvisionPage() {
            getHikvisionPageApi({
                projectSn: this.projectSn,
                pageNo: this.pagInfo.pageNo,
                pageSize: this.pagInfo.pageSize,
                type: Number(this.activeName),
            }).then((res) => {
                if (res.code == 200) {
                    this.tableList = res.result.records;
                    this.pagInfo.total = res.result.total;
                    if(+res.result.total>this.pageSizeList[this.pageSizeList.length - 1]){
                        this.pageSizeList.push(+res.result.total)
                    }
                }
            });
        },

        //切换Tab记录类型
        handleClick(val) {
            // console.log(val.name);
            this.activeName = val.name;
            this.$refs.multipleTable.clearSelection();
            this.pageSizeList = JSON.parse(JSON.stringify(this.$store.state.PAGESIZRS));
            this.initClear();
            this.getHikvisionPage();
        },
        // 初始化
        initClear() {
            this.pagInfo = {
                pageNo: 1,
                pageSize: 10,
                total: 0,
            };
            this.multipleSelection = [];
        },
        // 刷新
        resetForm() {
            this.initClear();
            this.getHikvisionException();
        },
        //切换条数
        sizeChange(val) {
            this.pagInfo.pageSize = val;
            this.getHikvisionPage();
        },
        //切换页数
        currentChange(val) {
            this.pagInfo.pageNo = val;
            this.getHikvisionPage();
        },
    },
};
</script>
<style lang="less" scoped>
/deep/ .el-icon-question {
    font-size: 22px;
    margin-left: 10px;
}

.synchronization {
    padding: 8px 16px;
    cursor: text !important;
}

.refreshbtn {
    color: #5181f6;
}

.unrefreshbtn {
    color: #f56c6c;
}

.tables {
    min-height: 535px;
    max-height: calc(100% - 128px);
}

.pagerBox {
    margin-top: 30px;
}

.accessory {
    cursor: pointer;
}
</style>
