<template>
    <div class="JNPF-common-layout">
        <div class="JNPF-common-layout-center">
            <el-row class="JNPF-common-search-box" :gutter="16">
                <el-form @submit.native.prevent>
                    <el-col :span="6">
                        <el-form-item label="机房名称">
                            <el-input v-model="query.computerRoom" placeholder="请输入机房名称" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search"
                                @click="search()">查询</el-button>
                            <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div class="JNPF-common-layout-main JNPF-flex-main">
                <div class="JNPF-common-head">
                    <div>
                        <el-button type="primary" icon="icon-ym icon-ym-btn-add"
                            @click="addOrUpdateHandle()">新增
                        </el-button>
                        <el-button type="info" icon="icon-export" @click="exportQR()">导出二维码
                        </el-button>
                    </div>
                    <div class="JNPF-common-head-right">
                        <el-tooltip effect="dark" :content="$t('common.refresh')" placement="top">
                            <el-link icon="icon-ym icon-ym-Refresh JNPF-common-head-icon"
                                :underline="false" @click="initData()" />
                        </el-tooltip>
                    </div>
                </div>
                <JNPF-table v-loading="listLoading" :data="list" @sort-change='handleTableSort'
                    :header-cell-class-name="handleHeaderClass" :has-c="hasBatchBtn"
                    :span-method="arraySpanMethod" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center">
                    </el-table-column>
                    <el-table-column prop="computerRoom" label="机房名称" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="code" label="编码" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="url" label="二维码">
                        <template slot-scope="scope" sortable>
                            <el-image style="width: 100px; height: 100px"
                                :src="minioPath+scope.row.url"
                                :preview-src-list="[minioPath+scope.row.url]">
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="150">
                        <template slot-scope="scope">
                            <el-button type="text" @click="addOrUpdateHandle(scope.row)">编辑
                            </el-button>
                            <el-button type="text" class="JNPF-table-delBtn"
                                @click="handleDel(scope.row.id)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </JNPF-table>
                <pagination :total="total" :page.sync="listQuery.currentPage"
                    :limit.sync="listQuery.pageSize" @pagination="initData" />
            </div>
        </div>
        <JNPF-Form v-if="formVisible" ref="JNPFForm" @refresh="refresh" />
    </div>
</template>

<script>
import request from '@/utils/request'
import { mapGetters } from "vuex";
import JNPFForm from './form'
import { getDataInterfaceRes } from '@/api/systemData/dataInterface'
import columnList from './columnList'
import superQueryJson from './superQueryJson'
import { noGroupList } from '@/components/Generator/generator/comConfig'
import { minioPath } from '@/utils/apiUrl'


export default {
    components: {
        JNPFForm,
    },
    data() {
        return {
            minioPath: minioPath,
            keyword: '',
            expandsTree: true,
            refreshTree: true,
            toFormDetailVisible: false,
            hasBatchBtn: false,
            expandObj: {},
            columnOptions: [],
            mergeList: [],
            exportList: [],
            columnList,

            superQueryJson,
            uploadBoxVisible: false,
            detailVisible: false,
            query: {
                computerRoom: undefined,
                createTime: undefined,
            },
            defListQuery: {
                sort: 'desc',
                sidx: '',
            },
            //排序默认值
            defaultSortConfig: [],
            treeProps: {
                children: 'children',
                label: 'fullName',
                value: 'id',
                isLeaf: 'isLeaf'
            },
            list: [],
            listLoading: true,
            multipleSelection: [],
            total: 0,
            queryData: {},
            listQuery: {
                superQueryJson: '',
                currentPage: 1,
                pageSize: 20,
                sort: "",
                sidx: "",
            },
            //多列排序
            ordersList: [],
            formVisible: false,
            flowVisible: false,
            flowListVisible: false,
            flowList: [],
            exportBoxVisible: false,
            interfaceRes: {
            },
            //掩码配置
            maskConfig: {
                rqCodeId: { "prefixType": 1, "useUnrealMask": false, "maskType": 1, "unrealMaskLength": 1, "prefixLimit": 0, "suffixLimit": 0, "filler": "*", "prefixSpecifyChar": "", "suffixType": 1, "ignoreChar": "", "suffixSpecifyChar": "" },
            },
            selectedData: null,
        }
    },
    computed: {
        ...mapGetters(['userInfo']),
        menuId() {
            return this.$route.meta.modelId || ''
        }
    },
    created() {
        this.getColumnList(),
            this.initSearchDataAndListData()
        this.queryData = JSON.parse(JSON.stringify(this.query))
        this.getHasBatchBtn();
        //排序默认值
        this.setDefaultQuery(this.defaultSortConfig);
    },
    methods: {
        exportQR() {
            if (this.selectedData && this.selectedData.length) {
                this.listLoading = true;
                let ids = []
                this.selectedData.forEach(item => {
                    ids.push(item.id)
                })

                request({
                    url: `/api/QRCode/QRCode/export`,
                    method: 'post',
                    header: {
                        'content-type': 'application/json',
                    },
                    responseType: 'blob',
                    data: ids
                }).then(res => {
                    console.log(res)
                    if (res.code !== 400) {
                        const url = window.URL.createObjectURL(res);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = '二维码导出.docx';
                        a.click();

                        this.$message({
                            message: '导出成功',
                            type: 'success',
                            duration: 1000,
                        })
                    } else {
                        this.$message({
                            message: '导出失败',
                            type: 'warning',
                            duration: 1000,
                        })
                    }
                    this.listLoading = false
                })
            } else {
                this.$message.warning('请选择至少一个机房二维码')
            }
        },
        handleSelectionChange(val) {
            this.selectedData = val;
        },
        getHasBatchBtn() {
            let btnsList = []
            this.hasBatchBtn = btnsList.some(o => ['batchRemove', 'batchPrint', 'download'].includes(o))
        },

        treeRefresh() {
            this.keyword = ''
            this.treeActiveId = ''
            this.leftTreeActiveInfo = {}
            this.$refs.treeBox.setCurrentKey(null)
            this.getTreeView()
        },
        toggleTreeExpand(expands) {
            this.refreshTree = false
            this.expandsTree = expands
            this.$nextTick(() => {
                this.refreshTree = true
                this.$nextTick(() => {
                    this.$refs.treeBox.setCurrentKey(null)
                })
            })
        },
        filterNode(value, data) {
            if (!value) return true;
            return data[this.treeProps.label].indexOf(value) !== -1;
        },
        loadNode(node, resolve) {
            const nodeData = node.data
            const config = {
                treeInterfaceId: "",
                treeTemplateJson: []
            }
            if (config.treeInterfaceId) {
                //这里是为了拿到参数中关联的字段的值，后端自行拿
                if (config.treeTemplateJson && config.treeTemplateJson.length) {
                    for (let i = 0; i < config.treeTemplateJson.length; i++) {
                        const element = config.treeTemplateJson[i];
                        element.defaultValue = nodeData[element.relationField] || ''
                    }
                }
                //参数
                let query = {
                    paramList: config.treeTemplateJson || [],
                }
                //接口
                getDataInterfaceRes(config.treeInterfaceId, query).then(res => {
                    let data = res.data
                    if (Array.isArray(data)) {
                        resolve(data);
                    } else {
                        resolve([]);
                    }
                })
            }
        },
        getColumnList() {
            // 没有开启权限
            this.columnOptions = this.transformColumnList(this.columnList)
        },
        transformColumnList(columnList) {
            let list = []
            for (let i = 0; i < columnList.length; i++) {
                const e = columnList[i];
                if (!e.prop.includes('-')) {
                    list.push(e)
                } else {
                    let prop = e.prop.split('-')[0]
                    let label = e.label.split('-')[0]
                    let vModel = e.prop.split('-')[1]
                    let newItem = {
                        align: "center",
                        jnpfKey: "table",
                        prop,
                        label,
                        children: []
                    }
                    e.vModel = vModel
                    if (!this.expandObj.hasOwnProperty(`${prop}Expand`)) this.$set(this.expandObj, `${prop}Expand`, false)
                    if (!list.some(o => o.prop === prop)) list.push(newItem)
                    for (let i = 0; i < list.length; i++) {
                        if (list[i].prop === prop) {
                            list[i].children.push(e)
                            break
                        }
                    }
                }
            }
            this.getMergeList(list)
            this.getExportList(list)
            return list
        },
        arraySpanMethod({ column }) {
            for (let i = 0; i < this.mergeList.length; i++) {
                if (column.property == this.mergeList[i].prop) {
                    return [this.mergeList[i].rowspan, this.mergeList[i].colspan]
                }
            }
        },
        getMergeList(list) {
            let newList = JSON.parse(JSON.stringify(list))
            newList.forEach(item => {
                if (item.children && item.children.length) {
                    let child = {
                        prop: item.prop + '-child-first'
                    }
                    item.children.unshift(child)
                }
            })
            newList.forEach(item => {
                if (item.children && item.children.length) {
                    item.children.forEach((child, index) => {
                        if (index == 0) {
                            this.mergeList.push({
                                prop: child.prop,
                                rowspan: 1,
                                colspan: item.children.length
                            })
                        } else {
                            this.mergeList.push({
                                prop: child.prop,
                                rowspan: 0,
                                colspan: 0
                            })
                        }
                    })
                } else {
                    this.mergeList.push({
                        prop: item.prop,
                        rowspan: 1,
                        colspan: 1
                    })
                }
            })
        },
        getExportList(list) {
            let exportList = []
            for (let i = 0; i < list.length; i++) {
                if (list[i].jnpfKey === 'table') {
                    for (let j = 0; j < list[i].children.length; j++) {
                        exportList.push(list[i].children[j])
                    }
                } else {
                    exportList.push(list[i])
                }
            }
            this.exportList = exportList.filter(o => !noGroupList.includes(o.__config__.jnpfKey))
        },

        sortChange({ column, prop, order }) {
            this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
            this.listQuery.sidx = !order ? '' : prop
            this.initData()
        },
        async initSearchDataAndListData() {
            await this.initSearchData()
            this.initData()
        },
        //初始化查询的默认数据
        async initSearchData() {
        },
        initData() {
            // this.queryData = JSON.parse(JSON.stringify(this.query))导致重置失效
            this.listLoading = true;
            let _query = {
                ...this.listQuery,
                ...this.query,
                ...this.defListQuery,
                keyword: this.keyword,
                dataType: 0,
                menuId: this.menuId,
                moduleId: '582544950567115333',
                type: 1,
            };
            request({
                url: `/api/QRCode/QRCode/getList`,
                method: 'post',
                data: _query
            }).then(res => {
                var _list = [];
                for (let i = 0; i < res.data.list.length; i++) {
                    let _data = res.data.list[i];
                    _list.push(_data)
                }
                this.list = _list.map(o => ({
                    ...o,
                    ...this.expandObj,
                }))
                this.total = res.data.pagination.total
                this.listLoading = false
            })
        },
        handleDel(id) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                type: 'warning'
            }).then(() => {
                request({
                    url: `/api/QRCode/QRCode/${id}`,
                    method: 'DELETE'
                }).then(res => {
                    this.$message({
                        type: 'success',
                        message: res.msg,
                        onClose: () => {
                            this.initData()
                        }
                    });
                })
            }).catch(() => {
            });
        },
        addOrUpdateHandle(row, isDetail) {
            let id = row ? row.id : ""
            this.formVisible = true
            if (!this.treeActiveId) {
                this.leftTreeActiveInfo = {}
            }
            this.$nextTick(() => {
                this.$refs.JNPFForm.init(id, isDetail, this.list, this.leftTreeActiveInfo)
            })
        },
        exportData() {
            this.exportBoxVisible = true
            this.$nextTick(() => {
                this.$refs.ExportBox.init(this.exportList, this.multipleSelection)
            })
        },
        download(data) {
            let query = { ...data, ...this.listQuery, ...this.query, menuId: this.menuId }
            request({
                url: `/api/QRCode/QRCode/Actions/Export`,
                method: 'post',
                data: query
            }).then(res => {
                if (!res.data.url) return
                this.jnpf.downloadFile(res.data.url)
                this.$refs.ExportBox.visible = false
                this.exportBoxVisible = false
            })
        },
        search() {
            this.listQuery.currentPage = 1
            this.listQuery.pageSize = 20
            this.initData()
        },
        refresh(isrRefresh) {
            this.formVisible = false
            if (isrRefresh) this.reset()
        },
        reset() {
            this.query = JSON.parse(JSON.stringify(this.queryData))
            this.search()
        },
        colseFlow(isrRefresh) {
            this.flowVisible = false
            if (isrRefresh) this.reset()
        },

        //以下排序相关方法
        setDefaultQuery(defaultSortList) {
            const defaultSortConfig = (defaultSortList || []).map(o =>
                (o.sort === 'desc' ? '-' : '') + o.field);
            this.defListQuery.sidx = defaultSortConfig.join(',')
        },
        handleHeaderClass({ column }) {
            column.order = column.multiOrder
        },
        handleTableSort({ column }) {
            if (column.sortable !== 'custom') return
            column.multiOrder = column.multiOrder === 'descending' ? 'ascending' : column.multiOrder ? '' : 'descending';
            this.handleOrderChange(column.property, column.multiOrder)
        },
        handleOrderChange(orderColumn, orderState) {
            let index = this.ordersList.findIndex(e => e.field === orderColumn);
            let sort = orderState === 'ascending' ? 'asc' : orderState === 'descending' ? 'desc' : '';
            if (index > -1) {
                this.ordersList[index].sort = orderState;
            } else {
                this.ordersList.push({ field: orderColumn, sort });
            }
            this.ordersList = this.ordersList.filter(e => e.sort);
            this.ordersList.length ? this.setDefaultQuery(this.ordersList) : this.setDefaultQuery(this.defaultSortConfig)
            this.initData()
        },
        //以上排序相关方法
    }
}
</script>
