<template>
<!-- 能源仪表数据查询 -->
    <div class="emsMeterData">
        <div class="box">
            <div class="box-top">
                <el-form
                    style="overflow: hidden;"
                    :style="filterForm.show ? null : { height: '0px' }"
                    size="mini"
                    label-width="80px"
                >
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="日期">
                                <el-date-picker
                                    value-format="yyyy-MM-dd"
                                    type="daterange"
                                    v-model="filterForm.data.clock"
                                    placeholder="日期"
                                    style="width: 100%;"
                                ></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="能介大类">
                                <el-select
                                    clearable
                                    filterable
                                    multiple
                                    collapse-tags
                                    v-model="filterForm.data.energytypeid"
                                    placeholder="能介大类"
                                    style="width: 100%;"
                                    @keyup.enter.native="getTableData(1)"
                                >
                                    <el-option
                                        v-for="item of nameObj.energytypeid.arr"
                                        :key="item.id"
                                        :value="item.id"
                                        :label="item.name"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="能介名称">
                                <el-select
                                    clearable
                                    filterable
                                    multiple
                                    collapse-tags
                                    v-model="filterForm.data.energy"
                                    placeholder="能介名称"
                                    style="width: 100%;"
                                    @keyup.enter.native="getTableData(1)"
                                >
                                    <el-option
                                        v-for="item of nameObj.energyid.arr"
                                        :key="item.id"
                                        :value="item.id"
                                        :label="item.name"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="能介属性">
                                <el-select
                                    clearable
                                    filterable
                                    multiple
                                    collapse-tags
                                    v-model="filterForm.data.property"
                                    placeholder="能介属性"
                                    style="width: 100%;"
                                    @keyup.enter.native="getTableData(1)"
                                >
                                    <el-option
                                        v-for="item of nameObj.propertyid.arr"
                                        :key="item.id"
                                        :value="item.id"
                                        :label="item.name"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="工序">
                                <el-select
                                    clearable
                                    filterable
                                    multiple
                                    collapse-tags
                                    v-model="filterForm.data.workproc"
                                    placeholder="工序"
                                    style="width: 100%;"
                                    @keyup.enter.native="getTableData(1)"
                                >
                                    <el-option
                                        v-for="item of nameObj.locateid.arr"
                                        :key="item.id"
                                        :value="item.id"
                                        :label="item.name"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="计量点名称">
                                <el-input
                                    clearable
                                    v-model="filterForm.data.itemname"
                                    placeholder="计量点名称"
                                    style="width: 100%;"
                                    @keyup.enter.native="getTableData(1)"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="CorDas位置">
                                <el-input
                                    clearable
                                    v-model="filterForm.data.cordastablecolum"
                                    placeholder="CorDas数据位置"
                                    style="width: 100%;"
                                    @keyup.enter.native="getTableData(1)"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="十分钟表位置">
                                <el-input
                                    clearable
                                    v-model="filterForm.data.timingtablecolum"
                                    placeholder="10分钟表数据位置"
                                    style="width: 100%;"
                                    @keyup.enter.native="getTableData(1)"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="小时表位置">
                                <el-input
                                    clearable
                                    v-model="filterForm.data.hourtablecolum"
                                    placeholder="小时表数据位置"
                                    style="width: 100%;"
                                    @keyup.enter.native="getTableData(1)"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div class="box-top-gjl">
                    <span style="font-size:14px;">数据获取时间：{{ CorDasTime }}</span>
                    <!-- v-if="userInfo.data && userInfo.data.userId === 'admin'" -->
                    <el-checkbox
                        v-show="tableData.length > 0"
                        v-model="autoGetData"
                        style="margin-left: 7px;"
                    >自动更新数据</el-checkbox>
                    <div style="float:right; text-align: right;">
                        <el-button
                            class="button"
                            type="primary"
                            size="mini"
                            icon="el-icon-search"
                            @click="getTableData(1)"
                        >查询</el-button>
                        <el-button
                            class="button"
                            type="primary"
                            size="mini"
                            icon="el-icon-refresh"
                            @click="tableDataCancel();"
                        >重置</el-button>
                        <el-button
                            size="mini"
                            :icon="filterForm.show ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
                            :title="filterForm.show ? '收起搜索区' : '展开搜索区'"
                            @click="filterForm.show = !filterForm.show;
                                $nextTick(() => {
                                    singleTableHeight = getRoleHeight($refs['singleTable'].$el) - 45;
                                }
                            );"
                        >{{ filterForm.show ? '收起' : '展开' }}</el-button>
                    </div>
                </div>
            </div>
            <div class="box-bottom">
                <el-table stripe
                    id="singleTable"
                    ref="singleTable"
                    :data="tableData"
                    v-loading="tableLoading"
                    style="width: 100%;"
                    :height="singleTableHeight"
                    border
                    size="mini"
                    highlight-current-row
                    :row-class-name="rowClassName"
                    show-summary
                    :summary-method="getSummaries"
                >
                    <el-table-column
                        sortable
                        prop="workproc"
                        label="工序"
                        width="100px"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <span>{{ nameObj.locateid.obj[scope.row.workproc] ? nameObj.locateid.obj[scope.row.workproc] : scope.row.workproc }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable
                        prop="energytypeid"
                        label="能介大类"
                        width="100px"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <span>{{ nameObj.energytypeid.obj[scope.row.energytypeid] ? nameObj.energytypeid.obj[scope.row.energytypeid] : scope.row.energytypeid }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable
                        prop="energy"
                        label="能介名称"
                        width="100px"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <span>{{ nameObj.energyid.obj[scope.row.energy] ? nameObj.energyid.obj[scope.row.energy].name : scope.row.energy }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable
                        prop="property"
                        label="能介属性"
                        width="70px"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <span>{{ nameObj.propertyid.obj[scope.row.property] ? nameObj.propertyid.obj[scope.row.property] : scope.row.property }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable
                        prop="itemname"
                        label="计量点名称"
                        min-width="100px"
                        :show-overflow-tooltip="true"
                    ></el-table-column>
                    <el-table-column
                        sortable
                        prop="mintvalue"
                        label="仪表期初值"
                        min-width="100px"
                        :show-overflow-tooltip="true"
                    ></el-table-column>
                    <el-table-column
                        sortable
                        prop="mendvalue"
                        label="仪表期末值"
                        min-width="100px"
                        :show-overflow-tooltip="true"
                    ></el-table-column>
                    <el-table-column
                        sortable
                        label="期末-期初"
                        min-width="100px"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <span>{{ isNaN(scope.row.mendvalue - scope.row.mintvalue) ? '' : floatComputed(scope.row.mendvalue, scope.row.mintvalue, '-') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable
                        prop="actualvalue"
                        label="计算值"
                        min-width="100px"
                        :show-overflow-tooltip="true"
                    ></el-table-column>
                    <el-table-column
                        sortable
                        prop="value"
                        label="当前仪表实时值"
                        min-width="120px"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <span :class="{ color_yes: scope.row.ischange, color_no: scope.row.noChangeSize > 60 }">{{ scope.row.value }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable
                        prop="dasaddress"
                        label="das地址"
                        min-width="100px"
                        :show-overflow-tooltip="true"
                    ></el-table-column>
                    <el-table-column
                        sortable
                        prop="cordastable"
                        label="CorDas数据位置"
                        min-width="120px"
                        :show-overflow-tooltip="true"
                    ></el-table-column>
                    <el-table-column
                        sortable
                        prop="timingtable"
                        label="10分钟表数据位置"
                        min-width="120px"
                        :show-overflow-tooltip="true"
                    ></el-table-column>
                    <el-table-column
                        sortable
                        prop="hourtable"
                        label="小时表数据位置"
                        min-width="120px"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <span>{{ (scope.row.hourtable && scope.row.hourcolum) ? (scope.row.hourtable + '.' + scope.row.hourcolum) : '' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable
                        prop="itemid"
                        label="计量点编号"
                        width="108px"
                        :show-overflow-tooltip="true"
                    ></el-table-column>
                    <!-- <el-table-column
                        sortable
                        prop=""
                        label="项目编号"
                        min-width="100px"
                        :show-overflow-tooltip="true"
                    ></el-table-column> -->
                </el-table>
                <!-- <el-pagination
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    :page-sizes="[10, 20, 50, 100, 500, 1000]"
                    :page-size="pageSize"
                    :current-page.sync="pageNum"
                    @size-change="tableSizeChange"
                    @current-change="getTableData()"
                    style="text-align: right;margin-top: 10px;"
                ></el-pagination> -->
            </div>
        </div>
    </div>
</template>

<script>
import timegranDate from '@/components/zg/timegranDate.vue'
import {formatDate, commonSummaries} from '@/utils/util.js';
import store from '@/store/index.js';
export default {
    name: 'emsMeterData',
    components: {
        'zj-timegran-date': timegranDate
    },
    data () {
        let setDate = new Date();
        setDate.setDate((setDate.getDate() - 1));
        setDate = formatDate(setDate, 'yyyy-MM-dd')
        return {
            store,
            userInfo: {
                data: null
            },
            autoGetData: false,
            autoTimeId: null,
            autoSize: 0,
            activeMenu: '',
            operateType: '0',
            filterForm: {
                show: true,
                data: {
                    clock: [setDate, setDate],
                    workproc: '',
                    energytypeid: '',
                    energy: '',
                    property: '',
                    itemname: '',
                    hourtablecolum: '',
                    timingtablecolum: '',
                    cordastablecolum: ''
                },
                rules: {

                }
            },
            CorDasTime: '',
            pageNum: 1,
            pageSize: 2000,
            total: 0,
            singleTableHeight: 100,
            tableData: [],
            multipleSelection: [],
            loading: false,
            tableLoading: false,
            nameObj: {
                energytypeid: {
                    obj: {},
                    arr: []
                },
                energyid: {
                    obj: {},
                    arr: []
                },
                propertyid: {
                    obj: {},
                    arr: []
                },
                locateid: {
                    obj: {},
                    arr: []
                }
            }
        }
    },
    watch: {
        'autoGetData': function (newVal, oldVal) {
           let that = this;
            window.clearInterval(that.autoTimeId);
            that.autoSize = 0;
            if (that.autoGetData) {
                console.log('on')
                that.autoTimeId = setInterval(function () {
                    if (that.autoSize < 100) {
                        that.getCorDasData();
                        that.autoSize++;
                    } else {
                        that.autoGetData = false;
                    }
                }, 2000);
            } else {
                console.log('off')
            }
        }
    },
    created () {
        this.activeMenu = window.localStorage.getItem('activeMenu');
    },
    mounted () {
        let that = this;
        window.PEDataObj = {
            // 将数据绑定到window上，供main页面使用
            vm: that,
            // tableArr：用于导出成Excel的表格的信息
            tableArr: [
                {
                    name: '',
                    id: 'singleTable'
                }
            ]
        };
        that.store.dispatch('getUserInfo').then((res) => {
            that.userInfo.data = res.data;
        });
        that.$nextTick(() => {
            // 立即获取的height有一定偏差，通过setTimeout延迟来解决
            setTimeout(() => {
                that.singleTableHeight = that.getRoleHeight(that.$refs['singleTable'].$el) - 15;
            }, 1);
        });
        that.getEnergyTypeIdData();
        that.getEnergyIdData();
        that.getPropertyIdData();
        that.getLocateIdData();
        that.getTableData(1);
    },
    methods: {
        //  计算树区域高度
        getRoleHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        // 自定义的表格合计方法：只给指定列进行合计
        getSummaries (param) {
            const prop = ['actualvalue']; // 合计列绑定的prop
            return commonSummaries(param, prop);
        },
        rowClassName ({row, rowIndex}) {
            return row.property === '2' || row.property === '3' ? 'rowDisable' : ''
        },
        // 获取能介类型
        getEnergyTypeIdData () {
            let that = this
            let url = 'pass/ems/v1/trmenergytypes/selectNameAndId/';
            that.axios.get(url)
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                        let obj = {};
                        for (let item of res.data) {
                            arr.push({
                                id: item.id,
                                name: item.name
                            })
                            obj[item.id] = item.name;
                        }
                        that.nameObj.energytypeid.arr = arr;
                        that.nameObj.energytypeid.obj = obj;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        // 获取能介
        getEnergyIdData () {
            let that = this;
            let url = 'pass/ems/v1/trmenergys/selectNameAndId/';
            that.axios.get(url)
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                        let obj = {};
                        for (let item of res.data) {
                            arr.push({
                                id: item.id,
                                name: item.name,
                                energytypeid: item.energytypeid,
                                unitid: item.unitid
                            })
                            obj[item.id] = {
                                name: item.name,
                                unitid: item.unitid
                            }
                        }
                        that.nameObj.energyid.arr = arr;
                        that.nameObj.energyid.obj = obj;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        // 获取属性
        getPropertyIdData () {
            let that = this
            let url = 'pass/ems/v1/trmenergypropertys/getidandname/';
            that.axios.get(url)
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                        let obj = {};
                        for (let item of res.data) {
                            arr.push({
                                id: item.id,
                                name: item.name
                            })
                            obj[item.id] = item.name;
                        }
                        that.nameObj.propertyid.arr = arr;
                        that.nameObj.propertyid.obj = obj;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        // 获取位置
        getLocateIdData () {
            let that = this
            let url = 'pass/ems/v1/trmlocations/getidandname/';
            that.axios.get(url)
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                        let obj = {};
                        for (let item of res.data) {
                            arr.push({
                                id: item.id,
                                name: item.name
                            })
                            obj[item.id] = item.name;
                        }
                        that.nameObj.locateid.arr = arr;
                        that.nameObj.locateid.obj = obj;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        // 获取表格中的数据
        getTableData (pageNum) {
            let that = this,
                params = {
                    workproc: that.filterForm.data.workproc.toString(),
                    energytype: that.filterForm.data.energytypeid.toString(),
                    energy: that.filterForm.data.energy.toString(),
                    property: that.filterForm.data.property.toString(),
                    itemname: that.filterForm.data.itemname,
                    hourtablecolum: that.filterForm.data.hourtablecolum,
                    timingtablecolum: that.filterForm.data.timingtablecolum,
                    cordastablecolum: that.filterForm.data.cordastablecolum
                };
            that.pageNum = pageNum || that.pageNum;
            that.autoGetData = false;
            that.tableLoading = true;
            let url = 'pass/ems/v1/cordasconfigurations/like/?pageNum=' + that.pageNum + '&pageSize=' + that.pageSize;
            that.axios.get(url, {
                params: params
            })
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                        // let workprocSet = new Set();
                        // let propertySet = new Set();
                        for (let i = 0; i < res.data.list.length; i++) {
                            let item = res.data.list[i];
                            arr.push({
                                workproc: item.WORKPROC,
                                energytypeid: item.ENERGYTYPE,
                                energy: item.ENERGY,
                                property: item.PROPERTY,
                                cordastable: item.SOURCE_TYPE,
                                dasaddress: item.DASADDRESS,
                                itemid: item.ITEMID,
                                itemname: item.ITEMNAME,
                                hourtable: item.HOURTABLE,
                                hourcolum: item.HOURCOLUM,
                                timingtable: item.BTYPE2,
                                returnName: 'DATA_TAB_' + i
                            });
                            // workprocSet.add(item.workproc);
                            // propertySet.add(item.property);
                        }
                        that.tableData = arr;
                        that.getItemDate();
                        that.getCorDasData();
                        // that.total = res.data.total;
                    } else {
                        that.$message.error(res.message);
                    }
                    that.tableLoading = false;
                }).catch(function () {
                    that.tableLoading = false;
                });
        },
        // 获取指定日期的计量点数据
        getItemDate () {
            let that = this,
                idsArr = [];
            if (!that.tableData || that.tableData.length < 1) {
                return true;
            }
            for (let item of that.tableData) {
                idsArr.push(item.itemid);
            }
            console.log('---', idsArr.toString());
            let params = {
                    // timegranid: 'DAY',
                    start: that.filterForm.data.clock[0],
                    end: that.filterForm.data.clock[1],
                    ids: idsArr.toString()
                };
            let url = 'pass/ems/v1/trmcalpointvalues/getCalpointValue';
            that.axios.get(url, {
                params: params
            })
                .then(function (res) {
                    if (res.code === '0') {
                        let obj = {};
                        for (let item of res.data) {
                            obj[item.itemid] = {
                                mintvalue: item.qc,
                                mendvalue: item.qm,
                                actualvalue: item.ap
                            }
                        }
                        let arr = [];
                        for (let item of that.tableData) {
                            item.mintvalue = obj[item.itemid].mintvalue;
                            item.mendvalue = obj[item.itemid].mendvalue;
                            item.actualvalue = obj[item.itemid].actualvalue;
                            arr.push(item);
                        }
                        that.tableData = arr;
                    } else {
                        that.$message.error(res.message);
                    }
                }).catch(function () {
                    that.tableLoading = false;
                });
        },
        // 获取CorDas的实时数据
        getCorDasData () {
            let that = this,
                cordasSql = '';
            for (let item of that.tableData) {
                if (cordasSql !== '') {
                    cordasSql += ', ';
                }
                cordasSql += item.cordastable + ' ' + item.returnName;
            }
            let url = 'pass/ems/v1/emscordass/gettabledata';
            that.axios.post(url, {
                cordasDataNames: cordasSql
            }, {
                contentType: 'application/json'
            })
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                        for (let item of that.tableData) {
                            if (item.value && item.value !== res.data[0][item.returnName]) {
                                item.ischange = true;
                                item.noChangeSize = 0;
                            } else {
                                item.ischange = false;
                                item.noChangeSize ? item.noChangeSize++ : item.noChangeSize = 1;
                            }
                            item.value = res.data[0][item.returnName];
                            arr.push(item);
                        }
                        that.tableData = arr;
                        that.CorDasTime = formatDate(res.data[0].TIM.replace(/-/g, '/'), 'yyyy/MM/dd HH:mm:ss');
                    } else {
                        that.$message.error(res.message);
                    }
                }).catch(function () {
                });
        },
        // 改变表格显示条数
        tableSizeChange (val) {
            let that = this;
            that.pageSize = val;
            that.getTableData(1);
        },
        // 重置搜索
        tableDataCancel () {
            let that = this;
            for (let key in that.filterForm.data) {
                if (that.filterForm.data[key] instanceof Array) {
                    that.filterForm.data[key] = [];
                } else {
                    that.filterForm.data[key] = '';
                }
            }
            that.getTableData(1);
        }
    }
}
</script>

<style lang="less">
.emsMeterData {
    min-width: 700px;
    height: 100%;
    .box {
        height: 100%;
        padding: 15px 15px 0 15px;
        .box-top {
            .el-form-item {
                margin-bottom: 7px;
            }
            .box-top-gjl {
                overflow: hidden;
                padding: 7px 0;
                border-top: 1px solid #ccc;
            }
        }
        .rowDisable td {
            color: #6bb025 !important;
        }
        .el-table .el-table__row {
            height: 35px;
        }
        .el-table__body .el-form-item--mini.el-form-item {
            margin: 0px;
            .error {
                overflow: hidden;
                color: #f56c6c;
                font-size: 12px;
                line-height: 1;
            }
        }
    }
    .color_no {
        // color: red;
    }
    .color_yes {
        // color: #1a9f17;
    }
    .cnspicuous .el-checkbox__input.is-disabled .el-checkbox__inner {
        background-color: #dcdfe6;
        border-color: #babbbf;
    }
}
</style>
