<template>
    <!-- 原材料消耗盈亏 -->
    <div class="processAndRawMaterials">
        <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="月份">
                                <zj-timegran-date
                                    v-model="filterForm.data.clock"
                                    style="width: 100%;"
                                    :timegranId="'MONTH'"
                                    :oneFoo="getTableData"
                                ></zj-timegran-date>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="产品名称">
                                <el-select
                                    filterable 
                                    collapse-tags
                                    v-model="filterForm.data.productid"
                                    placeholder=""
                                    style="width: 100%;"
                                >
                                    <el-option
                                        v-for="item of nameObj.productid.arr"
                                        :key="item.id"
                                        :value="item.id"
                                        :label="item.name"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="工序">
                                <el-select
                                    filterable 
                                    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-form>
                <div class="box-top-gjl">
                    <el-checkbox
                        v-show="tableData.length > 0"
                        v-model="filterForm.checked"
                        @change="handleChecked"
                        style="margin-left: 7px;"
                    >盘盈亏操作</el-checkbox>
                    <div style="float:right; text-align: right;">
                        <!-- <span v-show="difference" style="margin-left: 5px; color: #f56c6c;" v-if="filterForm.checked">根据库存量推算：{{ difference < 0 ? '不需要均摊': '需要均摊'+ difference.toFixed(2)}}</span> -->
                        <el-button
                            class="button"
                            type="primary"
                            size="mini"
                            icon="el-icon-search"
                            
                            v-privilege="activeMenu + 'QUERY'"
                            @click="getTableData(1)"
                        >查询</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="filterForm.checked ? '500px' :singleTableHeight"
                        border
                        size="mini"
                        highlight-current-row
                        show-summary
                        :summary-method="getSummaries">
                    >
                        <!-- <el-table-column
                            sortable
                            type="selection"
                            width="40"
                            align="center"
                            fixed="left"
                        >
                        </el-table-column> -->
                        <el-table-column
                            sortable
                            prop="seq"
                            width="70px"
                            label="序号"
                            align="center"
                            fixed="left"
                            v-if="filterForm.seqshow"
                        >
                        </el-table-column>
                        <el-table-column
                            sortable
                            prop="timegranid"
                            width="70px"
                            label="timegranid"
                            align="center"
                            fixed="left"
                            v-if="filterForm.seqshow"
                        >
                        </el-table-column>
                        <el-table-column
                        sortable
                            prop="clock"
                            label="时间"
                            min-width="100px"
                            :show-overflow-tooltip="true"
                            align="center"
                        ></el-table-column>
                        <el-table-column
                        sortable
                            prop="itemid"
                            label="项目编号"
                            min-width="100px"
                            align="center"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                        sortable
                            prop="workprocid"
                            label="工序"
                            align="center"
                            min-width="100px"
                            :show-overflow-tooltip="true"
                        >
                            <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="productid"
                            label="产品"
                            align="center"
                            min-width="100px"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <span>{{ nameObj.productid.obj[scope.row.productid] ? nameObj.productid.obj[scope.row.productid] : scope.row.productid }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                        sortable
                            prop="apportvalue"
                            label="生产量"
                            align="center"
                            min-width="150px"
                            :show-overflow-tooltip="true"
                        >
                        </el-table-column>
                         <el-table-column
                        sortable
                            prop="jtz"
                            label="盈亏量"
                            align="center"
                            min-width="150px"
                            :show-overflow-tooltip="true"
                        >
                         <template slot-scope="scope">
                                <el-form-item
                                 v-if="filterForm.checked && scope.row.apportvalue != 0"
                                 :prop="scope.row.seq +'.jtz'"
                                >
                                    <el-input
                                    style="width: 100%;"
                                    v-model="tableFormDataObj[scope.row.seq].jtz"
                                    ></el-input>
                                </el-form-item>
                                <span v-else>{{scope.row.jtz}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                        sortable
                            prop="unitid"
                            label="单位"
                            min-width="100px"
                            align="center"
                            :show-overflow-tooltip="true"
                        >
                            <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>
                </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 class="box-xh" v-if="filterForm.checked">
                    <el-form
                    style="margin-left: 630px;"
                    size="mini"
                    label-width="100px"
                    >
                    <!-- <el-row>
                        <el-col :span="8">
                            <el-form-item label="">
                                <span  style="margin-left: 20px;">根据库存量推算:{{difference}}</span>
                            </el-form-item>
                        </el-col>
                    </el-row> -->
                     <el-row>
                        <el-col :span="6">
                            <el-form-item label="盈亏量:">
                                <el-input clearable
                                    v-model="filterForm.data.kcl"
                                    placeholder=""
                                ></el-input> 
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-button
                                class="button"
                                type="primary"
                                size="mini"
                                icon="el-icon-refresh"
                                @click="againCount2()"
                                >自动均摊</el-button>
                        </el-col>
                        <el-col :span="2">
                             <el-button
                            class="button"
                            type="primary"
                            size="mini"
                            icon="el-icon-save"
                            @click="but_more()"
                        >保存</el-button>
                        </el-col>
                    </el-row>
                    </el-form>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import timegranDate from '~/components/zg/timegranDate.vue'
import {formatDate, XtcommonSummaries} from '@/utils/util.js';
export default {
    name: 'processAndRawMaterials',
    components: {
        'zj-timegran-date': timegranDate
    },
    data () {
        return {
            activeMenu: '',
            filterForm: {
                show: true,
                checked: false,
                seqshow: false,
                difference: 0,
                data: {
                    timegranid: '',
                    clock: '',
                    productid: '',
                    workprocid: '',
                    itemid: '',
                    kcl: ''
                },
                rules: {

                }
            },
            pageNum: 1,
            pageSize: 20,
            total: 0,
            singleTableHeight: 0,
            tableData: [
                // {
                //     clock: '',
                //     itemid: '010000C001R',
                //     timegranid: '',
                //     workprocid: '球团',
                //     materialid: '混合矿',
                //     actualvalue: '0',
                //     correctvalue: '0',
                //     apportvalue: '0',
                //     stdvalue: '0',
                //     sumvalue: '0',
                //     ucvalue: '0',
                //     sumucvalue: '0',
                //     unitid: '吨',
                //     bz: ''
                // }
            ],
            nameObj: {
                timegranid: {
                    obj: {},
                    arr: []
                },
                productid: {
                    obj: {
                        //'CP010':{name:'白灰粉'}
                        },
                    arr: [
                        //{id:'CP010',name:'白灰粉'}
                    ]
                },
                workprocid: {
                    obj: {},
                    arr: []
                },
                unitid: {
                    obj: {},
                    arr: []
                }
            },
            loading: false,
            tableLoading: false,
            dialog: {
                editorBox: {
                    show: false,
                    type: '',
                    form: {
                        data: {
                            clock: '',
                            itemid: '',
                            timegranid: '',
                            actualvalue: '',
                            correctvalue: '',
                            apportvalue: '',
                            kcl: ''
                        },
                        rules: {

                        }
                    }
                }
            },
            multipleSelection: [],
            tableFormDataObj: {}
        }
    },
    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);
        });
        //接收路由参数
        // if (that.$route.query.workprocid == 'jc') {
        //     that.nameObj.workprocid = {
        //              obj:{
        //                  'AT3011':{
        //                      name: '1#回转窑'
        //                 },
        //                  'AT3012': {
        //                      name: '2#回转窑'
        //                  }
        //              },
        //              arr:[
        //                  {id:'AT3011', name:'1#回转窑'},
        //                  {id:'AT3012', name:'2#回转窑'}
        //              ]
        //              }
        //               that.filterForm.data.workprocid ='AT3011';        
        // }
        // if(that.$route.query.workprocid == 'jj'){
        //    that.nameObj.workprocid = {
        //              obj:{
        //                  'AT2017':{
        //                      name: '炼焦'
        //                 }
        //              },
        //              arr:[
        //                  {id:'AT2017', name:'炼焦'}
        //              ]
        //              }
        //               that.filterForm.data.workprocid ='AT2017';  
        // }
        if (that.$route.query.productid) {
             that.filterForm.data.productid = that.$route.query.productid;
        }
        if(that.$route.query.workprocid){
            console.log(that.$route.query.workprocid);
            that.filterForm.data.workprocid = that.$route.query.workprocid;
        }
        that.getTimeGranData();
        that.getProductIdData();
        that.getWorkprocIdData();
        that.getUnitIdData();
        //that.getTableData();
    },
    methods: {
        //  计算树区域高度
        getRoleHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        // 自定义的表格合计方法：只给指定列进行合计
        getSummaries (param) {
            let that = this;
            const prop = ['actualvalue', 'correctvalue', 'apportvalue', 'jtz']; // 合计列绑定的prop
            let sum = XtcommonSummaries(param, prop);
            that.difference = sum[4] - sum[5];
            that.filterForm.data.kcl = sum[5];
             return XtcommonSummaries(param, prop);
        },
        // 获取时间粒度(工序与原材料数据维护)
        getTimeGranData () {
            let that = this
            let url = 'pass/ems/v1/tcmdatasourcetimegrans/getTimegranRmWorkprocMaterialValue';
            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.filterForm.data.timegranid = that.filterForm.data.timegranid ? that.filterForm.data.timegranid : item.ID;
                        }
                        that.nameObj.timegranid.arr = arr;
                        that.nameObj.timegranid.obj = obj;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        // 获取产品
        getProductIdData () {
            let that = this
            let url = 'pass/ems/v1/trmproducts/getDataForPk'
            let params = {
                productid: that.filterForm.data.productid
            };
            that.axios.get(url,{
                params: params
            })
                .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.productid.arr = arr;
                        that.nameObj.productid.obj = obj;
                        that.filterForm.data.productid = that.nameObj.productid.arr[0].id;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        // 获取工序(产出)
        getWorkprocIdData () {
            let that = this
            let params = {
                workprocid: that.filterForm.data.workprocid
            };
            let url = 'pass/ems/v1/trmworkprocs/getDataForPk';
            that.axios.get(url,{
                params: params
            })
                .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;
                        that.filterForm.data.workprocid = that.nameObj.workprocid.arr[0].id;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        //是否选中
        handleChecked(val){
          let that = this;
          if (val) {
             that.againCount();
          }else {
           that.getTableData();
           that.tableFormDataObj = {};
          }
        },
        // 获取标准计量单位
        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;
                            if (item.name === '吨') {
                                that.nameObj.unitid.defaults = that.nameObj.unitid.defaults ? that.nameObj.unitid.defaults : item.id;
                            }
                        }
                        that.nameObj.unitid.arr = arr;
                        that.nameObj.unitid.obj = obj;
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        //先把消耗值为0或者为空的剔除掉
        againCount(){
            let that = this;
            let tableFormDataObj = {};
            //  for (let item of that.tableData) {
            //      let obj = {};
            //      let xId = item.itemid;
            //      if(item.apportvalue != 0){
            //        if (that.tableFormDataObj[xId]) {
            //         tableFormDataObj[xId] = that.tableFormDataObj[xId];
            //       } 
            //  else {
            //      for (let key in item) {
            //              obj[key] = item[key];
            //         }
            //         tableFormDataObj[xId] = obj;
            //     }
            //      }
            //  }
            for (let item of that.tableData) {
                 let obj = {};
                 let xId = item.seq;
                 if(item.apportvalue != 0){
                   if (that.tableFormDataObj[xId]) {
                    tableFormDataObj[xId] = that.tableFormDataObj[xId];
                  } 
             else {
                 for (let key in item) {
                         obj[key] = item[key];
                    }
                    tableFormDataObj[xId] = obj;
                }
                 }
             }
             that.tableFormDataObj = tableFormDataObj;
        },
        //自由均摊
        againCount2(){
        let that =this;
           let ids = [];
            for(let i = 0; i < that.tableData.length; i++){
             if(that.tableFormDataObj[that.tableData[i].seq]){
                   ids.push({
                       id:i
                   })
             }
            }
            let lengths = ids.length;
            var sum = 0;
            for(let i = 0; i < lengths; i++){
                if(i === (lengths-1)){
                let ys = that.floatComputed(that.filterForm.data.kcl,sum,"-");
                that.tableData[ids[i].id].jtz = ys.toFixed(4);
                }
                else {
                     let avgvalue = (that.filterForm.data.kcl/lengths).toFixed(4);//that.floatComputed(that.filterForm.data.kcl,lengths,"/");
                     that.tableData[ids[i].id].jtz = avgvalue;
                     sum += that.floatComputed(avgvalue,0,"+");
                 }
                 that.tableFormDataObj = {};
                 that.againCount();
             }

        },
        // 获取表格中的数据
        getTableData (pageNum) {
            let that = this;
            let params = {};
                params = {
                    timegranid: that.filterForm.data.timegranid,
                    clock: that.filterForm.data.clock,
                    productid: that.filterForm.data.productid.toString(),
                    workprocid: that.filterForm.data.workprocid.toString(),
                };
            that.pageNum = pageNum || that.pageNum;
            that.tableLoading = true;
            let url = 'pass/ems/v1/trmworkprocproductvalues/getpkdata';
            that.axios.get(url, {
                params: params
            })
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                         for (let i = 0; i < res.data.list.length; i++) {
                             let item = res.data.list[i];
                            arr.push({
                                seq: item.ITEMID+item.CLOCK,
                                clock: item.CLOCK,
                                itemid: item.ITEMID,
                                timegranid: item.TIMEGRANID,
                                workprocid: item.WORKPROCID,
                                productid: item.PRODUCTID,
                                actualvalue: item.ACTUALVALUE,
                                correctvalue: item.CORRECTVALUE,
                                apportvalue: item.APPORTVALUE,
                                jtz:item.JTZ,
                                stdvalue: item.stdvalue,
                                sumvalue: item.SUMVALUE,
                                ucvalue: item.UCVALUE,
                                sumucvalue: item.SUMUCVALUE,
                                unitid: item.UNITID,
                                bz: item.BZ
                            })
                        }
                        that.tableData = arr;
                        that.total = res.data.total;
                        that.filterForm.checked = false;
                    } 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.timegranid = '';
            that.filterForm.data.clock = '';
            that.filterForm.data.workprocid = '';
            that.filterForm.data.materialid = '';
            that.filterForm.data.itemid = '';
            that.getTableData(1);
        },
        but_edit (row) {
            let that = this;
            that.dialog.editorBox.form.data.itemid = row.itemid;
            that.dialog.editorBox.form.data.clock = row.clock;
            that.dialog.editorBox.form.data.timegranid = row.timegranid;
            that.dialog.editorBox.form.data.actualvalue = row.actualvalue;
            that.dialog.editorBox.form.data.correctvalue = row.correctvalue;
            that.dialog.editorBox.form.data.apportvalue = row.apportvalue;
            that.dialog.editorBox.type = 'edit';
            that.dialog.editorBox.show = true;
        },
        // 修改多条数据
        but_more () {
            let that = this;
            let url = 'pass/ems/v1/trmworkprocproductvalues/updatecc';
            let submitData = [];
            for (let item in that.tableFormDataObj) {
                submitData.push({
                    itemid: that.tableFormDataObj[item].itemid,
                    clock: that.tableFormDataObj[item].clock,
                    timegranid: that.tableFormDataObj[item].timegranid,
                    jtz: that.tableFormDataObj[item].jtz
                })
            }
            that.axios.put(url, submitData)
                .then(function (res) {
                    if (res.code === '0') {
                        that.$message({
                            message: '保存成功',
                            type: 'success'
                        });
                        that.filterForm.checked = false;
                        that.getTableData();
                    } else {
                        that.$message.error(res.message);
                    }
                    that.loading = false;
                }).catch(function () {
                    that.loading = false;
                });
        }
    }
}
function sortNumber (a, b) {
  return a - b
}
</script>

<style lang="less">
.processAndRawMaterials {
    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;
        }
    }
}
.box-xh {
    min-width: 700px;
    height: 100px;
    text-align: center;
}
</style>
