<template>
  <div class="examination">
    <div class="common-head-search">
      <el-form :inline='true'>
        <el-form-item label='物料名称'>
          <el-input v-model="search.matName" @keyup.enter.native="searchData()" size="small" placeholder="请输入查询内容" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label='样品类型'>
          <el-select v-model="search.sampleTypeCode" clearable filterable collapse-tags size="small" style="width:150px;" placeholder="请选择查询内容">
            <el-option v-for="item in sampleTypeNameType" :key="item.baseCode" :label="item.baseName"
              :value="item.baseCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='送样日期'>
          <el-date-picker
           v-model="search.createTime"
           type="daterange"
           range-separator="至"
           start-placeholder="开始日期"
           end-placeholder="结束日期"
           size="small"
           format="yyyy-MM-dd"
           value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="goon" size="mini" @click="searchData">查询</el-button>
          <el-button icon="el-icon-refresh" type="info" plain size="mini" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-tabs type="border-card" v-model="activeName">
      <el-tab-pane label="待接样" name="first">
        <span slot="label">待接样<el-badge :max="10" :hidden='page.totalPage == 0' style="margin-top:-18px" :value="page.totalPage"></el-badge></span>
        <div class="common-title-div">
          <div class="common-title-name">
            <img style="width: 25px; height: 25px" src='../../../../assets/img/imgScreen/logo.png' />
            待接样信息
          </div>
          <div>
            <el-form :inline='true' @submit.native.prevent>
              <el-form-item>
                <el-button icon="el-icon-check" type="goon" size="mini" :loading='sampleLoading' v-privilege="activeMenu + 'receive'" @click="samplingData">接样</el-button>
                <el-button icon="el-icon-remove-outline" type="danger" size="mini" v-privilege="activeMenu + 'returnSample'" @click="sampleWithdrawalData">退样</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="common-table-div">
           <el-table id="excelTable" v-loading="dataLoading" ref="dataTable" border :height="height_top" highlight-current-row @selection-change="handleRow" :data="table.list" :icore-filter-flag="icoreFilterFlag"
           :header-cell-style="tableHeaderCellStyle"  :summary-method="getSummaries" show-summary>
            <el-table-column type="index" label="NO" align="center"></el-table-column>
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop='stateFlagName' label="状态" align="center"></el-table-column>
            <!-- <el-table-column sortable :show-overflow-tooltip="true" min-width="140px" prop="sndTime" label="送样日期" align="center"></el-table-column> -->
            <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="matName" label="物料名称" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="140px" prop="showCode" label="样品号" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="itemTypeName" label="项目类型" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="sampleTypeName" label="样品类型" align="center"></el-table-column>
            <!-- <el-table-column sortable width="140px" prop="batchNo" label="批次号" align="center"></el-table-column> -->
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="sndMan" label="送样人" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="memo" label="备注" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="createMan" label="创建人" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="140px" prop="createTime" label="创建时间" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="updateMan" label="修改人" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="140px" prop="updateTime" label="修改时间" align="center"></el-table-column>
          </el-table>
        </div>
        <div class="common-foot-style">
            <el-pagination v-loading="dataLoading" @size-change="pageSizeChange" @current-change="pageCurrentChange"
              :current-page="page.pageNum" :page-sizes="[10, 20, 50, 100, 200]" :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="page.totalPage" background>
            </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="已接样" name="second">
        <span slot="label">已接样<el-badge :max="10" :hidden='page2.totalPage == 0' style="margin-top:-18px" :value="page2.totalPage"></el-badge></span>
        <div class="common-title-div">
          <div class="common-title-name">
            <img style="width: 25px; height: 25px" src='../../../../assets/img/imgScreen/logo.png' />
            已接样信息
          </div>
          <div>
          <el-form :inline='true' @submit.native.prevent>
              <el-form-item label="扫码接样">
                <el-input v-model="values" ref="autoInput" size='mini' style="width：200px" clearable @input="autoSubmit()" :disabled='inputLoading'></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="common-table-div">
           <el-table v-loading="dataLoading2" ref="dataTable2" border :height="height_bot" highlight-current-row :data="table.list2" :icore-filter-flag="icoreFilterFlag"
           :header-cell-style="tableHeaderCellStyle" :cell-class-name="tableRowClassName2" :summary-method="getSummaries" show-summary>
            <el-table-column type="index" label="NO" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="stateFlagName" label="状态" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="matName" label="物料名称" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="140px" prop="showCode" label="样品号"  align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="itemTypeName" label="项目类型" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="sampleTypeName" label="样品类型" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="batchNo" label="批次号" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="120px" prop="refuseNote" label="拒收原因" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="140px" prop="sndTime" label="送样日期" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="sndMan" label="送样人"  align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="140px" prop="acptTime" label="接样日期" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="acptMan" label="收样人" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="memo" label="备注" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="95px" prop="createMan" label="创建人" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="160px" prop="createTime" label="创建时间" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="95px" prop="updateMan" label="修改人" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="160px" prop="updateTime" label="修改时间" align="center"></el-table-column>
          </el-table>
        </div>
        <div class="common-foot-style">
            <el-pagination  @size-change="pageSizeChange2" @current-change="pageCurrentChange2"
              :current-page="page2.pageNum" :page-sizes="[10, 20, 50, 100, 200]" :page-size="page2.pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="page2.totalPage" background>
            </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog @close="closeDialog" :visible.sync="dialogTableVisible">
      <div slot="title" class="titleBox">
        <i class="el-icon-document" style="font-size: 20px"></i>
        <span style="margin-left:10px;font-size:18px">退样原因</span>
      </div>
      <el-form ref="baseData" label-width="60px" :rules="ruleValidate" :model="baseData">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="matName" label="物料">
              <el-input v-model="baseData.matName" readonly disabled size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="sampleNo" label="样号">
              <el-input v-model="baseData.sampleNo" readonly disabled size="small"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
          <el-row>
           <el-col :span="24">
            <el-form-item prop="refuseNote" label="原因">
              <el-input v-model="baseData.refuseNote"  size="small"></el-input>
            </el-form-item>
          </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item prop="memo" label="备注">
                <el-input v-model="baseData.memo" size="small"></el-input>
              </el-form-item>
            </el-col>
         </el-row>
       </el-form>
       <span slot="footer" class="dialog-footer">
        <el-button type="goon" size="mini" icon="el-icon-check" :loading='backLoading' @click="modifyData()">确定</el-button>
        <el-button size="mini" type="goon" icon="el-icon-remove-outline" @click="cancel">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getCookie,
  formatDate
} from '@/utils/util.js';
import {
  cookieUserId,
  cookieUserName
} from '@/config/config.js'
let userName = getCookie(cookieUserName);
let userId = getCookie(cookieUserId);
export default {
  data () {
    return {
      table: {
        list: [],
        list2: []
      },
      sampleLoading:false,
      backLoading:false,
      cnacelLoading:false,
      values:'',
      inputLoading:false,
      saveRow:[],
      baseData:{},
      ruleValidate: {
        refuseNote: [{ required: true, message: '该项不能为空', trigger: 'blur' }]
      },
      dialogTableVisible:false,
      dataLoading: false,
      dataLoading2: false,
      icoreFilterFlag: true,
      page: {
        pageSize: 50,
        pageNum: 1,
        totalPage: 0
      },
      page2: {
        pageSize: 50,
        pageNum: 1,
        totalPage: 0
      },
      planId: '',
      sampleTypeNameType: [],
      multipleSelection4: [],
      search: {
        createTime: [],
        sampleTypeCode: '',
        matName: '',
      },
      activeName:'first',
      height_top:0,
      height_bot:0,
      activeMenu:'',
      timeId:null
    }
  },
  created() {
    this.height_top = window.innerHeight  - 240;
    this.height_bot = window.innerHeight  - 240;
    this.search.createTime = [this.getYNM(new Date()), this.getYNM(new Date())] 
    this.activeMenu = window.top.localStorage.getItem('activeMenu')
  },
  mounted () {
    this.axios.post("pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode",{validFlag:1,baseCode:4801}, {individualType: 'json'}).then(res => {
      this.sampleTypeNameType = res.data
    })
    this.searchData();
    // this.addScreen();
    // this.addScreen2()
  },
  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}`;
    },
    getSummaries(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;   
    },
    closeDialog(){
      this.baseData = {}
      this.backLoading = false
    },
    autoSubmit(val){
      if (!this.values) {
        this.$message.warning('请先用扫码枪扫描标签')
        return
      }
      if (!this.timeId) {
        this.timeId = setTimeout(() => {
          this.inputLoading = true
          this.axios.post('pass/testManagement/v1/limssampleacpts/saveLimsSampleAcptScan2',{itemTypeCode:'480406',scanCode:this.values,scanName:'markNo'},{individualType: 'json'}).then(res => {
            if(res.code== 0 || res.code == 200) {
              this.$message.success(res.message);
              this.searchData()
            } else {
             this.$message.error(res.message)
            }
            this.$nextTick(() =>{
              this.$refs.autoInput.focus()
            })
            this.values = ''
            this.inputLoading = false
            }).catch(e => {
              this.$nextTick(() =>{
                this.$refs.autoInput.focus()
              })
            this.values = ''
            this.inputLoading = false
            }).catch(e => {
              this.$nextTick(() =>{
                this.$refs.autoInput.focus()
              })
              this.values = ''
              this.inputLoading = false
             this.$message.error(e.message)
          })
          this.timeId = null;
        }, 1000);
      }
    },
    //接样
    samplingData () {
      if (this.saveRow.length < 1) {
        this.$message.warning('请点击勾选中您接样的数据！')
        return
      }
      let tempArr = []
      tempArr =  JSON.parse(JSON.stringify(this.saveRow))
      // tempArr.forEach(item =>{
      //   item.itemTypeCode = 480401
      // })
      this.sampleLoading = true
      this.axios.post('pass/testManagement/v1/limssampleacpts/saveLimsSampleAcpt',tempArr, {individualType: 'json'}).then(res => {
        if(res.code== 0 || res.code == 200) {
          this.$message.success(res.message);
          this.searchData()
        } else {
         this.$message.error(res.message)
        }
        this.sampleLoading = false
        }).catch(e => {
          this.sampleLoading = false
         this.$message.error(e.message)
       })
    },
    //退样弹窗
    sampleWithdrawalData () {
      if (this.saveRow.length != 1) {
        this.$message.warning('请点击勾选中您要退样的一条数据！')
        return
      }
      this.baseData = Object.assign({},this.saveRow[0])
      this.dialogTableVisible = true
    },
    //退样确认
    modifyData () {
      this.$refs['baseData'].validate((valid) => {
        if (valid) {
          this.backLoading = true
          this.baseData.id = ''
          this.baseData.stateFlag = ''
          this.axios.post('pass/testManagement/v1/limssampleacpts/refuseacpt', this.baseData, {individualType: 'json'}).then(res => {
            if (res.code == 0 || res.code == 200) {
              this.dialogTableVisible = false;
              this.$message.success(res.message)
              this.searchData()
            } else {
              this.$message.error(res.message)
            }
            this.backLoading = false
          }).catch(e => {
            this.backLoading = false
            this.$message.error(e.message)
          })
        }
      })
    },
    //弹出窗取消
    cancel(){
      this.baseData = {}
      this.backLoading = false
      this.dialogTableVisible = false
    },
    cancelData () {
      if (this.multipleSelection4.length < 1) {
        this.$message.warning('请勾选您要取消的数据！')
        return
      }
      let tempArr = []
      this.multipleSelection4.map(item =>{
        tempArr.push(item.id)
      })
      this.cnacelLoading = true
      this.axios.post('pass/testManagement/v1/limssampleacpts/cancel', tempArr, {individualType: 'json'}).then(res => {
        if (res.code == 0 || res.code == 200) {
         this.$message.success('取消成功');
         this.searchData()
        } else {
         this.$message.error(res.message)
        }
        this.cnacelLoading = false
      }).catch(e => {
        this.cnacelLoading = false
        this.$message.error(e.message)
      })
    },
    searchData(){
      this.page.pageNum = 1;
      this.page.pageSize = 50
      this.page2.pageNum = 1;
      this.page2.pageSize = 50
      this.mainData()
      this.getDataList2()
    },
    mainData () {
      // this.saveRow = {}
      this.dataLoading = true;
      if (!this.search.createTime) {
        this.startTime = ''
        this.endTime = ''
      } else {
        this.startTime = this.search.createTime[0] + ' 00:00:00',
        this.endTime = this.search.createTime[1] + ' 23:59:59'
      }
      let obj = {
        'object':{
          'matName': this.search.matName,
          'sampleTypeCode': this.search.sampleTypeCode,
          // 'itemTypeCode':480401,
          'stateFlag':1
        },
        'list2':['480401','480406'],
        "pageSize": this.page.pageSize,
        "pageIndex": this.page.pageNum,
        'startTime2': this.startTime,
        'endTime2':this.endTime 
      }
      this.axios.post('pass/testManagement/v1/limssampleacpts/queryLimsSampleAcptPage',obj,{individualType: 'json'}).then(res => {
        this.dataLoading = false;
        if (res.code == 0 || res.code == 200) {
          this.table.list = res.data.list;
          this.table.list.forEach(item =>{
            item.showCode =  item.sampleTypeCode == '480101' ? item.markNo : item.sampleNo
            item.stateFlagName = item.stateFlag === '-1' ? '退样' : item.stateFlag === '0' ? '未交样' : item.stateFlag === '1' ? '已交样' : item.stateFlag === '2' ? '已接样' : item.stateFlag === '3' ? '已处理' :'退样'
          })
          this.page.totalPage = res.data.total
        }else{
          this.$message.error(res.message)
        }
      }).catch(e => {
        this.dataLoading = false;
        this.$message.error(e.message)
      });
    },
    getDataList2 () {
      this.dataLoading2 = true;
      if (!this.search.createTime) {
        this.startTime = ''
        this.endTime = ''
      } else {
        this.startTime = this.search.createTime[0] + ' 00:00:00'
        this.endTime = this.search.createTime[1] + ' 23:59:59'
      }
      let obj = {
        'object':{
          'matName': this.search.matName,
          'sampleTypeCode': this.search.sampleTypeCode,
          // 'itemTypeCode':480401,
          'acptNo':userId,
          'stateFlag':2
        },
        'list2':['480401','480406'],
        'mode':'',
        "pageSize": this.page2.pageSize,
        "pageIndex": this.page2.pageNum,
        'startTime': this.startTime ,
        'endTime':this.endTime 
      }
      this.axios.post('pass/testManagement/v1/limssampleacpts/queryLimsSampleAcptPage',obj,{individualType: 'json'}).then(res => {
        this.dataLoading2 = false;
        if (res.code == 0 || res.code == 200) {
          this.table.list2 = res.data.list;
          this.table.list2.forEach(item =>{
            item.showCode =  item.sampleTypeCode == '480101' ? item.markNo : item.sampleNo
            item.stateFlagName = item.stateFlag === '-1' ? '退样' : item.stateFlag === '0' ? '未交样' : item.stateFlag === '1' ? '已交样' : item.stateFlag === '2' ? '已接样' : item.stateFlag === '3' ? '已处理' :'退样'
          })
          this.page2.totalPage = res.data.total;
        }else{
          this.$message.error(res.message)
        }
      }).catch(e => {
        this.dataLoading2 = false;
        this.$message.error(e.message)
      });
    },
    reset () {
      this.search.createTime = [this.getYNM(new Date()), this.getYNM(new Date())]
      this.search.matName = '';
      this.search.sampleTypeCode = '';
      this.searchData();
    },
    //待接样信息表格点击选中
    handleRow (val) {
      this.saveRow = val;
    },
    pageSizeChange (size) {
      this.page.pageSize = size;
      this.mainData();
    },
    pageCurrentChange (index) {
      this.page.pageNum = index;
      this.mainData();
    },
    pageSizeChange2 (size) {
      this.page2.pageSize = size;
      this.getDataList2();
    },
    pageCurrentChange2 (index) {
      this.page2.pageNum = index;
      this.getDataList2();
    },
    addScreen () {
      this.$nextTick(() => {
          let ss = document.createElement('div');
          ss.innerHTML = '筛选';
          ss.style = 'text-align: center;'
          this.$refs.dataTable.$el.getElementsByClassName('el-table__fixed')[0].getElementsByTagName('td')[0].appendChild(ss);
       });
    },
    addScreen2 () {
     this.$nextTick(() => {
          let ss = document.createElement('div');
          ss.innerHTML = '筛选';
          ss.style = 'text-align: center;'
          this.$refs.dataTable2.$el.getElementsByClassName('el-table__fixed')[0].getElementsByTagName('td')[0].appendChild(ss);
       });
    },
  //  tableRowClassName ({
  //       row, column, rowIndex, columnIndex
  //     }) {
  //       if (columnIndex === 13) {
  //       if (row.validFlag !== '1') {
  //         return 'error-row';
  //       }
  //       }
  //       if (columnIndex === 3) {
  //       if (row.stateFlag === '1') {
  //         return 'error-green';
  //       }
  //       return '';
  //       }
  //     },
    tableRowClassName2 ({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 1) {
        if (row.stateFlag === '-1') {
          return 'error-row';
        }
        return '';
      }
    },
    tableHeaderCellStyle () {
      return 'color: rgb(255,255,255);border-bottom: 1px solid #DCDFE7;'
    }
  }
}
</script>
<style  scoped>
</style>
