<template>
    <div class="ele-body">
        <a-card :bordered="false">
            <a-form
                :model="where"
                :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }"
            >
                <a-row>
                    <a-col :lg="6" :md="12" :sm="24" :xs="24">
                        <a-form-item label="年份:">
                            <a-select v-model:value="where.year" allow-clear show-search>
                                <a-select-option
                                    v-for="(item) in yearOptions"
                                    :key="item.value"
                                >{{ item.label }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6" :md="12" :sm="24" :xs="24">
                        <a-space>
                            <a-button type="primary" @click="reload">查询</a-button>
                            <a-button @click="reset">重置</a-button>
                        </a-space>
                    </a-col>
                </a-row>
                <a-row>

                </a-row>
            </a-form>
            <a-modal
                v-model:visible="showNYear"
                :title="'批量复制'"
                :confirm-loading="loading"
                :body-style="{ paddingBottom: '8px' }"
                @ok="copyBatch"
            >
                <a-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    :label-col="{ md: { span: 6 }, sm: { span: 24 } }"
                    :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }"
                >
                    <a-form-item label="新年份" name="nYear">
                        <a-input-number id="inputNumber" v-model:value="nYear" :min="1970" :max="2050"/>
                    </a-form-item>
                </a-form>
            </a-modal>
            <a-modal
                v-model:visible="showEdit"
                :title="form.zoneNoisePlaceId !== undefined ? '修改' : '添加'"
                :confirm-loading="loading"
                :width="800"
                :body-style="{ paddingBottom: '8px' }"
                @ok="save"
            >
                <a-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    :label-col="{ md: { span: 6 }, sm: { span: 24 } }"
                    :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }"
                >
                    <a-form-item label="年份" name="year">
                        <a-input-number v-model:value="form.year" :min="1970" :max="2050"/>
                    </a-form-item>
                    <a-form-item label="测点名称" name="placeName">
                        <a-input v-model:value="form.placeName" placeholder="请输入测点名称" allow-clear/>
                    </a-form-item>
                    <a-form-item label="点位编码" name="placeCode">
                        <a-input v-model:value="form.placeCode" placeholder="请输入点位编码" allow-clear/>
                    </a-form-item>
                    <a-form-item label="所属路段" name="road">
                        <a-input v-model:value="form.road" placeholder="请输入所属路段" allow-clear />
                    </a-form-item>
                    <a-form-item label="所属城区" name="area">
                        <a-input v-model:value="form.area" placeholder="请输入所属城区" allow-clear />
                    </a-form-item>
                    <a-form-item label="功能区代码" name="functionCode">
                        <a-input v-model:value="form.functionCode" placeholder="请输入功能区代码" allow-clear />
                    </a-form-item>
                    <a-form-item label="网格边长" name="girdLength">
                        <a-input type="number" v-model:value="form.girdLength" placeholder="请输入网格边长" allow-clear/>
                    </a-form-item>
                    <a-form-item label="声源代码" name="sourceCode">
                        <a-input v-model:value="form.sourceCode" placeholder="请输入声源代码" allow-clear />
                    </a-form-item>
                    <a-form-item label="测点经度" name="placeLng">
                        <a-input type="number" v-model:value="form.placeLng" placeholder="请输入测点经度" allow-clear/>
                    </a-form-item>
                    <a-form-item label="测点纬度" name="placeLat">
                        <a-input type="number" v-model:value="form.placeLat" placeholder="请输入测点纬度" allow-clear/>
                    </a-form-item>
                    <a-form-item label="点位等级" name="regionLevel">
                        <a-input v-model:value="form.regionLevel" placeholder="请输入点位等级" allow-clear />
                    </a-form-item>

                </a-form>
            </a-modal>
            <!-- 表格 -->
            <ele-pro-table
                v-model:selection="selectionList"
                ref="table"
                row-key="zoneNoisePlaceId"
                :datasource="url"
                :columns="columns"
                :where="where"
                :scroll="{ x: 'max-content' }"
            >
                <template #toolbar>
                    <a-space>
                        <a-button @click="openEdit" type="primary">新增</a-button>
                        <a-dropdown>
                            <template #overlay>
                                <a-menu @click="setCYear">
                                    <a-menu-item v-for="item in yearOptions" :key="item.value">
                                        {{ item.label }}
                                    </a-menu-item>
                                </a-menu>
                            </template>
                            <a-button>
                                批量复制
                                <DownOutlined/>
                            </a-button>
                        </a-dropdown>
                        <a-popconfirm
                            :disabled="selectionList.length == 0"
                            :title="`确认删除${selectionList.length}条数据吗?`"
                            ok-text="Yes"
                            cancel-text="No"
                            @confirm="removeBatch"
                        >
                            <a-button
                                :disabled="selectionList.length == 0"
                                type="primary"
                                ghost
                                danger
                            >删除
                            </a-button>
                        </a-popconfirm>
                        <a-upload
                            :before-upload="importFile"
                            :showUploadList="false"
                            accept=".xls,.xlsx,.csv"
                        >
                            <a-button>导入</a-button>
                        </a-upload>
                        <a-button @click="exportData" type="primary">导出</a-button>
                    </a-space>
                </template>
                <template #action="{ record }">
                    <a-space>
                        <a-button
                            @click="openEdit(record)"
                            type="primary"
                            shape="round"
                            size="small"
                        >修改
                        </a-button
                        >
                        <a-popconfirm
                            :title="`确认删除这条数据吗?`"
                            ok-text="Yes"
                            cancel-text="No"
                            @confirm="remove(record)"
                        >
                            <a-button type="primary" danger shape="round" size="small"
                            >删除
                            </a-button
                            >
                        </a-popconfirm>
                    </a-space>
                </template>
            </ele-pro-table>
        </a-card>
    </div>
    <!-- 编辑弹窗 -->
</template>

<script>
// import _ from "lodash";
import {
    listAllUrl,
    savePlace,
    updatePlace,
    removePlace,
    removeBatchPlace,
    copyBatchPlace,
    getColumnOptions,
    savePlaceBatch
} from "@/api/ecology/noise/zone-noise-place";
import {DownOutlined} from '@ant-design/icons-vue';
import XLSX from "xlsx";
import {Modal} from "ant-design-vue";
// import moment from "moment";
export default {
    name: "ZoneNoisePlace",
    components: {DownOutlined},
    data() {
        return {
            data: [],
            // 表格数据接口
            url: listAllUrl,
            selection: [],
            // 表格列配置
            columns: [
                {
                    title: "年份",
                    dataIndex: "year",
                    sorter: true,
                },
                {
                    title: "测点名称",
                    dataIndex: "placeName",
                    sorter: true,
                }, {
                    title: "点位编码",
                    dataIndex: "placeCode",
                    sorter: true,
                },
                {title: "所属路段",dataIndex: "road",sorter: true, },
                {title: "所属城区",dataIndex: "area",sorter: true, },
                {title: "功能区代码",dataIndex: "functionCode",sorter: true, },
                {title: "网格边长",dataIndex: "gridLength",sorter: true, },
                {title: "声源代码",dataIndex: "sourceCode",sorter: true, },

                {title: "测点经度",dataIndex: "placeLng",sorter: true,},
                {
                    title: "测点纬度",
                    dataIndex: "placeLat",
                    sorter: true,
                },
                {title: "点位等级",dataIndex: "regionLevel",sorter: true, },
                {title: "操作",key: "action",width: 150,align: "center",
                    fixed: "right",
                    slots: {
                        customRender: "action",
                    },
                },
            ],

            // 表格搜索条件
            where: {},
            yearOptions: [],
            // 表格选中数据
            selectionList: [],
            // 是否显示编辑弹窗
            showEdit: false,
            showNYear: false,
            cYear: undefined,
            nYear: undefined,
            // 表单数据
            form: {},
            loading: false,
            rules: {
                // year: [{required: true, message: '请输入年份'}],
                // placeName: [{required: true, message: '请输入测点名称'}],
                // placeCode: [{required: true, message: '请输入点位编码'}],
                // placeLng: [{required: true, message: '请输入测点经度',},],
                // placeLat: [{required: true, message: '请输入测点纬度',},],
            },
        };
    },
    mounted() {
        this.getOptions();
    },
    methods: {
        /* 刷新表格 */
        reload() {

            this.$refs.table.reload({
                where: this.where,
            });
        },
        getOptions() {
            getColumnOptions("year").then(res => {
                console.log(res)
                if (res.data.code == 0) {
                    this.yearOptions = res.data.data.map(item => {
                        return {
                            label: item,
                            value: item
                        }
                    })
                }
            })
        },
        /* 重置搜索 */
        reset() {
            this.where = {};
            this.reload();
        },
        /* 打开编辑弹窗 */
        openEdit(row) {
            // cloneRecord.mi
            this.form = Object.assign({}, row);
            this.showEdit = true;
            this.$nextTick(() => {
                this.$refs.form.clearValidate(); // 清除表单验证信息
            });
        },
        async save() {
            await this.$refs.form.validate();
            const hide = this.$message.loading('请求中..', 0);
            const form = this.form;
            if (form.zoneNoisePlaceId) {
                updatePlace(form)
                    .then((res) => {
                        if (res.data.code == 0) {
                            this.showEdit = false;
                            this.$message.success(res.data.msg);
                            this.reload();
                            this.getOptions();

                        } else {
                            this.$message.error(res.data.msg);
                        }
                    })
                    .catch((error) => {
                        this.$message.error(error.message);
                    })
                    .finally(() => {
                        hide();
                    });
            } else {
                savePlace(form)
                    .then((res) => {
                        if (res.data.code == 0) {
                            this.showEdit = false;
                            this.$message.success(res.data.msg);
                            this.reload();
                            this.getOptions();

                        } else {
                            this.$message.error(res.data.msg);
                        }
                    })
                    .catch((error) => {
                        this.$message.error(error.message);
                    })
                    .finally(() => {
                        hide();
                    });
            }
        },
        /* 删除单个 */
        remove(row) {
            const hide = this.$message.loading('请求中..', 0);
            removePlace(row.zoneNoisePlaceId).then((res) => {
                hide();
                if (res.data.code === 0) {
                    this.$message.success(res.data.msg);
                    this.reload();
                } else {
                    this.$message.error(res.data.msg);
                }
            }).catch(e => {
                hide();
                this.$message.error(e.message);
            })
        },
        /* 批量删除 */
        removeBatch() {
            const hide = this.$message.loading('请求中..', 0);
            const ids = this.selectionList.map((item) => item.zoneNoisePlaceId);
            removeBatchPlace(ids).then((res) => {
                if (res.data.code === 0) {
                    this.$message.success(res.data.msg);
                    this.reload();
                } else {
                    this.$message.error(res.data.msg);
                }
            }).catch(e => {
                this.$message.error(e.message);
            }).finally(() => {
                hide();
            })
        },
        setCYear(e) {
            this.cYear = e.key;
            this.showNYear = true;
        },
        copyBatch() {
            const hide = this.$message.loading('请求中..', 0);
            copyBatchPlace({cyear: Number(this.cYear), nyear: this.nYear}).then(res => {
                if (res.data.code === 0) {
                    this.$message.success(res.data.msg);
                    this.reload();
                    this.getOptions();
                } else {
                    this.$message.error(res.data.msg);
                }
                this.showNYear = false;
            }).catch(e => {
                this.$message.error(e.message);
            }).finally(() => {
                hide();
            })
        },
        exportData() {
            const columns = this.columns.filter(item => item.dataIndex);
            const arr = [];
            const th = columns.map((item) => item.title);
            arr.push(th);
            this.data.forEach((d) => {
                const td = columns.map((item) => d[item.dataIndex]);
                arr.push(td);
            });

            let sheet = XLSX.utils.aoa_to_sheet(arr);
            this.$util.exportSheet(XLSX, sheet, new Date().getTime().toString());
        },
        importFile(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",
                    });
                    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 >= 10 && item[0] && !item[0].toString().includes("年")
                        }
                    );

                    // 解析成对象数组
                    const billData = roadNoiseList.map(item=>{
                        return {
                            year:item[0],
                            placeCode:item[1],
                            placeName:item[2],
                            road:item[3],
                            area:item[4],
                            functionCode:item[5],
                            gridLength:item[6],
                            gridWidth:item[6],
                            sourceCode:item[7],
                            placeLng:item[8],
                            placeLat:item[9],
                            regionLevel:item[10],
                        }
                    });

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

                        return;
                    }

                    if (billData.length > 0) {
                        // 上传到服务器
                        savePlaceBatch(billData)
                            .then((res) => {
                                if (res.data.code == 0) {
                                    Modal.success({
                                        title: "导入成功",
                                        content: `成功导入${
                                            billData.length
                                        }条数据`,
                                    });
                                    this.reload();
                                    this.getOptions();
                                } 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>