<template>
<!-- 批量采集 -->
  <div class="examination_dataCollection">
    <el-dialog :close-on-click-modal='false' @close="CollectionCancel" width='100%' :visible.sync="collectionShow" top="0">
        <div slot="title" class="titleBox">
        <i class='el-icon-document' style="font-size: 20px"></i>
        <span style="margin-left:10px;font-size:18px;margin-right:20px" >数据采集</span>
        </div>
        <el-form :inline='true' :model="collet" ref="collet" :rules='ruleData'>
          <el-form-item prop='eqpTypeCode' label='设备类型'>
            <el-select v-model="collet.eqpTypeCode" @change='selectFaclity' filterable collapse-tags size="small" style="width:160px;" placeholder="">
              <el-option
              v-for="item in facilityType"
              :key="item.baseCode"
              :label="item.baseName"
              :value="item.baseCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop='eqpNo' label='设备名称'>
            <el-select v-model="collet.eqpNo" clearable filterable collapse-tags size="small" style="width:360px;" placeholder="">
              <el-option
              v-for="item in eqpType"
              :key="item.eqpNo"
              :label="item.eqpName + ` (${item.eqpUseNo})`"
              :value="item.eqpNo">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop='stateFlags' label='状态'>
            <el-select v-model="collet.stateFlags" multiple clearable filterable  placeholder="" size="small">
              <el-option
                v-for="item in stateFlagList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item prop='stateFlags1' label='去重'>
            <el-select v-model="collet.stateFlags1" multiple clearable filterable  placeholder="" size="small">
              <el-option
                v-for="item in stateFlagList1"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label='采集时间'>
            <el-date-picker
              v-model="collet.times"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              style="width:300px"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              :default-time="['00:00:00','23:59:59']">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="goon" size="mini" @click="searchcollection">查询</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter='10'>
          <el-col :span='14'>
            <div class="common-title-name">
              <img style="width: 25px; height: 25px; margin-left: 20px" src='../../../../assets/img/imgScreen/logo.png' />
              <span>数据采集</span>
              <span style="margin:0 0 0 20px;">选中行数:</span> <span prop="">{{Numberows}}</span>
            </div>
            <el-table ref="dataTable" v-loading='collectionLoading' border :height="heightTop" :icore-filter-flag="icoreFilterFlag"
            @selection-change="SelectionCllotData" highlight-current-row :data="table.collectionData"
            :header-cell-style="tableHeaderCellStyle" :summary-method="getSummaries2" show-summary>
              <el-table-column type="index" label="NO" width="45" fixed="left" align="center"></el-table-column>
              <el-table-column type="selection" width="45" fixed="left" align="center"></el-table-column>
              <el-table-column sortable width="45" prop="seq" label="序号" fixed="left" align="center"></el-table-column>
              <el-table-column sortable width="45" prop="stateFlagName" label="状态" fixed="left" align="center"></el-table-column>
              <el-table-column sortable min-width="85px" show-overflow-tooltip prop="collSampleNo" label="采集样号" fixed="left" align="center"></el-table-column>
              <el-table-column width="80px" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" style="padding:0" @click="copyData(scope.row, scope.$index)">复制</el-button>
                  <el-button type="text" style="padding:0" @click="delData(scope.row, scope.$index)">删除</el-button>
                </template>
              </el-table-column>
              <template v-for="col in cols">
	              <el-table-column sortable
                  v-if="col.prop !='collId' && col.prop !='collSampleNo' && col.prop !='createTime' && col.prop !='stateFlagName'"
                  :prop="col.prop" show-overflow-tooltip min-width="100" align='center' :key="col.prop" :label="col.label">
                  <template slot-scope="scope">
                    <el-checkbox @change="changeCheckBox(scope.$index, col.prop, $event)" :key="col.prop">{{table.collectionData[scope.$index][col.prop]}}</el-checkbox>
                  </template>
                </el-table-column>
	            </template>
              <el-table-column sortable min-width="120px" show-overflow-tooltip prop="createTime" label="采集时间" align="center"></el-table-column>
              <el-table-column width="80px" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" style="padding:0" @click="moveUp(scope.row, scope.$index)">上移</el-button>
                  <el-button type="text" style="padding:0" @click="moveDw(scope.row, scope.$index)">下移</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 20px; margin-left: 10px">
              <el-pagination  @size-change="SizeTest" @current-change="pageChangeTest"
                :current-page="pageTests.pageNum" :page-sizes="[100, 200, 500, 800,1000]" :page-size="pageTests.pageSize" layout="total, sizes, prev, pager, next"
                :total="pageTests.totalPage" background>
              </el-pagination>
            </div>
          </el-col>
          <!-- <el-col :span='8'>
            <div class="common-title-name">
              <img style="width: 25px; height: 25px; margin-left: 20px" src='../../../../assets/img/imgScreen/logo.png' />
              <span>采集信息</span>
            </div>
            <el-table border :height="heightTop" v-loading='collectLoading' highlight-current-row :data="tableData"
            :header-cell-style="tableHeaderCellStyle" :summary-method="getSummaries2" show-summary>
              <el-table-column type="index" label="NO" align="center"></el-table-column>
              <el-table-column width="120px" show-overflow-tooltip label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" style="padding:0" :disabled="scope.$index == 0" @click="moveUpward(scope.row, scope.$index)">上移</el-button>
                  <el-button type="text" style="padding:0" :disabled="(scope.$index + 1) == table.selectCollectionData.length" @click="moveDown(scope.row, scope.$index)">下移</el-button>
                  <el-button type="text" style="padding:0" @click="moveleft(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
              <template v-for="col in cols">
	              <el-table-column :prop="col.prop" show-overflow-tooltip min-width="100" align='center' :key="col.prop" :label="col.label">
                </el-table-column>
	            </template>
            </el-table>
          </el-col> -->
          <el-col :span='10'>
            <div class="common-title-name">
              <img style="width: 25px; height: 25px; margin-left: 20px" src='../../../../assets/img/imgScreen/logo.png' />
              <span>样品信息</span>
            </div>
            <el-table ref="dataTable2" border :height="heightTop" :data="table.sampleData"
            :summary-method="getSummaries2" show-summary :row-style="styleRow"
            :header-cell-style="tableHeaderCellStyle">
             <el-table-column type="index" label="NO" align="center"></el-table-column>
             <el-table-column width="50px" show-overflow-tooltip label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" style="padding:0" @click="delData2(scope.row, scope.$index)">删除</el-button>
                </template>
              </el-table-column>
              <el-table-column sortable min-width="130px" show-overflow-tooltip prop="sampleNo" label="样号" align="center"></el-table-column>
              <el-table-column sortable min-width="130px" show-overflow-tooltip prop="carNo" label="委托编号" align="center"></el-table-column>
             <el-table-column sortable min-width="120px" show-overflow-tooltip prop="matName" label="物料名称" align="center"></el-table-column>
             <el-table-column sortable min-width="210px" show-overflow-tooltip prop="testItemName" label="任务名称" align="center"></el-table-column>
             <el-table-column sortable min-width="90px" show-overflow-tooltip prop="testOrder" label="测试顺序" align="center"></el-table-column>
            </el-table>
          </el-col>
        </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="goon" size="mini" :loading='addCollectionLoading' icon="el-icon-check" @click="addCollection()">确定</el-button>
        <el-button size="mini" type="goon" icon="el-icon-remove-outline" @click="CollectionCancel">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getCookie } from "@/utils/util.js";
import { cookieUserId, cookieUserName } from "@/config/config.js";
let userName = getCookie(cookieUserName);
let userId = getCookie(cookieUserId);
export default {
  props: ["showFlag", "Params2"],
  data() {
    return {
      collectionShow: false,
      addCollectionLoading:false,
      taskDataLoading:false,
      icoreFilterFlag: true,
      addtestLoading:false,
      collectionLoading:false,
      collectLoading:false,
      cols:[],
      tableData:[],
      saveColsData:[],
      resultData:[],
      eqpType:[],
      Numberows:'',
      ruleData: {
        eqpTypeCode: [{ required: true, message: '不能为空', trigger: 'change' },],
        eqpNo: [{ required: true, message: '不能为空', trigger: 'change' }],
      },
      facilityType:[],
      collet:{
        eqpTypeCode:'',
        eqpNo:'',
        times:'',
        stateFlags: ['0'],
        stateFlags1: ['1']
      },
      stateFlagList: [
        {label: '未读', value: '0'},
        {label: '已读', value: '1'}
      ],
      stateFlagList1: [
        {label: '去重', value: '1'}
      ],
      dataLoading2:false,
      testItemName2:'',
      heightTop:0,
      stId:'',
      pageTests: {
        pageSize: 200,
        pageNum: 1,
        totalPage: 0
      },
      table:{
        sampleData:[],
        selectCollectionData:[],
      },
      cllotData: [], // 左表选中行
      addList:[],
      discards: []
    };
  },
  created(){
    this.heightTop = window.innerHeight - 255 < 249 ? 249 : window.innerHeight - 255
    this.axios.post("pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode",{validFlag:1,baseCode:4808}, {individualType: 'json'}).then(res => {
      this.facilityType = res.data
    })
    let now = new Date();
    let start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 6, 0, 0);
    let end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 0, 0);
    this.collet.times = [start, end]
  },
  mounted() {
  },
  methods: {
    getYNM(date) {
      let year = date.getFullYear().toString();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      return `${year}-${month}-${day}`;
    },
    getSummaries2(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
        }
        if (index === 1) {
          sums[index] = data.length;
        }
      });
      return sums;
    },
    selectFaclity(val){
        this.eqpType = []
        this.collet.clearFlag ? '' : this.collet.eqpNo = ''
        if (!val) {
          return
      }
      this.axios.post('pass/baseManagement/v1/limslrceqpinfos/queryeqpName',{eqpTypeCode:val},{individualType: 'json'}).then(res => {
        this.eqpType = res.data;
      })
    },
    //采集信息取消
    CollectionCancel(){
      this.collectionShow = false
      this.addCollectionLoading = false
      this.collectionLoading = false
      this.collectLoading = false
      this.table.sampleData = []
      this.saveColsData = []
      this.cols = []
      this.tableData = []
      this.table.selectCollectionData = []
      this.table.collectionData = []
      this.cllotData = []
    },
    //勾选数据采集信息数据
    SelectionCllotData(val){
      let that = this;
      that.Numberows = val.length;
      for (let item of that.table.collectionData) {
          item.seq = '';
      }
      for (let i = 0; i < val.length; i++) {
        val[i].seq = i+1;
      }
      that.cllotData = val
    },
    changeCheckBox(index, item, event) {
      if (event) {
        this.table.collectionData[index].discard.push(item)
      } else {
        let ind = this.table.collectionData[index].discard.indexOf(item);
        if (ind != -1) {
            this.table.collectionData[index].discard.splice(index, 1)
        }
      }
    },
    // 复制数据
    copyData (row, index) {
      let that = this;
      let rdata = Object.assign({}, row);
      that.table.collectionData.splice(index+1, 0, rdata);
    },
    // 删除数据（前端删除）
    delData (row, index) {
      let that = this;
      that.table.collectionData.splice(index, 1);
      let cindex = that.cllotData.indexOf(row);
      if(cindex >= 0){
        that.cllotData.splice(cindex, 1);
        // 触发勾选数据方法-SelectionCllotData，更新选中数、选中数据cllotData
        that.$refs.dataTable.toggleRowSelection(row, false);
      }
    },
    //上移
    moveUp(row, index) {
      let that = this;
      let seq = row.seq;
      let iarr = [];
      if(seq){
        if(seq == 1){
          that.$message({message: '已经是第一条，上移失败', type: 'warning'});
        } else {
          // 和上一条数据换位置
          that.cllotData[seq-1] = that.cllotData.splice(seq-2,1,that.cllotData[seq-1])[0];
          for (let i = 0; i < that.cllotData.length; i++) {
            iarr.push(that.table.collectionData.indexOf(that.cllotData[i]))
          }
          // console.log('iarr', iarr)
          that.$refs.dataTable.clearSelection();
          for(let j = 0; j < iarr.length; j++) {
            that.$refs.dataTable.toggleRowSelection(that.table.collectionData[iarr[j]], true);
          }
        }
      }else{
        that.$message({message: '请先勾选数据', type: 'warning'});
      }
    },
    //下移
    moveDw(row, index) {
      let that = this;
      let seq = row.seq;
      let iarr = [];
      console.log('that.cllotData.length', that.cllotData.length)
      if(seq){
        if(seq == that.cllotData.length){
          that.$message({message: '已经是最后一条，下移失败', type: 'warning'});
        } else {
          // 和下一条数据换位置
          that.cllotData[seq] = that.cllotData.splice(seq-1,1,that.cllotData[seq])[0];
          for (let i = 0; i < that.cllotData.length; i++) {
            iarr.push(that.table.collectionData.indexOf(that.cllotData[i]))
          }
          // console.log('iarr', iarr)
          that.$refs.dataTable.clearSelection();
          for(let j = 0; j < iarr.length; j++) {
            that.$refs.dataTable.toggleRowSelection(that.table.collectionData[iarr[j]], true);
          }
        }
      }else{
        that.$message({message: '请先勾选数据', type: 'warning'});
      }
    },
    // 删除样品信息（前端删除）
    delData2 (row, index) {
      let that = this;
      that.table.sampleData.splice(index, 1);
    },
    styleRow ({row, rowIndex}) {
      if (this.cllotData && this.cllotData.length > rowIndex) {
        return 'background-color: rgba(64, 158, 255, 0.3) !important;' // rgb(202,249,130,0.6)
      } else {
        return ''
      }
    },
    //查询采集数据
    searchcollection(){
      let startTime = ''
      let endTime = ''
      if (!this.collet.times) {
        startTime = ''
        endTime = ''
      }else{
        startTime = this.collet.times[0]
        endTime = this.collet.times[1]
      }
      this.$refs.collet.validate((valid) => {
        if (valid) {
          this.cols = []
          this.table.collectionData = []
          let obj = {
            object:{
              eqpTypeCode:this.collet.eqpTypeCode,
              eqpNo:this.collet.eqpNo,
            },
            list: this.collet.stateFlags,
            list2: this.collet.stateFlags1,
            startTime:startTime,
            endTime:endTime,
            pageIndex:this.pageTests.pageNum,
            pageSize:this.pageTests.pageSize
          }
          this.collectionLoading = true
          this.axios.post('pass/testManagement/v1/limsdatacollects/queryLimsDataCollect2',obj,{individualType: 'json'}).then(res =>{
            if (res.code == 0 || res.code == 200) {
              // console.log('res.data', res.data)
              this.table.collectionData = res.data.data.list
              this.pageTests.totalPage = res.data.data.total
              this.table.collectionData.forEach(item =>{
                item.stateFlagName = item.stateFlag == 0 ? '未读' : item.stateFlag == 1 ? '已读' : ''
                item.discard = []
              })
              this.cols = res.data.head
            }else{
              this.$message.error(res.message)
            }
            this.collectionLoading = false
          }).catch(err =>{
            this.collectionLoading = false
            this.$message.error(err.message)
          })
        }
      })
    },
    //右移
    moveRight(index,row){
      if (this.table.selectCollectionData.length >= this.table.sampleData.length ) {
        this.$message.warning('采集信息表中的数据不能超过样品信息表中的数据')
        return
      }
      // 在数据采集表中删除,添加到选中的采集信息表中
      for( let item of this.table.selectCollectionData){
        if (item.collId === row.collId) {
          this.$message.warning('采集信息表中已存在此数据！,请重新选择')
          return
        }
      }
      this.collectionLoading = true
      this.collectLoading = true
      this.axios.post('pass/testManagement/v1/limsdatacollectds/disposeData',row,{individualType: 'json'}).then(res =>{
        if (res.code == 0 || res.code == 200) {
          this.saveColsData.push(res.data.head)
          let tempArrLength = []
          this.saveColsData.map((item,index) =>{
            tempArrLength.push({leng:item.length,arrIndex:index})
          })
          tempArrLength.sort((a,b)=>{
            return b.leng - a.leng
          })
          this.$nextTick(()=>{
            this.cols = this.saveColsData.length ? this.saveColsData[tempArrLength[0].arrIndex] : []
          })
          this.tableData.push(res.data.badyData[0])
          this.table.selectCollectionData.push(row)
        }else{
          this.$message.error(res.message)
        }
        this.collectionLoading = false
        this.collectLoading = false
      }).catch(err =>{
        this.collectionLoading = false
        this.collectLoading = false
        this.$message.error(err.message)
      })
    },
    //上移
    moveUpward(row, index) {
      if (index > 0) {
          let upData = this.table.selectCollectionData[index - 1];
          this.table.selectCollectionData.splice(index - 1, 1);
          this.table.selectCollectionData.splice(index, 0, upData);
          let upColData = this.saveColsData[index - 1];
          this.saveColsData.splice(index - 1, 1);
          this.saveColsData.splice(index, 0, upColData);
          let upTableData = this.tableData[index - 1];
          this.tableData.splice(index - 1, 1);
          this.tableData.splice(index, 0, upTableData);
          let tempArrLength = []
          this.saveColsData.map((item,index) =>{
            tempArrLength.push({leng:item.length,arrIndex:index})
          })
          tempArrLength.sort((a,b)=>{
            return b.leng - a.leng
          })
          this.$nextTick(()=>{
            this.cols = this.saveColsData.length ? this.saveColsData[tempArrLength[0].arrIndex] : []
          })
      } else {
        this.$message({message: '已经是第一条，上移失败',type: 'warning'});
      }
    },
    //下移
    moveDown(row, index) {
      if ((index + 1) == this.table.selectCollectionData.length) {
          this.$message({message: '已经是最后一条，下移失败',type: 'warning' });
      } else {
          let downData = this.table.selectCollectionData[index + 1];
          this.table.selectCollectionData.splice(index + 1, 1);
          this.table.selectCollectionData.splice(index, 0, downData);
          let downColData = this.saveColsData[index + 1];
          this.saveColsData.splice(index + 1, 1);
          this.saveColsData.splice(index, 0, downColData);
          let downTableData = this.tableData[index + 1];
          this.tableData.splice(index + 1, 1);
          this.tableData.splice(index, 0, downTableData);
          let tempArrLength = []
          this.saveColsData.map((item,index) =>{
            tempArrLength.push({leng:item.length,arrIndex:index})
          })
          tempArrLength.sort((a,b)=>{
            return b.leng - a.leng
          })
          this.$nextTick(()=>{
            this.cols = this.saveColsData.length ? this.saveColsData[tempArrLength[0].arrIndex] : []
          })
      }
    },
    //删除
    moveleft(index,row){
      // 在采集信息表表中删除,添加到选中的数据采集表中
      this.table.selectCollectionData.splice(index,1)
      this.saveColsData.splice(index,1)
      this.tableData.splice(index,1)
      let tempArrLength = []
      this.saveColsData.map((item,index) =>{
        tempArrLength.push({leng:item.length,arrIndex:index})
      })
      tempArrLength.sort((a,b)=>{
        return b.leng - a.leng
      })
      this.$nextTick(()=>{
        this.cols = this.saveColsData.length ? this.saveColsData[tempArrLength[0].arrIndex] : []
      })
    },
    //采集信息确定
    addCollection(){
      if (this.table.sampleData.length  !== this.cllotData.length ) {
        this.$message.warning('样品信息表中的数据与采集信息表中的数据不相等，请按照顺序对应上')
        return
      }
      let tempArr = []
      this.table.sampleData.map((item,index) =>{
        tempArr.push({
          stId:item.stId,
          sampleNo:item.sampleNo,
          eqpNo:this.cllotData[index].eqpNo,
          eqpName:this.cllotData[index].eqpName,
          collId:this.cllotData[index].collId, // 数采记录id
          discard:this.cllotData[index].discard,   // 丢弃的分析项目
          stateFlag: this.cllotData[index].stateFlag
        })
      })
      this.addCollectionLoading = true
      this.axios.post('pass/testManagement/v1/limssampletests/datagather',tempArr,{individualType: 'json'}).then(res =>{
        if (res.code == 0 || res.code == 200) {
          this.CollectionCancel()
          this.searchcollection()
          this.$emit('refresh')
        }else{
          this.$message.error(res.message)
        }
        this.addCollectionLoading = false
      }).catch(err =>{
        this.addCollectionLoading = false
        this.$message.error(err.message)
      })
    },
    SizeTest (size) {
      this.pageTests.pageSize = size;
      this.searchcollection();
    },
    pageChangeTest (index) {
      this.pageTests.pageNum = index;
      this.searchcollection();
    },
    tableHeaderCellStyle () {
      return 'background-color: rgb(249,249,249) !important;color: rgb(73, 72, 72);border-bottom: 1px solid #DCDFE7;border-top:3px solid #3ac1ea;'
    }
  },
  watch: {
    showFlag(arg) {
      this.collectionShow = true;
      this.table.sampleData = JSON.parse(JSON.stringify(this.Params2))
      this.$nextTick(() =>{
        this.searchcollection();
      })
    },
  },
};
function compare (obj1, obj2) {
  var val1 = obj1.seq || 9999;
  var val2 = obj2.seq || 9999;
  return val1 - val2;
}
</script>
<style lang="less">
.examination_dataCollection div.el-table table tr td div.cell{
  height: 21px;
}
</style>
