<template>
    <div class="ele-body">
        <a-card style="width: 100%" :bordered="false">
            <template #title>
                <a-space>
                    <a-upload
                        :before-upload="importFileCity"
                        :showUploadList="false"
                        accept=".xls,.xlsx,.csv"
                    >
                        <a-button>市级导入</a-button>
                    </a-upload>
                    <a-upload
                        :before-upload="importFileArea"
                        :showUploadList="false"
                        accept=".xls,.xlsx,.csv"
                    >
                        <a-button>县级导入</a-button>
                    </a-upload>
                </a-space>
            </template>
            <a-tabs v-model:activeKey="activeKey">
                <a-tab-pane tab="噪声信息" key="noise">
                    <noise-bill ref="noise"></noise-bill>
                </a-tab-pane>
            </a-tabs>
        </a-card>
    </div>
</template>

<script>
import XLSX from "xlsx";
import utils from "./utils";
import {Modal} from "ant-design-vue";
import NoiseBill from "./noise-bill.vue";
import {saveRoadNoiseBill} from "@/api/ecology/noise/road-sound";

export default {
    name: "RoadCollectIndex",
    components: {
        NoiseBill,
    },
    data() {
        return {
            activeKey: "noise",
        };
    },
    methods: {
        /* 导入本地excel文件 */
        importFileCity(file) {
            const hide = this.$message.loading("导入中..", 0);

            let reader = new FileReader();
            reader.onload = (e) => {
                try {
                    let data = new Uint8Array(e.target.result);
                    let workbook = XLSX.read(data, {
                        type: "array",
                    });
                    //0.昼间数据 1.夜间数据 2.其他信息
                    let sheetNames = workbook.SheetNames;
                    // 解析成二维数组
                    let aoa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[0]], {
                        header: 1,
                    });
                    let aoa2 = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[1]], {
                        header: 1,
                    });
                    let aoa3 = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[2]], {
                        header: 1,
                    });
                    const reportDate = aoa[1][0].replace(/[^\d]+/g, "-");
                    const reportDate2 = aoa2[1][0].replace(/[^\d]+/g, "-");

                    const roadNoiseList = aoa.filter(
                        (item) => {
                            console.log(item.length)
                            return item.length >= 21 && typeof item[0] == "number"
                        }
                    );
                    const roadNoiseList2 = aoa2.filter(
                        (item) => item.length >= 21 && typeof item[0] == "number"
                    );
                    const roadNoiseList3 = aoa3.filter(
                        (item) => item.length >= 16 && typeof item[1] == "number"
                    );

                    // 解析成对象数组
                    const billName = file.name;
                    const billData = utils.toObjData(roadNoiseList);
                    const billName2 = file.name;
                    const billData2 = utils.toObjData(roadNoiseList2);
                    // 其他信息
                    const billData3 = utils.toPlaceData(roadNoiseList3);
                    if (
                        (!billData || billData.length == 0) &&
                        (!billData2 || billData2.length == 0)
                    ) {
                        hide()
                        Modal.error({
                            title: "导入失败",
                            content: "找不到数据",
                        });
                        return;
                    }

                    const tasks = [];
                    if (billData.length > 0) {
                        billData.forEach((item) => {
                            Object.assign(
                                item,
                                billData3.find((b3Item) => b3Item.place == item.place)
                            );
                        });
                        tasks.push(
                            saveRoadNoiseBill({
                                reportTime: new Date(reportDate).getTime(),
                                billName: billName,
                                regionLevel: "市级",
                                roadNoiseList: billData,
                            })
                        );
                    }

                    if (billData2.length > 0) {
                        billData.forEach((item) => {
                            Object.assign(
                                item,
                                billData3.find((b3Item) => b3Item.place == item.place)
                            );
                        });
                        tasks.push(
                            saveRoadNoiseBill({
                                reportTime: new Date(reportDate2).getTime(),
                                billName: billName2,
                                regionLevel: "市级",
                                roadNoiseList: billData2,
                            })
                        );
                    }

                    // 上传到服务器

                    Promise.all(tasks)
                        .then(() => {
                            Modal.success({
                                title: "导入成功",
                                content: `成功导入${billData.length + billData2.length}条数据`,
                            });
                            this.$refs.noise && this.$refs.noise.reload();
                            this.$refs.place && this.$refs.place.reload();
                        })
                        .catch(() => {
                            Modal.error({
                                title: "导入失败",
                                content: "数据上传出错",
                            });
                        })
                        .finally(() => {
                            hide();
                        });
                } catch (error) {
                    hide();
                    Modal.error({
                        title: "导入失败",
                        content: error.message,
                    });
                }
                // console.log(billData);
            };
            reader.readAsArrayBuffer(file);

            return false;
        },
        importFileArea(file) {
            const hide = this.$message.loading("导入中..", 0);

            let reader = new FileReader();

            reader.onload = (e) => {
                try {
                    let data = new Uint8Array(e.target.result);
                    let workbook = XLSX.read(data, {
                        type: "array",
                    });
                    //0.昼间数据 1.夜间数据 2.其他信息
                    let sheetNames = workbook.SheetNames;
                    // 解析成二维数组
                    let aoa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[0]], {
                        header: 1,
                    });

                    // const reportDate = aoa[1][0].replace(/[^\d]+/g, "-");
                    const roadNoiseList = aoa.filter(
                        (item) => {
                            return item.length >= 35 && item[0] && !item[0].toString().includes("行政区划代码")
                            // return item.length >= 35 && item[0] != "行政区划代码"
                        }
                    );

                    // 解析成对象数组
                    const billName = file.name;
                    const billData = utils.toAreaObjData(roadNoiseList);

                    if (!billData || billData.length == 0) {
                        hide();
                        Modal.error({
                            title: "导入失败",
                            content: "找不到可用数据",
                        });

                        return;
                    }

                    if (billData.length > 0) {
                        // 上传到服务器
                        saveRoadNoiseBill({
                            // reportTime: new Date(reportDate).getTime(),
                            billName: billName,
                            regionLevel: "县级",
                            roadNoiseList: billData,
                        })
                            .then((res) => {
                                if (res.data.code == 0) {
                                    Modal.success({
                                        title: "导入成功",
                                        content: `成功导入${
                                            billData.length
                                        }条数据`,
                                    });
                                    this.$refs.noise && this.$refs.noise.reload();
                                } else {
                                    Modal.error({
                                        title: "导入失败",
                                        content: "数据上传出错",
                                    });
                                }
                            })
                            .catch(() => {
                                Modal.error({
                                    title: "导入失败",
                                    content: "数据上传出错",
                                });
                            })
                            .finally(() => {
                                hide();
                            });
                    }
                } catch (error) {
                    hide();
                    Modal.error({
                        title: "导入失败",
                        content: error.message,
                    });
                }
                // console.log(billData);
            };
            reader.readAsArrayBuffer(file);
            return false;
        },
    },
};
</script>

<style scoped lang="less">
</style>