<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.createBy" placeholder="请输入申请人" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <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="el-icon-upload2" @click="exportData()">导出
                        </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">
                    <el-table-column prop="createBy" label="申请人" align="left" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="accessThing" label="登记信息" align="left"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="qRCode.computerRoom" label="机房" align="left"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="auditBy" label="审核人" align="left" show-overflow-tooltip>
                        <template slot-scope="scope" sortable>
                            {{ scope.row.auditBy || '无数据' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="登记时间" align="left"
                        show-overflow-tooltip>
                        <template slot-scope="scope" sortable>
                            {{ getDate(scope.row.createTime, 'YY-MM-DD HH:mm:ss') }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="auditTime" label="审核时间" align="left"
                        show-overflow-tooltip>
                        <template slot-scope="scope" sortable>
                            {{ getDate(scope.row.auditTime, 'YY-MM-DD HH:mm:ss') }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="sign" label="签到次数" align="left" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="150">
                        <template slot-scope="scope">
                            <el-button type="text" @click="goDetail(scope.row)">详情
                            </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" />
        <Detail v-if="detailVisible" ref="Detail" @refresh="detailVisible=false" />
    </div>
</template>

<script>
import request from '@/utils/request'
import { mapGetters } from "vuex";
import JNPFForm from './form'
import Detail from './Detail'
import dayjs from 'dayjs'

export default {
    components: {
        JNPFForm,
        Detail,
    },
    data() {
        return {
            expandsTree: true,
            hasBatchBtn: false,
            expandObj: {},
            mergeList: [],

            detailVisible: false,
            query: {
                createBy: undefined,
                computerRoom: undefined,
            },
            defListQuery: {
                sort: 'desc',
                sidx: '',
            },
            //排序默认值
            defaultSortConfig: [],
            list: [],
            listLoading: true,
            total: 0,
            queryData: {},
            listQuery: {
                currentPage: 1,
                pageSize: 20,
                // audit: '1'
            },
            //多列排序
            ordersList: [],
            formVisible: false,
            flowVisible: false,
            flowList: [],
            exportBoxVisible: false,
            methodOptions: [],
            methodProps: { "label": "fullName", "value": "enCode" },
            interfaceRes: {
            },
        }
    },
    computed: {
        ...mapGetters(['userInfo']),
        menuId() {
            return this.$route.meta.modelId || ''
        }
    },
    created() {
        this.initData()
        this.queryData = JSON.parse(JSON.stringify(this.query))
        //排序默认值
        this.setDefaultQuery(this.defaultSortConfig);
    },
    methods: {
        exportData() {
            let ids = []
            this.list.forEach(item => {
                ids.push(item.id)
            })
            request({
                url: `/api/ComputerRoomManagementSign/ComputerRoomManagementSign/Actions/Export`,
                responseType: 'blob',
                method: 'post',
                data: ids
            }).then(res => {
                // 接收接口返回的xlsx文件并下载下来
                this.excelDownload(res)

                this.$message.success('导出成功')
            })
        },
        excelDownload(obj, name = '进出登记数据', suffix = 'xlsx') {//Date.now()获取当前日期
            const url = window.URL.createObjectURL(
                //Blob是二进制大对象
                new Blob([obj], { type: 'application/vnd.ms-excel' })
            )
            const aDOM = document.createElement('a')
            aDOM.style.display = 'none'//设置dom元素不显示，隐藏
            aDOM.href = url
            const fileName = name + '.' + suffix
            aDOM.setAttribute('download', fileName)
            //setAttribute(name, value)增加一个指定名称和值的新属性，或者把一个现有属性设定为指定的值
            document.body.appendChild(aDOM)//向body节点中添加dom节点
            aDOM.click()//在adom上模拟一次鼠标点击
            document.body.removeChild(aDOM)//移除节点
        },
        getDate(time) {
            let str = time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '无数据'
            return str
        },
        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
                    })
                }
            })
        },
        goDetail(row) {
            this.detailVisible = true
            this.$nextTick(() => {
                this.$refs.Detail.init(row)
            })
        },
        initData() {
            // this.queryData = JSON.parse(JSON.stringify(this.query))导致重置失效
            this.listLoading = true;
            let _query = {
                ...this.listQuery,
                ...this.query,
                dataType: 0,
                // menuId: this.menuId,
                // type: 1,
            };
            request({
                url: `/api/ComputerRoomManagement/ComputerRoomManagement/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
            })
        },
        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>
