<template>
    <div class="m-table">
        <div class="u-table-btn2">
            <div class="u-table-btn2-left">
                <el-button style="" size="small" type="primary " icon="el-icon-plus" @click="handleAdd">新增小区</el-button>

                <div v-if="showImportBtn" class="u-btn-upload">
                    <el-popover v-if="showImportBtn" popper-class="btn-popper" placement="bottom" width="20"
                        trigger="click">
                        <div class="table-more-btn">
                            <el-upload :headers="$getElUploadHeaders()" ref="upload_community" style="text-align: center"
                                :multiple="false" :show-file-list="false" :before-upload="(file) => {
                                    beforeUpload(file, 'community');
                                }
                                    " action="" accept=".xls,.xlsx" :http-request="() => {
        uploadFile('community');
    }
        ">
                                <el-button size="small" type="text" class="diy-button--other">导入小区楼栋数据</el-button>
                            </el-upload>
                        </div>
                        <div class="table-more-btn">
                            <el-upload :headers="$getElUploadHeaders()" style="text-align: center" ref="upload_room"
                                :multiple="false" :show-file-list="false" :before-upload="(file) => {
                                    beforeUpload(file, 'room');
                                }
                                    " action="" accept=".xls,.xlsx" :http-request="() => {
        uploadFile('room');
    }
        ">
                                <el-button size="small" type="text" class="diy-button--other">导入房屋数据</el-button>
                            </el-upload>
                        </div>
                        <el-button size="small" style="float: right" class="diy-button--white" slot="reference">导入<i
                                class="el-icon-arrow-down el-icon--right"></i></el-button>
                    </el-popover>
                </div>
                <el-button style="margin-left: 10px" class="diy-button--white" size="small"
                    @click="handleExportOpen">导出</el-button>

                <el-button style="margin-left: 10px" class="diy-button--white" size="small"
                    @click="deleteBatch">批量删除</el-button>

                <!-- <el-button style=";margin-left:10px"
                 class="diy-button--export"
                 size="small"
                 :disabled="yihuyidangDisabled"
                 @click="handleExportYihuyidang()">导出一户一档</el-button> -->
            </div>
            <div>
                <el-popover popper-class="btn-popper" placement="bottom" style="margin-left: 10px" width="20"
                    trigger="click">
                    <!-- <div v-if="showImportBtn" class="table-more-btn">
                        <el-button class="diy-button--other" size="small" type="text"
                            @click="handleExportModule('community')">下载小区模板</el-button>
                    </div> -->

                    <div v-if="showImportBtn" class="table-more-btn">
                        <el-button :headers="$getElUploadHeaders()" class="diy-button--other" size="small" type="text"
                            @click="handleExportModule('building')">下载小区楼栋模板</el-button>
                    </div>
                    <div v-if="showImportBtn" class="table-more-btn">
                        <el-button :headers="$getElUploadHeaders()" class="diy-button--other" size="small" type="text"
                            @click="handleExportModule('room')">下载房屋模板</el-button>
                    </div>
                    <div  class="table-more-btn">
                        <el-button :headers="$getElUploadHeaders()" class="diy-button--other" size="small" type="text"
                            @click="handleExportIDCard()">下载电子门牌二维码</el-button>
                    </div>
                    <!-- <div
						v-if="
							showYhymInfo && customerId !== '1535072605621841922'
						"
						class="table-more-btn"
					>
						<el-button
							:headers="$getElUploadHeaders()"
							class="diy-button--other"
							size="small"
							type="text"
							:loading="yhymLoading"
							@click="handleYhymInfo"
							>补全一房一码信息</el-button
						>
					</div>
					<div
						v-if="
							showYhymInfo && customerId !== '1535072605621841922'
						"
						class="table-more-btn"
					>
						<el-button
							class="diy-button--other"
							size="small"
							type="text"
							:loading="xcxmLoading"
							@click="createBatchNeiQrUrl"
							>补全小程序小区码</el-button
						>
					</div> -->
                    <div v-if="displayedBaobiaoBtn" class="table-more-btn">
                        <el-button size="small" type="text" class="diy-button--other" @click="reportForm">智能填报</el-button>
                    </div>
                    <!-- <div
						v-if="agencyObj.level == 'community'"
						class="table-more-btn"
					>
						<el-button
							class="diy-button--other"
							size="small"
							type="text"
							@click="handleDownQr(agencyObj, 'community')"
							>社区二维码</el-button
						>
					</div> -->
                    <el-button size="small" style="float: right" class="diy-button--white" slot="reference">更多
                        <i class="el-icon-arrow-down el-icon--right"></i></el-button>
                </el-popover>
            </div>
        </div>

        <div class="m-table-item">
            <el-table ref="ref_table" :data="tableData" border :height="tableHeight" v-loading="tableLoading"
                style="width: 100%" :show-overflow-tooltip="true" @select-all="selectAll"
                @selection-change="selectionChange">
                <el-table-column type="selection" :selectable="checkSelect" width="55">
                </el-table-column>
                <el-table-column prop="neighborHoodName" label="小区名称" header-align="left" align="left" min-width="100">
                    <template slot-scope="scope">
                        <a class="name-a" @click="handleToNextLevel(scope.row)">
                            {{ scope.row.neighborHoodName }}
                        </a>
                    </template>
                </el-table-column>
                <el-table-column prop="agencyName" label="所属组织" header-align="left" align="left" min-width="100">
                </el-table-column>
                <el-table-column prop="gridName" label="所属网格" header-align="left" align="left" min-width="120">
                </el-table-column>
                <!-- <el-table-column prop="总单元数"
                         label="所属网格"
                         min-width="80">
        </el-table-column>
        <el-table-column prop="总户数"
                         label="所属网格"
                         min-width="80">
        </el-table-column> -->
                <el-table-column prop="address" label="详细地址" header-align="left" align="left" min-width="180">
                </el-table-column>

                <el-table-column label="操作" fixed="right" width="220" header-align="center" align="center" class="operate">
                    <template slot-scope="scope">
                        <el-button type="text" class="div-table-button--blue" size="small"
                            @click="handleDetail(scope.row)">查看</el-button>
                        <!-- <el-button v-if="scope.row.showBtn"
                       type="text"
                       class="div-table-button--blue"
                       size="small"
                       @click="handleEdit(scope.row)">编辑</el-button>

            <el-button v-if="scope.row.showBtn"
                       type="text"
                       class="div-table-button--blue"
                       size="small"
                       @click="handleDelete(scope.row)">删除</el-button> -->
                        <el-button type="text" class="div-table-button--blue" size="small"
                            @click="handleEdit(scope.row)">编辑</el-button>

                        <el-button type="text" class="div-table-button--blue" size="small"
                            @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div>
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page.sync="pageNo" :page-sizes="[20, 50, 100, 200]" :page-size="pageSize"
                    layout="sizes, prev, pager, next, total" :total="total">
                </el-pagination>
            </div>
        </div>
        <!-- 详情弹出框 -->
        <el-dialog :visible.sync="detailShow" :close-on-click-modal="false" :close-on-press-escape="false" :title="'小区详情'"
            width="920px" top="5vh" class="dialog-h" @closed="detailFormCancle">
            <community-detail ref="ref_form_detail" @diaDetailClose="detailFormCancle"></community-detail>
        </el-dialog>

        <!-- 修改弹出框 -->
        <el-dialog :visible.sync="formShow" v-if="formShow" :close-on-click-modal="false" :close-on-press-escape="false"
            :title="formTitle" width="670px" top="5vh" class="dialog-h" @closed="diaClose">
            <community-form ref="ref_form" @dialogCancle="addFormCancle" @dialogOk="addFormOk"></community-form>
        </el-dialog>

        <!-- <el-dialog title="导出"
               :visible.sync="dialogVisible"
               width="30%"
               :before-close="handleClose">
      <div>
        <el-button class="diy-button--reset"
                   size="small"
                   @click="handleExport">导出小区数据</el-button>
        <el-button class="diy-button--export"
                   size="small"
                   :disabled="yihuyidangDisabled"
                   @click="handleExportYihuyidang()">导出一户一档</el-button>
        <el-button class="diy-button--qrcode"
                   size="small"
                   :disabled="yihuyimaDisabled"
                   :loading="exportBtn"
                   @click="handleExportYihuyima()">导出一房一码</el-button>
      </div>

    </el-dialog> -->

        <el-dialog :visible.sync="diyDialog" :close-on-click-modal="false" :close-on-press-escape="false" width="1150px"
            title="导出模板" top="5vh" class="dialog-h">
            <community-export-info v-if="diyDialog" ref="ref_diy" :list="exportList" :search="{
                formCode: 'community_info',
                pageNo: pageNo,
                pageSize: pageSize,
                conditions: queryConditions
            }" :orgId="treeObj.id" @close="handleDiyClose"></community-export-info>
        </el-dialog>

        <baobiao ref="baobiao" />
    </div>
</template>

<script>
import CommunityForm from "./communityForm";
import CommunityDetail from "./communityDetail";
import communityExportInfo from "./communityExportInfo.vue";

import { requestPost } from "@/js/dai/request";
import { mapGetters } from "vuex";
import { Loading } from "element-ui"; // 引入Loading服务
import axios from "axios";
import baobiao from "@/views/modules/cpts/baobiao";
import util from "@/js/util";

let loading; // 加载动画

export default {
    props: {
        staffAgencyId: {
            type: String,
            default: "",
        },
        ownerName: {
            type: String,
            default: "",
        },
        ownerPhone: {
            type: String,
            default: "",
        },
        rentFlag: {
            type: String,
            default: "",
        },
        purpose: {
            type: String,
            default: "",
        },
        remark: {
            type: String,
            default: "",
        },
        updateStartDate: {
            type: String,
            default: "",
        },
        updateEndDate: {
            type: String,
            default: "",
        },
    },

    data() {
        return {
            searchHeight: 190, //搜索栏高度
            // tableHeight: 0,
            importBuildingLoading: false,
            importRoomLoading: false,
            importCommunityLoading: false,
            total: 0,
            pageSize:window.localStorage.getItem('pageSize') || 20,
            pageNo: 0,
            tableLoading: true,

            showImportBtn: false, //是否显示操作按钮，根据登录人所属组织判断
            roleList: [], //角色列表
            showYhymInfo: false, // 是否显示补全一房一码信息按钮
            yhymLoading: false,
            xcxmLoading: false,

            agencyObj: {}, //树所选的组织对象
            treeObj: {},
            tableData: [],
            validTableDataNum: 0, //有效的数据数量，即有权限操作的数据数量
            selection: [],
            showDeletBtn: false,

            //form相关
            formShow: false,
            formTitle: "新增小区",

            detailShow: false,

            files: "",
            fileName: "",
            uploadUlr:
                window.SITE_CONFIG["apiURL"] + "/gov/org/neighborhood/import",
            yihuyidangDisabled: false,
            yihuyimaDisabled: false,
            exportBtn: false,

            displayedBaobiaoBtn: false,
            customerId: "", //烟台的客户id :  1535072605621841922

            //导出
            exportList: [],
            diyDialog: false,


            queryConditions: [],

            uploadType:null
        };
    },

    computed: {
        tableHeight() {
            console.log(this.searchHeight);
            let height = this.searchHeight + 270;
            return this.$store.state.inIframe
                ? this.clientHeight - height + this.iframeHeight
                : this.clientHeight - height;
        },

        ...mapGetters(["clientHeight", "iframeHeight"]),
    },
    watch: {
        selection(val) {
            if (val.length > 0) {
                this.showDeletBtn = true;
            } else {
                this.showDeletBtn = false;
            }
        },
        "$store.state.sidebarFold": {
            handler(newVal, oldVal) {
                if (newVal) {
                    //收起
                    this.searchHeight = 155;
                } else {
                    this.searchHeight = 190;
                }
            },
            deep: true,
        },
    },

    components: {
        baobiao,
        CommunityForm,
        CommunityDetail,
        communityExportInfo,
    },

    activated() { },

    async mounted() {
        this.customerId = localStorage.getItem("customerId");
        this.displayedBaobiaoBtn = await this.$refs.baobiao.existsTemplate({
            elseParams: {
                categoryKeys: ['house_info'], categoryKey: 'house_info',
            }
        });
        this.getQueryConditions();
    
    },

    methods: {
        async getQueryConditions() {
            let params = {
                formCode: "community_info",
                customerId: this.$store.state.user.customerId,
            };

            const { data } = await this.$http.post(
                "/oper/customize/icform/queryItems",
                params
            );

            if (data.code === 0) {
                this.queryConditions = data.data.map((item) => {
                    return {
                        ...item,
                        humpName: util.capitalToHump(item.columnName),
                    };
                });
                console.log(this.queryConditions);
            } else {
                this.$message.error(data.msg);
            }
        },

        reportForm() {
            let paramMap = {
                pageSize: this.pageSize,
                pageNo: this.pageNo,
                level: this.agencyObj.level,
                id: this.agencyObj.id,
                ownerName: this.ownerName,
                ownerPhone: this.ownerPhone,
                rentFlag: this.rentFlag,
                purpose: this.purpose,
                remark: this.remark,
                sortType: this.sortType,
                updateStartDate: this.updateStartDate,
                updateEndDate: this.updateEndDate,
            };
            
            this.$refs.baobiao.init({
                elseParams: {
                    categoryKeys: ["house_info"],
                    categoryKey: "house_info",
                    paramMap,
                },
            });
        },
        async loadTable(fromTree, treeObj) {
            this.treeObj = { ...treeObj }
            // 是否显示补全一房一码信息按钮
            this.roleList = localStorage.getItem("roleList");
            if (
                this.roleList.indexOf("root_manager") > -1 ||
                this.roleList.indexOf("manager") > -1
            ) {
                this.showYhymInfo = true;
            } else {
                this.showYhymInfo = false;
            }
            this.tableLoading = true;
            if (fromTree) {
                this.agencyObj = treeObj;
                if (this.agencyObj.level === "community") {
                    //只有社区和网格显示操作按钮
                    if (this.agencyObj.id === this.staffAgencyId) {
                        //如果所选树的组织id和登录人员id相同，有权限
                        this.showImportBtn = true;
                    } else {
                        this.showImportBtn = false;
                    }
                } else if (this.agencyObj.level === "grid") {
                    //网格下
                    if (this.agencyObj.pid === this.staffAgencyId) {
                        //如果所选树的父级组织id和登录人员id相同，有权限
                        this.showImportBtn = true;
                    } else {
                        this.showImportBtn = false;
                    }
                } else {
                    this.showImportBtn = false;
                }
            }

            const url = "/actual/base/communityQuarters/listQuarters";

            let params = {
                pageSize: this.pageSize,
                pageNo: this.pageNo,

                level: this.agencyObj.level,
                id: this.agencyObj.id,
            };

            const { data, code, msg } = await requestPost(url, params);

            if (code === 0) {
                this.validTableDataNum = 0;
                this.total = data.total;
                data.list.forEach((item) => {
                    if (item.agencyId === this.staffAgencyId) {
                        // item.showBtn = true;
                        this.validTableDataNum++;
                    } else {
                        // item.showBtn = false;
                    }
                });
                this.tableData = data.list;
            } else {
                this.$message.error(msg);
            }
            this.tableLoading = false;
        },

        checkSelect(row, index) {
            let isChecked = true;
            // if (row.showBtn) {
            //   // 判断里面是否存在某个参数
            //   isChecked = true;
            // } else {
            //   isChecked = false;
            // }
            return isChecked;
        },

        diaClose() {
            this.$refs.ref_form.resetData();
            this.formShow = false;
        },

        async handleDetail(row) {
            // this.formTitle = '小区详情'
            // this.formShow = true
            // const _data = await this.detail(row)
            // this.$nextTick(() => {
            //   this.$refs.ref_form.initForm('detail', _data, this.agencyObj)
            // })

            this.detailShow = true;

            const _data = await this.detail(row);
            this.$nextTick(() => {
                this.$refs.ref_form_detail.initForm(_data);
            });
        },

        handleAdd() {
            this.formTitle = "新增小区";
            this.formShow = true;
            this.$nextTick(() => {
                this.$refs.ref_form.initForm("add", null, this.agencyObj);
            });
        },
        async detail(row) {
            const url =
                "/actual/base/communityQuarters/getQuartersDetail/" +
                row.neighborHoodId;

            const { data, code, msg } = await requestPost(url);

            if (code === 0) {
                return data;
            } else {
                this.$message.error(msg);
            }
        },
        // 补全一房一码点击事件
        async handleYhymInfo() {
            this.yhymLoading = true;
            const url = "/gov/org/house/createBatchHouseCodeAndUrl";

            let params = {};

            const { data, code, msg } = await requestPost(url, params);

            if (code === 0) {
                this.yhymLoading = false;
                this.$message({
                    type: "success",
                    message: "批量生成成功",
                });
            } else if (code > 8000) {
                this.yhymLoading = false;
                this.$message({
                    showClose: true,
                    message: msg,
                    duration: 0,
                });
            } else {
                this.yhymLoading = false;
                this.$message.error(msg);
            }
        },
        // 补全小程序一户一码
        async createBatchNeiQrUrl() {
            this.xcxmLoading = true;
            const url = "/gov/org/neighborhood/createBatchNeiQrUrl";

            let params = {};

            const { data, code, msg } = await requestPost(url, params);

            if (code === 0) {
                this.xcxmLoading = false;
                this.$message({
                    type: "success",
                    message: "批量生成成功",
                });
            } else if (code > 8000) {
                this.xcxmLoading = false;
                this.$message({
                    showClose: true,
                    message: msg,
                    duration: 0,
                });
            } else {
                this.xcxmLoading = false;
                this.$message.error(msg);
            }
        },
        async handleEdit(row) {
            this.formTitle = "修改小区";
            this.formShow = true;
            const _data = await this.detail(row);
            this.$nextTick(() => {
                this.$refs.ref_form.initForm("edit", _data, this.agencyObj);
            });
        },

        handleToNextLevel(row) {
            this.$emit("toNextLevel", row, "community");
        },

        addFormCancle() {
            this.formShow = false;
        },
        detailFormCancle() {
            this.$refs.ref_form_detail.diaDestroy();
            this.detailShow = false;
        },
        addFormOk() {
            this.formShow = false;
            this.loadTable();
            this.$emit("refreshTree");
        },


        selectAll(selection) {
            this.selection = selection;
        },
        selectionChange(selection) {
            this.selection = selection;
        },

        async handleDelete(row) {
            this.$confirm("确认删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    let ids = [row.neighborHoodId];

                    //第一次删除，非强制删除
                    this.deleteCommunity(ids, false);
                })
                .catch((err) => {
                    if (err == "cancel") {

                    }
                });
        },
        deleteBatch() {
            if (this.selection.length > 0) {
                this.$confirm("确认删除选择的小区?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {

                        let ids = [];
                        console.log(this.selection);
                        this.selection.forEach((element) => {
                            ids.push(element.neighborHoodId);
                        });

                        //第一次删除，非强制删除
                        this.deleteCommunity(ids, false);
                    })
                    .catch((err) => {
                        if (err == "cancel") {
                            // this.$message({
                            //   type: "info",
                            //   message: "已取消删除"
                            // });
                        }
                    });
            } else {
                this.$message.warning("请先选择要删除的小区");
            }
        },

        async deleteCommunity(ids, forceDelete) {
            const url = "/actual/base/communityHouse/deleteCommunityInfoByIds";
            let params = {
                forceDelete: forceDelete,
                type: 'neighborHood',
                ids: ids
            }

            const { data, code, msg } = await requestPost(url, params);

            if (code === 0) {
                this.$message({
                    type: "success",
                    message: "删除成功",
                });
                this.$emit("refreshTree");
                this.loadTable();

            } else if (code > 8000) {

                this.$confirm(msg, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {

                        this.deleteCommunity(ids, true);
                    })
                    .catch((err) => {
                        if (err == "cancel") {

                        }
                    });


            } else {
                this.$message.error(msg);
            }
        },

        async handleDownQr(row, type) {
            let title = row.label + "二维码.png";
            // const url = window.SITE_CONFIG['apiURL'] + `/gov/org/icneighborhood/createQrCode/${row.neighborHoodId}`
            const url = "/gov/org/agency/create-qrcode";
            const _id = type == "community" ? row.id : row.neighborHoodId;
            const params = {
                id: _id,
                type,
            };
            await axios({
                method: "POST",
                url: window.SITE_CONFIG["apiURL"] + url,
                data: params,
                responseType: "blob",
            }).then((res) => {
                console.log("res----1r", res);
                if (res.data) {
                    // let fileName = window.decodeURI(res.headers["content-disposition"].split(";")[1].split("=")[1])
                    // console.log('filename', fileName)
                    this.download(res.data, title); //释放掉blob对象
                } else this.$message.error("下载失败");
                // this.download(res.data, '1.png')
            });
        },
        // 导出按钮点击事件
        async handleExportOpen() {
            await this.getExportList();
        },
        async getExportList(type) {
            const url = "/oper/customize/icformitemgroup/list";
            let params = {
                formCode: "community_info",
            };

            const { data, code, msg } = await requestPost(url, params);

            if (code === 0) {
                data.forEach((item) => {
                    (async (id) => {
                        // item.queryItemList = await this.getExportChildList(id)
                        item.queryItemList = [];
                    })(item.id);
                });
                this.exportList = [...data];
                this.$nextTick(() => {
                    this.diyDialog = true;
                });
                console.log("获取详情成功getExportList----", this.exportList);
            } else {
                this.$message.error(msg);
            }
        },
        //导出表格 以前是导出 现在改成导出房屋数据
        async handleExport() {
            let title = this.agencyObj.label;
            title = title + "—小区列表";

            const url = "/gov/org/neighborhood/exportneighborhoodinfo";
            let params = {
                level: this.agencyObj.level,
                id: this.agencyObj.id,
            };

            app.ajax.exportFilePost(
                url,
                params,
                (data, rspMsg) => {
                    this.download(data, title + ".xls");
                },
                (rspMsg, data) => {
                    this.$message.error(rspMsg);
                }
            );
        },
        handleDiyClose() {
            this.diyDialog = false;
        },
        handleClose(done) {
            this.diyDialog = false;
        },

        // 下载文件
        download(data, downFileName) {
            if (!data) {
                this.endLoading()
                return;
            }
            var csvData = new Blob([data]);

            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveOrOpenBlob(csvData, downFileName);
            }
            // for Non-IE (chrome, firefox etc.)
            else {
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                var url = window.URL.createObjectURL(csvData);
                a.href = url;
                a.download = downFileName;
                a.click();
                a.remove();
                window.URL.revokeObjectURL(url);
                this.endLoading()
            }
        },

        handleExportModule(type) {
            let title = "";
            let url = "/actual/base/intelligentImportData/autoGenerateExcelModule";
            let params = {
                importCategory:''
            };
            if (type === "building") {
                title = "楼栋导入模板";
                params.importCategory = 'BUILDING_INFO'
            } else if (type === "room") {
                title = "房屋导入模板";
                params.importCategory = 'HOUSE_INFO'
            }
            app.ajax.exportFilePost(
                url,
                params,
                (data, rspMsg) => {
                    this.download(data, title + ".xls");
                },
                (rspMsg, data) => {
                    this.$message.error(rspMsg);
                }
            );
        },
        
        //导入电子门牌信息
        
        handleExportIDCard() {
            let title = this.agencyObj.label;
            title = title + "电子门牌信息";
            let url = "/actual/base/communityHouse/downloadZip";
            console.log(this.agencyObj)
            this.startLoading('正在生成，请稍候...')
            let params = {
                pageSize:this.pageSize,
                pageNo:this.pageNo,
                level:this.agencyObj.level ,              
                id:this.agencyObj.id,
                ownerName: this.ownerName,
                ownerPhone: this.ownerPhone,
                rentFlag: this.rentFlag,
                purpose: this.purpose,
                remark: this.remark,
                updateStartDate: this.updateStartDate,
                updateEndDate: this.updateEndDate,
                sortType:"asc",
                neighborHoodId:"",
                buildingId:"",
                buildingUnitId:"",
                houseId:"",
            };
            // if (this.agencyObj.level === "grid") {
            //     params.gridId = this.agencyObj.id;
            //     params.agencyId = "";
            // } else {
            //     params.gridId = "";
            //     params.agencyId = this.agencyObj.id;
            // }

            app.ajax.exportFilePost(
                url,
                params,
                (data, rspMsg) => {
                    console.log(data)
                    this.download(data, title + ".zip");
                },
                (rspMsg, data) => {
                    this.$message.error(rspMsg);
                }
            );
        },
        //导出一户一档
        handleExportYihuyidang() {
            this.yihuyidangDisabled = true;
            let title = this.agencyObj.label;
            title = title + "-一户一档";
            let url = "/gov/org/house/exportHouseUser";

            let params = {
                agencyId: "",
                gridId: "",
                ownerName: this.ownerName,
                ownerPhone: this.ownerPhone,
                rentFlag: this.rentFlag,
                purpose: this.purpose,
                remark: this.remark,
                updateStartDate: this.updateStartDate,
                updateEndDate: this.updateEndDate,
            };

            if (this.agencyObj.level === "grid") {
                params.gridId = this.agencyObj.id;
                params.agencyId = "";
            } else {
                params.gridId = "";
                params.agencyId = this.agencyObj.id;
            }

            app.ajax.exportFilePost(
                url,
                params,
                (data, rspMsg) => {
                    this.download(data, title + ".xls");
                    this.yihuyidangDisabled = false;
                },
                (rspMsg, data) => {
                    this.yihuyidangDisabled = false;
                    this.$message.error(rspMsg);
                }
            );
        },

        // 导出一房一码

        handleExportYihuyima() {
            this.exportBtn = true;
            this.yihuyimaDisabled = true;
            let title = this.agencyObj.label;
            title = title + "-一房一码";
            let url = "/gov/org/house/downloadZip";

            let params = {
                level: this.agencyObj.level,
                id: this.agencyObj.id,
            };

            app.ajax.exportFilePost(
                url,
                params,
                (data, rspMsg) => {
                    this.download(data, title + ".Zip");
                    this.exportBtn = false;
                    this.yihuyimaDisabled = false;
                },
                (rspMsg, data) => {
                    this.exportBtn = false;
                    this.yihuyimaDisabled = false;
                    this.$message.error(rspMsg);
                }
            );
        },

        // 上传文件之前的钩子
        beforeUpload(file, type) {
            this.files = file;

            const isText = file.type === "application/vnd.ms-excel";
            const isTextComputer =
                file.type ===
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            if (!isText && !isTextComputer) {
                this.$message.error("请选择正确格式的文件");
                this.files = null;
                this.fileName = "";
                return false;
            } else {
                this.fileName = file.name;
                return true;
            }
        },
        // 上传文件个数超过定义的数量
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，请删除后继续上传`);
        },

        async uploadFile(type) {
            this.uploadType = type;
            if (this.fileName == "") {
                this.$message.warning("请选择要上传的文件！");
                return false;
            }

            this.$message({
                showClose: true,
                dangerouslyUseHTMLString: true,
                message: "导入中，请到系统管理-<a id='clickA' style='cursor: pointer;'>导入记录</a>中查看进度",
                duration: 3000,
            });
            let than = this
            document.getElementById('clickA').addEventListener('click', function () {
                than.$router.replace('/main/importRecord-index');
            })
            //清空上传列表
            let url = "/actual/base/intelligentImportData/uploadFile";

            let fileFormData = new FormData();
            fileFormData.append("file", this.files); //filename是键，file是值，就是要传的文件，test.zip是要传的文件名
            fileFormData.append("orgId", this.agencyObj.id); //filename是键，file是值，就是要传的文件，test.zip是要传的文件名
            fileFormData.append(
                "orgType",
                this.agencyObj.level === "grid" ? "grid" : "agency"
            ); //filename是键，file是值，就是要传的文件，test.zip是要传的文件名

            if (type === "community") {
                this.importCommunityLoading = true;
                this.$refs["upload_community"].clearFiles();
            }  else if (type === "room") {
                this.$refs["upload_room"].clearFiles();
                this.importRoomLoading = true;
            }

            window.app.ajax.post2(
                url,
                fileFormData,
                (data, rspMsg) => {
                    if (data.code === 0 && data.msg == "success") {
                        // this.$message.success('导入成功')
                        this.checkExtractExcelHead(data.data.fileName,data.data.url,type === 'community'?'BUILDING_INFO':'HOUSE_INFO')
                    } else {
                        // this.$message({
                        //   showClose: true,
                        //   message: rspMsg,
                        //   duration: 0,
                        //   type: "error"
                        // })
                        // this.$message.error(rspMsg)
                    }
                    this.$emit("refreshTree");
                    this.loadTable();
                    // this.showMessage(rspMsg)
                    if (type === "community") {
                        this.importCommunityLoading = false;
                    } else if (type === "room") {
                        this.importRoomLoading = false;
                    }
                },
                (rspMsg, data) => {
                    if (type === "community") {
                        this.importCommunityLoading = false;
                    }  else if (type === "room") {
                        this.importRoomLoading = false;
                    }
                    // this.$message.error(rspMsg)
                },
                { headers: { "Content-Type": "multipart/form-data" } }
            );
        },
        async checkExtractExcelHead(originFileName,originalFilePath,importCategory) {
            const url = "/actual/base/intelligentImportData/extractExcelHead";
            let params = {
                originFileName,
                originalFilePath,
                importCategory,
            };
            const { data, code, msg } = await requestPost(url, params);
            if (code === 0) {
                this.fileCode = data.fileCode;
                this.saveImportResiHouseExcel(originFileName)
            } else if (code >= 8000) {
                this.$message.err(msg);
                this.dataListLoading = false;
            }
        },
        async saveImportResiHouseExcel(originFileName) {
        const { fileCode ,uploadType} = this;
        const formData = new FormData();
        let json = uploadType === 'community'?'{"所属社区":"所属社区","所属网格":"所属网格","所属小区":"所属小区","所属楼栋":"所属楼栋","所属单元":"所属单元","门牌号":"门牌号","姓名":"居民姓名","联系电话":"联系电话","证件号":"证件号","低保类别":"低保类型","因病":"因病","因残":"因残","低收入":"低收入"}':'{"所属网格":"所属网格","所属小区":"所属小区","所属楼栋":"所属楼栋","所属单元":"所属单元","门牌号":"门牌号","房屋类型":"房屋类型","居住用途":"居住用途","房屋状态":"房屋状态","房主姓名":"房主姓名","房主电话":"房主电话","房主身份证":"房主身份证","党员中心户":"党员中心户","五好家庭":"五好家庭","模范之家":"模范之家","功臣之家":"功臣之家","光荣之家":"光荣之家"}'
        formData.append("columnMateJson", json);
        formData.append("fileCode", fileCode);
        formData.append("taskName", originFileName);
        await this.$http
            .post(
            "/actual/base/intelligentImportData/importResiHouseExcel",
            formData
            )
            .then((res) => {
            
            })
            .catch((err) => {
      
            });
    },
        showMessage(msg) {
            this.$alert(msg, "操作结果", {
                confirmButtonText: "关闭",
                callback: (action) => {
                    this.$emit("refreshTree");
                    this.loadTable();
                },
            });
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.pageNo = 1;
            this.loadTable(true, this.treeObj);
        },
        handleCurrentChange(val) {
            this.pageNo = val;
            this.loadTable(true, this.treeObj);
        },

        // 开启加载动画
        startLoading(message) {
            loading = Loading.service({
                lock: true, // 是否锁定
                text:message || "正在加载……", // 加载中需要显示的文字
                background: "rgba(0,0,0,.7)", // 背景颜色
            });
        },
        // 结束加载动画
        endLoading() {
            // clearTimeout(timer);
            if (loading) {
                loading.close();
            }
        },
    },
};
</script>
<style lang="scss" scoped>
@import "@/assets/scss/modules/visual/communityManage.scss";
@import "@/assets/scss/modules/management/list-main.scss";
</style>

<style>
.el-message.is-closable .el-message__content {
    line-height: 20px;
}

::v-deep .el-dialog__body {
    padding: 0;
}
</style>
