<template>
    <!-- 上报产量维护 -->
    <div class="productwData">
        <div class="box">
            <div class="box-top">
                <el-form
                    style="overflow: hidden;"
                    :style="filterForm.show ? null : { height: '0px' }"
                    size="mini"
                    label-width="85px"
                >
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="时间粒度">
                                <el-select
                                    filterable clearable
                                    v-model="filterForm.data.timegranid"
                                    placeholder=""
                                    style="width: 100%;"
                                >
                                    <el-option
                                        v-for="item of nameObj.timegranid.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="时间">
                                <zj-timegran-date
                                    v-model="filterForm.data.clock"
                                    style="width: 100%;"
                                    :type="'daterange'"
                                    :timegranId="filterForm.data.timegranid"
                                    :oneFoo="getTableData"
                                    :defaultOffset="-1"
                                ></zj-timegran-date>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="物料名称">
                                <el-input clearable
                                    v-model.trim="filterForm.data.pname"
                                    placeholder=""
                                    style="width: 100%;"
                                    @keyup.enter.native="getTableData(1)"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="工序">
                                <el-select filterable clearable multiple
                                    collapse-tags
                                    v-model="filterForm.data.workprocid"
                                    placeholder=""
                                    style="width: 100%;"
                                >
                                    <el-option
                                        v-for="item of nameObj.workprocid.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-input clearable
                                    v-model.trim="filterForm.data.itemid"
                                    placeholder=""
                                    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.trim="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="是否已确认">
                                <el-select clearable
                                    v-model="filterForm.data.state"
                                    placeholder="是否已确认"
                                    style="width: 100%;"
                                >
                                    <el-option
                                        v-for="item of nameObj.state.arr"
                                        :key="item.id"
                                        :value="item.id"
                                        :label="item.name"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div class="box-top-gjl">
                    <el-button
                        type="primary"
                        size="mini"
                        icon="el-icon-edit-outline"
                        v-privilege="activeMenu + 'PUT'"
                        @click="but_edit_plural()"
                        :loading="loading"
                    >确认</el-button>
                    <el-button
                        class="button"
                        type="primary"
                        size="mini"
                        icon="el-icon-refresh"
                        :loading="loading"
                        @click="but_get_data()"
                    >获取数据</el-button>
                    <div style="float:right; text-align: right;">
                        <el-button
                            class="button"
                            type="primary"
                            icon="el-icon-search"
                            size="mini"
                            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"
                        :row-class-name="rowClassName"
                        @cell-click="cellClick"
                        show-summary
                        :summary-method="getSummaries"
                    >
                        <el-table-column type="selection" width="40" align="center" fixed="left"></el-table-column>
                        <el-table-column
                        sortable
                            prop="timegranid"
                            label="粒度"
                            width="52px"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <span>{{ nameObj.timegranid.obj[scope.row.timegranid] ? nameObj.timegranid.obj[scope.row.timegranid] : scope.row.timegranid }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                        sortable
                            prop="clock"
                            label="时间"
                            width="65px"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                        sortable
                            prop="workprocid"
                            label="工序"
                            width="75px"
                            :show-overflow-tooltip="true"
                            :sort-by="function(row, index) { return sortFoo(row, index, 'workprocid') }"
                        >
                            <template slot-scope="scope">
                                <span>{{ nameObj.workprocid.obj[scope.row.workprocid] ? nameObj.workprocid.obj[scope.row.workprocid] : scope.row.workprocid }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                        sortable
                            prop="itemid"
                            label="项目编号"
                            width="105px"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                        sortable
                            prop="itemname"
                            label="项目名称"
                            width="165px"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                        sortable
                            prop="pname"
                            label="物料名称"
                            width="80px"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                            sortable
                            prop="unitid"
                            label="单位"
                            width="70px"
                            :show-overflow-tooltip="true"
                            :sort-by="function(row, index) { return sortFoo(row, index, 'unitid') }"
                        >
                            <template slot-scope="scope">
                                <span>{{ 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="apportvalue"
                            label="系统产量"
                            width="90px"
                            align="right"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                            sortable
                            prop="productwvalue"
                            label="上报产量"
                            width="120px"
                            align="right"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    v-if="scope.row.isSelection"
                                    :prop="scope.row.itemid + '-' + scope.row.clock + '.productwvalue'"
                                    :rules="dialog.editorBox.form.rules.productwvalue"
                                >
                                    <el-input clearable @keydown.native="keyDown" :id="scope.$index + scope.column.id"
                                        style="width: 100%;"
                                        v-model="tableFormDataObj[scope.row.itemid + '-' + scope.row.clock].productwvalue"
                                        refcous="true"
                                    ></el-input>
                                </el-form-item>
                                <span v-else>{{scope.row.productwvalue}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            sortable
                            prop="rtpitemid"
                            label="上报产量关联编号"
                            width="300px"
                            align="right"
                            :show-overflow-tooltip="true"
                        >
                          <template slot-scope="scope">
                                <el-form-item
                                    v-if="scope.row.isSelection"
                                    :prop="scope.row.itemid + '-' + scope.row.clock + '.rtpitemid'"
                                    :rules="dialog.editorBox.form.rules.rtpitemid"
                                >
                                    <el-input clearable @keydown.native="keyDown" :id="scope.$index + scope.column.id"
                                        style="width: 100%;"
                                        v-model="tableFormDataObj[scope.row.itemid + '-' + scope.row.clock].rtpitemid"
                                        refcous="true"
                                    ></el-input>
                                </el-form-item>
                                <span v-else>{{scope.row.rtpitemid}}</span>
                            </template></el-table-column>
                        <!-- <el-table-column
                            sortable
                            prop="state"
                            label="已确认"
                            width="80px"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <span>{{ nameObj.state.obj[scope.row.state] ? nameObj.state.obj[scope.row.state] : scope.row.state }}</span>
                            </template>
                        </el-table-column> -->
                        <el-table-column
                            sortable
                            prop="upuser"
                            label="确认人"
                            width="90px"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                            sortable
                            prop="uptime"
                            label="确认时间"
                            width="130px"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                            sortable
                            prop="bz"
                            label="备注"
                            min-width="55px"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    v-if="scope.row.isSelection"
                                    :prop="scope.row.itemid + '-' + scope.row.clock + '.bz'"
                                    :rules="dialog.editorBox.form.rules.bz"
                                >
                                    <el-input clearable @keydown.native="keyDown" :id="scope.$index + scope.column.id"
                                        style="width: 100%;"
                                        v-model="tableFormDataObj[scope.row.itemid + '-' + scope.row.clock].bz"
                                        refcous="true"
                                    ></el-input>
                                </el-form-item>
                                <span v-else>{{scope.row.bz}}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import { formatDate, commonSummaries } from '@/utils/util.js';
import timegranDate from '@/components/zg/timegranDate.vue'
import { zCheckNumber1 } from '@/utils/validator.js'
export default {
    name: 'productwData',
    components: {
        'zj-timegran-date': timegranDate
    },
    data () {
        return {
            rowIndex: '',
            columnId: '',
            focusTarget: null,
            seqArr: [],
            editSetFlag: '',
            activeMenu: '',
            filterForm: {
                show: true,
                useflag: '1',
                data: {
                    timegranid: 'MONTH',
                    clock: '',
                    energyid: '',
                    workprocid: '',
                    state: '',
                    itemid: '',
                    itemname: '',
                    pname: ''
                },
                rules: {}
            },
            pageNum: 1,
            pageSize: 100,
            total: 0,
            singleTableHeight: 100,
            tableData: [],
            multipleSelection: [],
            tableFormDataObj: {},
            nameObj: {
                timegranid: {
                    obj: {
                        'MONTH': '月',
                        'YEAR': '年'
                    },
                    arr: [{id: 'MONTH', name: '月'}, {id: 'YEAR', name: '年'}]
                },
                workprocid: {
                    obj: {},
                    arr: []
                },
                unitid: {
                    obj: {},
                    arr: []
                },
                state: {
                    obj: {'0': '否', '1': '是'},
                    arr: [{id: '0', name: '否'}, {id: '1', name: '是'}]
                }
            },
            loading: false,
            tableLoading: false,
            dialog: {
                editorBox: {
                    show: false,
                    form: {
                        data: {
                            productwvalue: '',
                            energyid: '',
                            showno: ''
                        },
                        rules: {
                            energyid: [
                                { required: true, message: '该项不能为空', trigger: 'change' }
                            ],
                            productwvalue: [
                                { validator: zCheckNumber1, trigger: 'change' }
                            ],
                            bz: [],
                            rtpitemid: []
                        }
                    }
                }
            }
        }
    },
    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.getWorkprocIdData();
        that.getUnitIdData();
    },
    methods: {
        //  计算树区域高度
        getRoleHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        // 用于表格特殊列的过滤方法（: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;
        },
        // 自定义的表格合计方法：只给指定列进行合计
        getSummaries (param) {
            const prop = ['apportvalue', 'productwvalue']; // 合计列绑定的prop
            return commonSummaries(param, prop);
        },
        // 获取工序(供需实际)
        getWorkprocIdData () {
            let that = this;
            let url = 'pass/ems/v1/trmworkprocs/getIdAndName?id=ZY3000,ZY4000,ZY5000,ZY6000,ZY7000,ZY8000,ZY9000,ZY9300,ZY9400'; // ZYA000,ZY1000
            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.workprocid.arr = arr;
                        that.nameObj.workprocid.obj = obj;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        // 获取标准计量单位
        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);
                    }
                });
        },
        // 获取表格中的数据
        getTableData (pageNum) {
            let that = this,
                params = {
                    timegranid: that.filterForm.data.timegranid,
                    clock: that.filterForm.data.clock[0],
                    clocke: that.filterForm.data.clock[1],
                    pname: that.filterForm.data.pname,
                    workprocid: that.filterForm.data.workprocid.toString(),
                    itemid: that.filterForm.data.itemid,
                    itemname: that.filterForm.data.itemname,
                    state: that.filterForm.data.state
                };
            that.pageNum = pageNum || that.pageNum;
            that.tableLoading = true;
            let url = 'pass/ems/v1/trmactitems/listpv/?pageNum=' + that.pageNum + '&pageSize=' + that.pageSize;
            that.axios.get(url, {
                params: params
            })
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                        for (let i = 0; i < res.data.length; i++) {
                            let item = res.data[i];
                            arr.push({
                                seq: i,
                                clock: item.CLOCK,
                                timegranid: item.TIMEGRANID,
                                itemid: item.ITEMID,
                                itemname: item.ITEMNAME,
                                workprocid: item.WORKPROCID,
                                unitid: item.UNITID,
                                pname: item.PNAME,
                                apportvalue: item.APPORTVALUE,
                                productwvalue: item.PRODUCTWVALUE,
                                upuser: item.UPUSER,
                                uptime: item.UPTIME,
                                state: item.PRODUCTWVALUE ? '1' : '0',
                                bz: item.BZ,
                                rtpitemid: item.RTPITEMID
                            })
                        }
                        that.tableData = arr;
                    } 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;
            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);
        },
        handleSelectionChange (val) {
            let that = this;
            let tableFormDataObj = {};
            let arr = [];
            for (let item of val) {
                arr.push(item.seq);
            }
            this.seqArr = arr.sort(sortNumber);
            for (let item of that.tableData) {
                item.isSelection = false;
            }
            for (let item of val) {
                let obj = {};
                let xId = item.itemid + '-' + item.clock;
                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;
            that.multipleSelection = val;
        },
        // 批量确认
        but_edit_plural () {
            let that = this;
            if (that.multipleSelection.length > 0) {
                that.$refs['dialog_form_arr'].validate((valid, msg) => {
                    if (valid) {
                        let SubmitData = [];
                        for (let key in that.tableFormDataObj) {
                            SubmitData.push({
                                itemid: that.tableFormDataObj[key].itemid,
                                clock: that.tableFormDataObj[key].clock,
                                apportvalue: that.tableFormDataObj[key].apportvalue,
                                productwvalue: that.tableFormDataObj[key].productwvalue,
                                bz: that.tableFormDataObj[key].bz,
                                rtpitemid: that.tableFormDataObj[key].rtpitemid
                            });
                        }
                        that.loading = true;
                        that.axios.put('pass/ems/v1/trmdwvalues/batchqr', SubmitData)
                            .then(function (res) {
                                if (res.code === '0') {
                                    that.$message({
                                        message: '操作成功',
                                        type: 'success'
                                    });
                                    that.getTableData();
                                } else {
                                    that.$message.error(res.message);
                                }
                                that.loading = false;
                            }).catch(function () {
                                that.loading = false;
                            });
                        } else {
                            let col = Object.keys(msg)[0].split('.')[1];
                            if (col && col === 'productwvalue') {
                                this.$message.error('请填写正确的上报值');
                            } else {
                                this.$message.error('数据不完整或者格式错误');
                            }
                        }
                });
            } else {
                this.$message.error('至少要选择一条数据');
            }
        },
        // 根据上报产量关联编号获取上报产量数据
        but_get_data () {
            let that = this;
            if (that.multipleSelection.length > 0) {
                that.$refs['dialog_form_arr'].validate((valid, msg) => {
                    if (valid) {
                        let SubmitData = [];
                        for (let key in that.tableFormDataObj) {
                            SubmitData.push({
                                itemid: that.tableFormDataObj[key].itemid,
                                clock: that.tableFormDataObj[key].clock,
                                rtpitemid: that.tableFormDataObj[key].rtpitemid
                            });
                        }
                        that.loading = true;
                        that.axios.put('pass/ems/v1/trmdwvalues/getPwData', SubmitData)
                            .then(function (res) {
                                if (res.code === '0' && res.data) {
                                    for (let item of res.data) {
                                        let xId = item.key;
                                        let val = item.val;
                                        that.tableFormDataObj[xId].productwvalue = val;
                                    }
                                    that.$message({
                                        message: '获取数据成功',
                                        type: 'success'
                                    });
                                } else {
                                    if (res.message) {
                                        that.$message.error(res.message);
                                    } else {
                                        that.$message.error('获取数据失败');
                                    }
                                }
                                that.loading = false;
                            }).catch(function () {
                                that.loading = false;
                            });
                        } else {
                            let col = Object.keys(msg)[0].split('.')[1];
                            if (col && col === 'productwvalue') {
                                this.$message.error('请填写正确的上报值');
                            } else {
                                this.$message.error('数据不完整或者格式错误');
                            }
                        }
                });
            } else {
                this.$message.error('至少要选择一条数据');
            }
        },
        rowClassName ({row, rowIndex}) {
            row.index = rowIndex;
        },
        // 回车换行1
        keyDown (event1) {
            let tdTarget = event1.target;
            let _this = this;
            while (tdTarget.tagName !== 'TD') {
                tdTarget = tdTarget.parentElement;
            }
            // 如果按下键盘下键或者回车键
            if (event.keyCode === 40 || event.keyCode === 13) {
                let index = parseInt(this.rowIndex);
                // index++;
                if (index !== this.seqArr[this.seqArr.length - 1]) {
                    for (let i = 0; i < this.seqArr.length; i++) {
                        if (index === this.seqArr[i]) {
                        index = this.seqArr[i + 1];
                        break;
                        }
                    }
                }
                this.editSetFlag = index + this.columnId;
                let id = '#' + this.editSetFlag;
                // console.log('id', id);
                this.$nextTick(() => {
                    $(id).click();
                });
            }
        },
        // 回车换行3
        cellClick (row, column, cell, event) {
            let _this = this;
            this.rowIndex = row.index;
            this.columnId = column.id;
            _this.editSetFlag = row.index + column.id;
            _this.focusTarget = event.target;
            while (_this.focusTarget.tagName !== 'TD') {
                _this.focusTarget = _this.focusTarget.parentElement;
            }
            _this.$nextTick(() => {
                let target = this.focusTarget;
                $(target).find('input').focus();
            });
        }
    }
}
function sortNumber (a, b) {
  return a - b
}
</script>

<style lang="less">
.productwData {
    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 {
            background-color: #dfdfdf !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;
            }
        }
        .el-table__body input {
            font-weight: normal;
            padding-left: 8px;
            padding-right: 25px;
        }
    }
}
</style>
