<template>
<!-- 折算系数维护 -->
    <div class="sourcecode">
        <div class="box">
            <div class="box-top">
                <el-form
                    style="overflow: hidden;"
                    :style="filterForm.show ? null : { height: '0px' }"
                    size="mini"
                    label-width="70px"
                >
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="能介" label-width="40px">
                                <el-select
                                filterable clearable
                                multiple
                                collapse-tags
                                    v-model="filterForm.data.energyid"
                                    placeholder=""
                                    style="width: 100%;"
                                >
                                    <el-option
                                        v-for="item of nameObj.energyid.arr"
                                        :key="item.id"
                                        :value="item.name"
                                        :label="item.name"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="公式版本">
                                <el-date-picker
                                    v-model="filterForm.data.clock"
                                    type="month"
                                    placeholder=""
                                    style="width: 100%;"
                                    format="yyyy-MM"
                                    value-format="yyyyMM00"
                                ></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="能介编码">
                                <el-input clearable
                                    v-model.trim="filterForm.data.code"
                                    placeholder="能介编码"
                                    style="width: 100%;"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div class="box-top-gjl">
                    <el-button
                        class="button"
                        type="primary"
                        size="mini"
                        icon="el-icon-save"
                        @click="but_more()"
                    >保存</el-button>
                    <div style="float:right; text-align: right;">
                        <el-button
                            class="button"
                            type="primary"
                            size="mini"
                            icon="el-icon-search"
                            v-privilege="activeMenu + 'QUERY'"
                            @click="getTableData(1)"
                        >查询</el-button>
                        <el-button
                            class="button"
                            type="primary"
                            size="mini"
                            icon="el-icon-refresh"
                            v-privilege="activeMenu + 'QUERY'"
                            @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-form
                    size="mini"
                    ref="dialog_form_arr"
                    label-width="0px"
                    :model="tableFormDataObj"
                >
                    <el-table stripe
                        id="singleTable"
                        ref="singleTable"
                        :data="tableData"
                        v-loading="tableLoading"
                        style="width: 100%;"
                        :height="singleTableHeight"
                        border
                        size="mini"
                        highlight-current-row
                        @selection-change="handleSelectionChange">
                    >
                        <el-table-column
                            sortable
                            type="selection"
                            width="40"
                            align="center"
                            fixed="left"
                        >
                        </el-table-column>
                        <el-table-column
                        sortable
                            prop="energyid"
                            label="能介编码"
                            width="100px"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                            sortable
                            :sort-by="function(row, index) { return sortFoo(row, index, 'energyid') }"
                            prop="energyid"
                            label="能介名称"
                            width="120px"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <span>{{ nameObj.energyid.obj[scope.row.energyid] ? nameObj.energyid.obj[scope.row.energyid] : scope.row.energyid }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                        sortable
                            prop="clock"
                            label="公式版本"
                            width="100px"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                        sortable
                            prop="sourcecode"
                            label="折算系数"
                            width="125px"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    v-if="scope.row.isSelection"
                                    :prop="scope.row.id + '.sourcecode'"
                                    :rules="dialog.editorBox.form.rules.sourcecode"
                                >
                                    <el-input clearable
                                        style="width: 100%;"
                                        v-model="tableFormDataObj[scope.row.id].sourcecode"
                                        refcous="true"
                                    ></el-input>
                                    <template slot="error" slot-scope="scope">
                                        <p class="error" :title="scope.error">{{ scope.error }}</p>
                                    </template>
                                </el-form-item>
                                <span v-else>{{scope.row.sourcecode}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            sortable
                            prop="unitid"
                            label="单位"
                            width="145px"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    v-if="scope.row.isSelection"
                                    :prop="scope.row.id + '.unitid'"
                                    :rules="dialog.editorBox.form.rules.unitid"
                                >
                                    <el-select
                                        filterable
                                        clearable
                                        style="width: 100%;"
                                        v-model="tableFormDataObj[scope.row.id].unitid"
                                    >
                                        <el-option
                                            v-for="item of nameObj.unitid.arr"
                                            :key="item.id"
                                            :value="item.id"
                                            :label="item.name"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                                <span v-else>{{ nameObj.unitid.obj[scope.row.unitid] ? nameObj.unitid.obj[scope.row.unitid] : scope.row.unitid }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            sortable
                            prop="description"
                            label="描述"
                            width="180px"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                            sortable
                            prop="bz"
                            label="备注"
                            min-width="150px"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    v-if="scope.row.isSelection"
                                    :prop="scope.row.id + '.bz'"
                                    :rules="dialog.editorBox.form.rules.bz"
                                >
                                    <el-input clearable
                                        style="width: 100%;"
                                        v-model="tableFormDataObj[scope.row.id].bz"
                                        refcous="true"
                                    ></el-input>
                                </el-form-item>
                                <span v-else>{{scope.row.bz}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            sortable
                            prop="revisor"
                            label="修改人"
                            width="80px"
                            :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column
                            sortable
                            prop="revisetime"
                            label="修改时间"
                            width="125px"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <!-- <el-table-column
                            class-name="gn-TableDownloadExcel-none"
                            label="操作"
                            align="center"
                            width="75px"
                            fixed="right"
                        >
                            <template slot-scope="scope">
                                <div>
                                    <el-button
                                        type="primary"
                                        size="mini"
                                        v-privilege="activeMenu + 'PUT'"
                                        @click="but_edit(scope.row)"
                                    >修改</el-button>
                                </div>
                            </template>
                        </el-table-column> -->
                    </el-table>
                </el-form>
                <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>
        <el-dialog
            :title="'折算系数信息 - ' + (dialog.editorBox.type === 'add' ? '新增' : '修改')"
            :visible.sync="dialog.editorBox.show"
            width="300px"
            :close-on-click-modal="false"
            :show-close="!loading"
        >
            <div>
                <el-form
                    ref="dialog_form"
                    :model="dialog.editorBox.form.data"
                    :rules="dialog.editorBox.form.rules"
                    size="mini"
                    label-width="70px"
                >
                    <el-form-item label="折算系数" prop="sourcecode">
                        <el-input clearable
                            style="width: 100%;"
                            v-model="dialog.editorBox.form.data.sourcecode"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="描述" prop="description">
                        <el-input clearable
                            style="width: 100%;"
                            v-model="dialog.editorBox.form.data.description"
                            disabled
                        ></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button @click="dialog.editorBox.show = false" :loading="loading">取 消</el-button>
                <el-button
                    type="primary"
                    @click="dataSave"
                    :loading="loading"
                >保 存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { zCheckNumber1 } from '@/utils/validator.js'
import { formatDate } from '@/utils/util.js';
export default {
    name: 'sourcecode',
    data () {
        return {
            activeMenu: '',
            filterForm: {
                show: true,
                data: {
                    code: '',
                    energyid: '',
                    timegranid: 'MONTH',
                    clock: formatDate(new Date(), 'yyyyMM00')
                },
                rules: {

                }
            },
            pageNum: 1,
            pageSize: 50,
            total: 0,
            singleTableHeight: 100,
            tableData: [
                // {
                //     energyid: '液化石油气',
                //     clock: '20180400000000',
                //     sourcecode: '1427',
                //     description: '液化石油气'
                // }
            ],
            tableFormDataObj: {},
            nameObj: {
                energyid: {
                    obj: {},
                    arr: []
                },
                unitid: {
                    obj: {},
                    arr: []
                }
            },
            loading: false,
            tableLoading: false,
            dialog: {
                editorBox: {
                    show: false,
                    type: '',
                    form: {
                        data: {
                            id: '',
                            energyid: '',
                            clock: '',
                            sourcecode: '',
                            description: '',
                            tablename: '',
                            analyzecode: '',
                            isavailable: '',
                            revisetime: '',
                            revisor: ''
                        },
                        rules: {
                            sourcecode: [
                                { required: true, message: '该项不能为空', trigger: 'change' },
                                { validator: zCheckNumber1, trigger: 'change' }
                            ]
                        }
                    }
                }
            },
            multipleSelection: []
        }
    },
    created () {
        this.activeMenu = window.localStorage.getItem('activeMenu');
    },
    mounted () {
        let that = this;
        window.PEDataObj = {
            // 将数据绑定到window上，供main页面使用
            vm: that,
            // tableArr：用于导出成Excel的表格的信息
            tableArr: [
                {
                    name: '',
                    id: 'singleTable'
                }
            ]
        };
        that.$nextTick(() => {
            // 立即获取的height有一定偏差，通过setTimeout延迟来解决
            setTimeout(() => {
                that.singleTableHeight = that.getRoleHeight(that.$refs['singleTable'].$el) - 45;
            }, 1);
        });
        that.getEnergyIdData();
        that.getTableData();
        that.getUnitIdData();
    },
    methods: {
        //  计算树区域高度
        getRoleHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        // 获取标准计量单位
        getUnitIdData () {
            let that = this
            let url = 'pass/ems/v1/trmunits/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.unitid.arr = arr;
                        that.nameObj.unitid.obj = obj;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        // 用于表格特殊列的过滤方法（:sort-by="function(row, index) { return sortFoo() }"）
        sortFoo (row, index, objName, name) {
            name = name || objName;
            let s = this.nameObj[objName].obj[row[name]] ? this.nameObj[objName].obj[row[name]] : row[name];
            return s;
        },
        // 获取能介
        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
                            })
                            obj[item.id] = item.name;
                        }
                        that.nameObj.energyid.arr = arr;
                        that.nameObj.energyid.obj = obj;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        // 获取表格中的数据
        getTableData (pageNum) {
            let that = this,
                params = {
                    energyName: that.filterForm.data.energyid.toString(),
                    code: that.filterForm.data.code,
                    tablename: 'T_RM_ENERGY',
                    clock: that.filterForm.data.clock || ''
                };
            that.pageNum = pageNum || that.pageNum;
            that.tableLoading = true;
            let url = 'pass/ems/v1/formulas/?pageNum=' + that.pageNum + '&pageSize=' + that.pageSize;
            that.axios.get(url, {
                params: params
            })
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                        for (let item of res.data.list) {
                            arr.push({
                                id: item.id,
                                energyid: item.code,
                                clock: item.clock,
                                sourcecode: item.sourcecode,
                                description: item.description,
                                tablename: item.tablename,
                                analyzecode: item.analyzecode,
                                isavailable: item.isavailable,
                                revisetime: item.revisetime,
                                revisor: item.revisor,
                                unitid: item.unitid,
                                bz: item.bz
                            })
                        }
                        that.tableData = arr;
                        that.total = res.data.total;
                    } else {
                        that.$message.error(res.message);
                    }
                    that.tableLoading = false;
                }).catch(function () {
                    that.tableLoading = false;
                });
        },
        // 改变表格显示条数
        tableSizeChange (val) {
            let that = this;
            that.pageSize = val;
            that.getTableData(1);
        },
        // 重置搜索
        tableDataCancel () {
            let that = this;
            that.filterForm.data.code = '';
            that.filterForm.data.energyid = '';
            that.filterForm.data.timegranid = '';
            that.filterForm.data.clock = '';
            that.getTableData(1);
        },
        but_edit (row) {
            let that = this;
            for (let key in that.dialog.editorBox.form.data) {
                if (typeof row[key] !== 'undefined') {
                    that.dialog.editorBox.form.data[key] = row[key];
                } else {
                    console.log(key);
                }
            }
            that.dialog.editorBox.type = 'edit';
            that.dialog.editorBox.show = true;
        },
        but_more () {
            let that = this;
            if (that.multipleSelection.length > 0) {
                that.$refs['dialog_form_arr'].validate((valid) => {
                    if (valid) {
                        let SubmitData = [];
                        for (var name in that.tableFormDataObj) {
                            SubmitData.push({
                                id: that.tableFormDataObj[name].id,
                                code: that.tableFormDataObj[name].energyid,
                                clock: that.tableFormDataObj[name].clock,
                                sourcecode: that.tableFormDataObj[name].sourcecode,
                                tablename: that.tableFormDataObj[name].tablename,
                                analyzecode: that.tableFormDataObj[name].analyzecode,
                                description: that.tableFormDataObj[name].description,
                                isavailable: that.tableFormDataObj[name].isavailable,
                                unitid: that.tableFormDataObj[name].unitid,
                                bz: that.tableFormDataObj[name].bz
                            });
                        }
                        that.loading = true;
                        that.axios.put('pass/ems/v1/formulas/batchupdate', SubmitData)
                            .then(function (res) {
                                if (res.code === '0') {
                                    that.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    });
                                    that.getTableData();
                                    that.dialog.editorBox.show = false;
                                } else {
                                    that.$message.error(res.message);
                                }
                                that.loading = false;
                            }).catch(function () {
                                that.loading = false;
                            });
                    } else {
                        that.$message.error('请输入正确的折标系数');
                    }
                });
            }
        },
        dataSave () {
            let that = this;
            let SubmitData = {
                id: that.dialog.editorBox.form.data.id,
                code: that.dialog.editorBox.form.data.energyid,
                clock: that.dialog.editorBox.form.data.clock,
                sourcecode: that.dialog.editorBox.form.data.sourcecode,
                tablename: that.dialog.editorBox.form.data.tablename,
                analyzecode: that.dialog.editorBox.form.data.analyzecode,
                description: that.dialog.editorBox.form.data.description,
                isavailable: that.dialog.editorBox.form.data.isavailable,
                revisetime: that.dialog.editorBox.form.data.revisetime,
                revisor: that.dialog.editorBox.form.data.revisor,
                bz: that.dialog.editorBox.form.data.bz
            };
            that.$refs['dialog_form'].validate((valid) => {
                if (valid) {
                        that.loading = true;
                        that.axios.put('pass/ems/v1/formulas/updateMula/' + SubmitData.id, SubmitData)
                            .then(function (res) {
                                if (res.code === '0') {
                                    that.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    });
                                    that.getTableData();
                                    that.dialog.editorBox.show = false;
                                } else {
                                    that.$message.error(res.message);
                                }
                                that.loading = false;
                            }).catch(function () {
                                that.loading = false;
                            });
                    // }
                }
            });
        },
        handleSelectionChange (val) {
            let that = this;
            let tableFormDataObj = {};
            for (let item of that.tableData) {
                item.isSelection = false;
            }
            for (let item of val) {
                let obj = {};
                let xId = item.id;
                if (that.tableFormDataObj[xId]) {
                    tableFormDataObj[xId] = that.tableFormDataObj[xId];
                } else {
                    for (let key in item) {
                        obj[key] = item[key];
                    }
                    tableFormDataObj[xId] = obj;
                }
                item.isSelection = true;
            }
            that.tableFormDataObj = tableFormDataObj;
            this.multipleSelection = val;
        }
    }
}
</script>

<style lang="less">
.sourcecode {
    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;
                // margin-top: -7px;
                padding: 7px 0;
                border-top: 1px solid #ccc;
                // border-bottom: 1px solid #ccc;
                // margin-bottom: 6px;
            }
        }
    }
    .el-table__body .el-form-item--mini.el-form-item {
        margin: 0px;
        .error {
            overflow: hidden;
            color: #f56c6c;
            font-size: 12px;
            line-height: 1;
        }
    }
}
</style>
