<template>
  <!-- 盘库管理-新 2022-07-12 -->
  <div class="Inventory">
    <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%;" :type="'daterange'"
                  timegranId='MONTH' :oneFoo="getTableData" :defaultOffset="-1"></zj-timegran-date>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料">
                <el-select filterable clearable multiple collapse-tags v-model="filterForm.data.materialid"
                  placeholder="" style="width: 100%;">
                  <el-option v-for="item of materialidChange" :key="item.id" :value="item.id" :label="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="工序">
                <el-select 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-col :span="6">
              <el-form-item label="项目编号">
                <el-input clearable v-model="filterForm.data.itemid" placeholder="" style="width: 100%;"
                  @keyup.enter.native="getTableData(1)"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="box-top-gjl">
          <el-button class="button" type="primary" size="mini" icon="el-icon-save" v-privilege="activeMenu + 'PUT'"
            @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.arr" v-loading="tableLoading"
            style="width: 100%;" :height="singleTableHeight" border size="mini" highlight-current-row show-summary
            :summary-method="getSummaries" @selection-change="handleSelectionChange" @cell-click="cellClick" :row-class-name="tableRowClassName">
            >
            <el-table-column sortable type="selection" width="40" align="center" fixed="left">
            </el-table-column>
            <el-table-column sortable prop="timegranid" label="时间粒度" min-width="100px" :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="时间" min-width="100px" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column sortable prop="itemid" label="项目编号" min-width="100px" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column sortable prop="workprocid" label="工序" 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="materialid" label="物料" min-width="100px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ nameObj.materialid.obj[scope.row.materialid] ? nameObj.materialid.obj[scope.row.materialid] : scope.row.materialid }}</span>
              </template>
            </el-table-column>
            <el-table-column sortable prop="TABLENAME" label="类别" min-width="100px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ nameObj.TABLENAME.obj[scope.row.TABLENAME] ? nameObj.TABLENAME.obj[scope.row.TABLENAME] : scope.row.TABLENAME }}</span>
              </template>
            </el-table-column>
            <el-table-column sortable prop="apportvalue" label="最终值" min-width="150px" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column sortable prop="JTZ" label="盘库值" min-width="150px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-form-item :prop="scope.row.seq + '.JTZ'" v-if="scope.row.isSelection"
                  :rules="dialog.editorBox.form.rules.JTZ">
                  <el-input clearable style="width: 90%;" v-model="tableFormDataObj[scope.row.seq].JTZ" refcous="true"
                    @keydown.native="keyDown" :id="scope.$index + scope.column.id"></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.JTZ}}</span>
              </template>
            </el-table-column>
            <el-table-column sortable prop="unitid" label="单位" min-width="100px" :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-column sortable prop="bz" label="备注" min-width="100px" :show-overflow-tooltip="true"><template
                slot-scope="scope">
                <el-form-item :prop="scope.row.seq + '.bz'" v-if="scope.row.isSelection">
                  <el-input clearable style="width: 90%;" v-model="tableFormDataObj[scope.row.seq].bz" refcous="true"
                    @keydown.native="keyDown" :id="scope.$index + scope.column.id"></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.bz}}</span>
              </template></el-table-column>
            <el-table-column sortable prop="USERID" label="创建人" min-width="100px" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column sortable prop="UPDATETIME" label="创建时间" min-width="100px" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column sortable prop="UPMAN" label="更新人" min-width="100px" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column sortable prop="UPTIME" label="更新时间" min-width="100px" :show-overflow-tooltip="true">
            </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>
  </div>
</template>

<script>
  import timegranDate from '~/components/zg/timegranDate.vue'
  import {
    formatDate,
    XtcommonSummaries
  } from '@/utils/util.js';
  import {
    zCheckNumber1
  } from '~/utils/validator.js'
  export default {
    name: 'Inventory',
    components: {
      'zj-timegran-date': timegranDate
    },
    data() {
      return {
        activeMenu: '',
        seqArr: [],
        rowIndex: '',
        columnId: '',
        focusTarget: null,
        editSetFlag: '',
        filterForm: {
          show: true,
          data: {
            timegranid: 'MONTH',
            clock: '',
            materialid: '',
            workprocid: '',
            changWorkprocid: '',
            changMaterialid: '',
            itemid: ''
          },
          rules: {

          }
        },
        pageNum: 1,
        pageSize: 20,
        total: 0,
        singleTableHeight: 100,
        tableData: {
          obj: {},
          arr:[]
        },
        nameObj: {
          timegranid: {
            obj: {
              'DAY': '日',
              'MONTH': '月',
              'YEAR': '年',
            },
            arr: [{
                id: 'DAY',
                name: '日'
              },
              {
                id: 'MONTH',
                name: '月'
              },
              {
                id: 'YEAR',
                name: '年'
              }
            ]
          },
          materialid: {
            obj: {},
            arr: []
          },
          workprocid: {
            obj: {},
            arr: []
          },
          unitid: {
            obj: {},
            arr: []
          },
          TABLENAME: {
            obj: {
              'T_RM_WORKPROC_MATERIAL_VALUE': '投入',
              'T_RM_WORKPROC_PRODUCT_VALUE': '产出'
            },
            arr: [{
                id: 'T_RM_WORKPROC_MATERIAL_VALUE',
                name: '投入'
              },
              {
                id: 'T_RM_WORKPROC_PRODUCT_VALUE',
                name: '产出'
              },
            ]
          }
        },
        loading: false,
        tableLoading: false,
        dialog: {
          editorBox: {
            show: false,
            type: '',
            form: {
              data: {
                clock: '',
                itemid: '',
                timegranid: '',
                actualvalue: '',
                correctvalue: '',
                apportvalue: ''
              },
              rules: {
                JTZ: [{
                    required: true,
                    message: '该项不能为空',
                    trigger: 'change'
                  },
                  {
                    validator: zCheckNumber1,
                    trigger: 'change'
                  }
                ],
              }
            }
          }
        },
        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.materialid) {
           that.filterForm.data.changMaterialid = that.$route.query.materialid;
      }
      if(that.$route.query.workprocid){
          that.filterForm.data.changWorkprocid = that.$route.query.workprocid;
      }
      that.getMaterialIdData();
      that.getProductIdData();
      that.getWorkprocIdData();
      that.getUnitIdData();
      // that.getTableData();
    },
    computed: {
      materialidChange () {
        let that = this;
        let Tdata = [];
        Tdata = that.nameObj.materialid.arr;
        let arr = [];
        let partArr = that.filterForm.data.changMaterialid.split(',');
        if(that.filterForm.data.changMaterialid !== '') {
          for(let item of partArr) {
            arr.push({
              id: item,
              name: that.nameObj.materialid.obj[item]
            })
          }
          that.nameObj.materialid.arr = arr;
        }
        return that.nameObj.materialid.arr;
      },
      workprocidChange () {
        let that = this;
        let Tdata = [];
        Tdata = that.nameObj.workprocid.arr;
        for(let item of that.filterForm.data.changWorkprocid.split(",")) {
          Tdata = Tdata.filter(data => !item || data.id.toLowerCase()
            .includes(item.toLowerCase()));
        }
        return Tdata;
      }
    },
    methods: {
      //  计算树区域高度
      getRoleHeight(dom) {
        return window.innerHeight - dom.offsetTop;
      },
      // 自定义的表格合计方法：只给指定列进行合计
      getSummaries(param) {
        const prop = ['apportvalue', 'JTZ']; // 合计列绑定的prop
        return XtcommonSummaries(param, prop);
      },
      // 获取原材料
      getMaterialIdData() {
        let that = this
        let url = 'pass/ems/v1/trmmaterials/?pageSize=1000000';
        that.axios.get(url)
          .then(function(res) {
            if (res.code === '0') {
              let arr = [];
              let obj = {};
              for (let item of res.data.list) {
                that.nameObj.materialid.arr.push({
                  id: item.id,
                  name: item.name
                })
                that.nameObj.materialid.obj[item.id] = item.name;
              }
            } else {
              that.$message.error(res.message);
            }
          });
      },
      // 获取产品
      getProductIdData() {
        let that = this
        let url = 'pass/ems/v1/trmproducts/?pageSize=1000000';
        that.axios.get(url)
          .then(function(res) {
            if (res.code === '0') {
              let arr = [];
              let obj = {};
              for (let item of res.data.list) {
                that.nameObj.materialid.arr.push({
                  id: item.id,
                  name: item.name
                })
                that.nameObj.materialid.obj[item.id] = item.name;
              }
            } else {
              that.$message.error(res.message);
            }
          });
      },
      // 获取工序
      getWorkprocIdData() {
        let that = this
        let url = 'pass/ems/v1/trmworkprocs/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(that.filterForm.data.changWorkprocid != '') {
                arr = [];
                for(let item of that.filterForm.data.changWorkprocid.split(',')) {
                  arr.push({
                    id: item,
                    name: obj[item]
                  })
                }
              }
              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;
                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);
            }
          });
      },
      // 获取表格中的数据
      getTableData(pageNum) {
        let materialid = '',workprocid = '';
        materialid = this.filterForm.data.materialid.toString();
        workprocid = this.filterForm.data.workprocid.toString();
        if(materialid === '' && this.filterForm.data.changMaterialid !== '') {
          materialid = this.filterForm.data.changMaterialid.toString();
        }
        if(workprocid === '' && this.filterForm.data.changWorkprocid !== '') {
          workprocid = this.filterForm.data.changWorkprocid.toString();
        }
        let that = this,
          params = {
            timegranid: that.filterForm.data.timegranid,
            startDate: that.filterForm.data.clock[0],
            endDate: that.filterForm.data.clock[1],
            materialid: materialid,
            workprocid: workprocid,
            itemid: that.filterForm.data.itemid
          };
        that.pageNum = pageNum || that.pageNum;
        that.tableLoading = true;
        let url = 'pass/ems/v1/ifmesemsswapfile/queryWorkprocInventory/?pageNum=' + that.pageNum + '&pageSize=' + that
          .pageSize;
        that.axios.get(url, {
            params: params
          })
          .then(function(res) {
            if (res.code === '0') {
              let arr = [],obj = {};
              let seq = 0;
              for (let item of res.data.list) {
                arr.push({
                  clock: item.CLOCK,
                  itemid: item.ITEMID,
                  timegranid: item.TIMEGRANID,
                  workprocid: item.WORKPROCID,
                  materialid: item.CODE,
                  actualvalue: item.ACTUALVALUE,
                  correctvalue: item.CORRECTVALUE,
                  apportvalue: item.APPORTVALUE,
                  JTZ: item.JTZ,
                  unitid: item.UNITID,
                  bz: item.BZ,
                  USERID: item.USERID,
                  UPDATETIME: item.UPDATETIME,
                  UPTIME: item.UPTIME,
                  UPMAN: item.UPMAN,
                  TABLENAME: item.TABLENAME,
                  seq: seq
                });
                obj[item.CLOCK + item.ITEMID] = {
                  clock: item.CLOCK,
                  itemid: item.ITEMID,
                  timegranid: item.TIMEGRANID,
                  workprocid: item.WORKPROCID,
                  materialid: item.CODE,
                  actualvalue: item.ACTUALVALUE,
                  correctvalue: item.CORRECTVALUE,
                  apportvalue: item.APPORTVALUE,
                  JTZ: item.JTZ,
                  unitid: item.UNITID,
                  bz: item.BZ,
                  USERID: item.USERID,
                  UPDATETIME: item.UPDATETIME,
                  UPTIME: item.UPTIME,
                  UPMAN: item.UPMAN,
                  TABLENAME: item.TABLENAME,
                  seq: seq
                };
                seq++;
              }
              that.tableData.arr = arr;
              that.tableData.obj = obj;
              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.itemid = '';
        that.filterForm.data.materialid = [];
        that.filterForm.data.workprocid = [];
        // 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.arr) {
          item.isSelection = false;
        }
        for (let item of val) {
          let obj = {};
          let xId = item.seq;
          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;
      },
      // 修改多条数据
      but_more() {
        let that = this;
        let url = 'pass/ems/v1/ifmesemsswapfile/updateWorkprocInventory/';
        let submitData = [],sumVal = 0,clock = '';
        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,
            bz: that.tableFormDataObj[item].bz,
            tableName: that.tableFormDataObj[item].TABLENAME
          })
          if(that.tableFormDataObj[item].itemid === 'AT2004CP003R') {
            if(sumVal > 0) {
              sumVal = sumVal - Number(that.tableData.obj[that.tableFormDataObj[item].clock + 'AT2004CP003R'].JTZ) + Number(that.tableFormDataObj[item].JTZ);
            } else{
              sumVal = Number(that.tableFormDataObj[item].JTZ) + Number(that.tableData.obj[that.tableFormDataObj[item].clock + 'AT2004CP002R'].JTZ);
            }
            clock = that.tableFormDataObj[item].clock;
          }
          if(that.tableFormDataObj[item].itemid === 'AT2004CP002R') {
            if(sumVal > 0) {
              sumVal = sumVal - Number(that.tableData.obj[that.tableFormDataObj[item].clock + 'AT2004CP002R'].JTZ) + Number(that.tableFormDataObj[item].JTZ);
            } else{
            sumVal = Number(that.tableFormDataObj[item].JTZ) + Number(that.tableData.obj[that.tableFormDataObj[item].clock + 'AT2004CP003R'].JTZ);
            }
            clock = that.tableFormDataObj[item].clock;
          }
        }
        if(sumVal > 0) {
          submitData.push({
            itemid: 'AT2004CP054R',
            clock: clock,
            timegranid: that.filterForm.data.timegranid,
            JTZ: sumVal,
            bz: that.tableData.obj[clock + 'AT2004CP054R'].bz,
            tableName: that.tableData.obj[clock + 'AT2004CP054R'].TABLENAME
          })
        }
        that.axios.put(url, 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;
          });
      },
      tableRowClassName ({row, rowIndex}) {
        // 把每一行的索引放进row
        row.index = rowIndex;
      },
      cellClick (row, column, cell, event) {
          let _this = this;
          this.rowIndex = row.index;
          this.columnId = column.id;
          _this.editSetFlag = column.id + row.index;
          _this.focusTarget = event.target;
          while (_this.focusTarget.tagName !== 'TD') {
              _this.focusTarget = _this.focusTarget.parentElement;
          }
          _this.$nextTick(() => {
              let target = this.focusTarget;
              $(target).find('input').focus();
          });
      },
      keyDown(event1, disabledFlag) {
        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;
          this.$nextTick(() => {
            $(id).click();
          });
        } else if (event.keyCode === 38) { // 键盘上键
          let index = parseInt(this.rowIndex);
          if (index !== this.seqArr[0]) {
            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;
          this.$nextTick(() => {
            $(id).click();
          });
        } else if (event.keyCode === 37) { // 键盘左键
          $(tdTarget).prevAll().find('input:text').last().click();
        } else if (event.keyCode === 39) { // 键盘右键
          $(tdTarget).nextAll().find('input').eq(0).click();
        }
      },
    }
  }

  function sortNumber(a, b) {
    return a - b
  }
</script>

<style lang="less">
  .Inventory {
    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>
