<template>
  <div class="table-wrap">
    <el-table :data="tableData" ref="tableRef"
      @cell-dblclick="cellDblclick"
      @select="select"
      :cell-style="cellStyle"
      highlight-current-row
      class="detail-smaple-table" size="mini" stripe border >

      <el-table-column type="selection"  fixed="left" width="60" show-overflow-tooltip>
      </el-table-column>
      <el-table-column type="index" label="序号" fixed="left"  width="60" show-overflow-tooltip>
      </el-table-column>

      <el-table-column  v-for="(item, index) in colunms" :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :fixed="item.fixed"
          :min-width="item.width"
          :show-overflow-tooltip="item.tooltip"
          >
      </el-table-column>

      <el-table-column prop="longsysPN" label="标准PN"   min-width="130" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.sealSample=='Y'"  class="seal">封</span>
          <span>{{scope.row.longsysPN}}</span>
        </template>
      </el-table-column>

      <el-table-column  v-for="(item, index) in colunms2" :key="index"
           :prop="item.prop"
           :label="item.label"
           :formatter="formatter"
           :class-name="item.prop =='sampleStatusKey'?'c357F':'' "
           :fixed="item.fixed"
           :min-width="item.width"
           :show-overflow-tooltip="item.tooltip"
           >
       </el-table-column>


      <el-table-column prop="checkResult"  label="样品状态"  min-width="180" >
        <template slot-scope="scope">
          <div v-if="scope.row.sampleLineStatus == 'draft' " class="c357F">{{scope.row.sampleStatusKey}}</div>
          <div v-else>
            <common-select v-model="scope.row.sampleStatus"
              size="mini"
             :disabled="scope.row.sampleLineStatus=='draft' || scope.row.sealSample =='Y' || !scope.row.sampleImportId "
              dictType="Crm_Sample_Status"   >
            </common-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="actualDate"  label="实际送样时间"  min-width="150" >
        <template slot-scope="scope">
          <el-date-picker
                size="mini"
                v-model="scope.row.actualDate"
                @change="actualTimeChange(scope.row.actualDate, scope.$index)"
                type="date"
                :editable="false"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :disabled="scope.row.sampleLineStatus=='draft' || scope.row.sealSample =='Y' || !scope.row.sampleImportId "
                placeholder="请选择"
               >
          </el-date-picker>
        </template>
      </el-table-column>
      <el-table-column prop="recDate"  label="承认样品时间"  min-width="150" >
        <template slot-scope="scope">
          <el-date-picker
                v-model="scope.row.recDate"
                 @change="recTimeChange(scope.row.recDate, scope.$index)"
                size="mini"
                type="date"
                :editable="false"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :disabled="scope.row.sampleLineStatus=='draft' || scope.row.sealSample =='Y' || !scope.row.sampleImportId "
                placeholder="请选择"
               >
          </el-date-picker>
        </template>
      </el-table-column>
      <el-table-column prop="checkResult"  label="样品检验结果"  min-width="130" >
        <template slot-scope="scope">
          <el-select v-model="scope.row.checkResult"
            :disabled="scope.row.sampleLineStatus=='draft' || scope.row.sealSample =='Y' || !scope.row.sampleImportId "
            placeholder="请选择"  size="mini"   clearable>
              <el-option
                v-for="item in sampleResultList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                >
              </el-option>
            </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="sealSample"  label="是否封样"  min-width="100" >
        <template slot-scope="scope">
          {{scope.row.sealSample == 'Y'?'是':'否'}}
        </template>
      </el-table-column>
      <el-table-column prop="trialDate"  label="实际小批试产时间"  min-width="150" >
        <template slot-scope="scope">
          <el-date-picker
                size="mini"
                v-model="scope.row.trialDate"
                 @change="trialTimeChange(scope.row.trialDate, scope.$index)"
                type="date"
                :editable="false"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :disabled="scope.row.sampleLineStatus=='draft' || scope.row.sealSample =='Y' || !scope.row.sampleImportId "
                placeholder="请选择"
               >
          </el-date-picker>
        </template>
      </el-table-column>
      <el-table-column prop="trialQuantity"  label="小批试产数量(pcs)"  min-width="150" >
        <template slot-scope="scope">
            <el-input
              size="mini"
              v-model="scope.row.trialQuantity"
              v-input-filter:gzero
              v-input-filter:comdify
              :disabled="scope.row.sampleLineStatus=='draft' || scope.row.sealSample =='Y' || !scope.row.sampleImportId "
              placeholder="请输入" />
        </template>
      </el-table-column>
      <el-table-column prop="outputDate"  label="实际量产时间"  min-width="150" >
        <template slot-scope="scope">
          <el-date-picker
                size="mini"
                v-model="scope.row.outputDate"
                @change="outputTimeChange(scope.row.outputDate, scope.$index)"
                type="date"
                :editable="false"
                :disabled="scope.row.sampleLineStatus=='draft' || scope.row.sealSample =='Y' || !scope.row.sampleImportId "
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
               >
          </el-date-picker>
        </template>
      </el-table-column>
      <el-table-column prop="outputQuantity"  label="量产数量(pcs)"  min-width="130" >
        <template slot-scope="scope">
          <el-input
            size="mini"
            v-model="scope.row.outputQuantity"
            v-input-filter:gzero
            v-input-filter:comdify
            :disabled="scope.row.sampleLineStatus=='draft' || scope.row.sealSample =='Y' || !scope.row.sampleImportId "
            placeholder="请输入" />
        </template>
      </el-table-column>
      <el-table-column prop="remark"  label="补充说明"  min-width="250" >
         <template slot-scope="scope">
            <el-input
                  v-model="scope.row.remark"
                  :maxlength="100"
                   size="mini"
                  type="textarea"
                  v-inputFilter:trim
                  :disabled="scope.row.sampleLineStatus=='draft' || scope.row.sealSample =='Y' || !scope.row.sampleImportId "
                  :autosize="{ minRows: 1, maxRows: 3}"
                  show-word-limit
                  placeholder="请输入" />
         </template>
      </el-table-column>
      <el-table-column prop="statusKey" fixed="right" label="审批状态" :formatter="formatter"  min-width="100" show-overflow-tooltip>  </el-table-column>
      <el-table-column  label="操作" fixed="right" v-if="projectStatus =='audited'|| projectStatus =='filed'" min-width="120"  show-overflow-tooltip>
         <template slot-scope="scope">
          <el-button v-if="scope.row.status=='draft' " @click="handleEdit(scope.row, 'line')"
               type="text" size="mini">编辑</el-button>
          <el-button v-if="scope.row.status=='draft' " @click="handleDelete(scope.row)"
               type="text" size="mini">删除</el-button>
<!--         <el-button v-if="scope.row.status !='draft' " type="text" size="mini"-->
<!--              @click="updateSample(scope.row,'line')"-->
<!--               >更新</el-button>-->
          <el-button v-if="scope.row.status !='draft' " type="text" size="mini"
              @click="handleDetail(scope.row, scope.row.sampleImportId?'item':'line')"
               >详情</el-button>
           <el-button v-if="scope.row.status=='audited' && !scope.row.sampleImportId" @click="updateSample(scope.row, 'line')"
                      type="text" size="mini">变更</el-button>
         </template>
      </el-table-column>




    </el-table>
    <!-- 分页-->
    <ls-pagination :pager.sync="pager"  @query="doQuery"></ls-pagination>
  </div>
</template>

<script>
  export default {
    name: 'sample-process-table',
    created() {
      this.doQuery();
    },
    mounted() {

    },
    methods: {
      // 查询数据
      doQuery(current){
        if ( typeof current != 'undefined') {
           this.pager.curPage = current;
        }
        let param = {
          currPage: this.pager.curPage,
          pageSize: this.pager.size,
          queryParam: {
            projectId: this.projectid,
            moduleId: '3101',
          }
        };

        this.$ajax.post({
          domain: 'crmUrl',
          url: 'sample.listPageSampleByProjectId',
          data: JSON.stringify(param),
          requestType: 'body',
          showLoad: true,
          success: function (res) {
            if (res.errorCode === 200) {
                this.tableData = res.data.records || [];
                this.pager.totals = res.data.total;
                this.tableData.forEach(item=>{
                  item.trialQuantity = this.$common.getComdifyNumber(item.trialQuantity);
                  item.outputQuantity = this.$common.getComdifyNumber(item.outputQuantity);
                })
              if(this.tableData.length){
                this.getProcessApprove(this.tableData);
              }
                this.$refs.tableRef.doLayout();
            }
          }.bind(this),
          error: function (res) {
            this.$message({
              type: 'error',
              message: res.body.msg || res.msg
            })
          }.bind(this)
        })
      },

      // 查询流程审批人
      getProcessApprove(list) {
        let ary = [];
        list.forEach(item=>{
          if(item.status == 'rejected' || item.status == 'auditing' ){
            if(item.processId){
              ary.push({processId: item.processId});
            }
          }
        })
        debugger;
        if(!ary.length){ return };

        this.$ajax.post({
          domain: 'crmUrl',
          url: 'process.getProcessApprove',
          data: ary,
          requestType: 'body',
          showLoad: false,
          success: function (res) {
            if (res.errorCode === 200) {
              this.approverList = res.data;

              this.tableData.forEach(item=>{
                if(item.status == 'rejected' || item.status == 'auditing' ){
                  for(let el of this.approverList){
                    if(item.processId === el.processId){
                      this.$set(item, 'approver', el.approver );
                      break;
                    }
                  }
                } else {
                  this.$set(item, 'approver', '' );
                }
              })
            }
          }.bind(this),
          error: function (res) {
            this.$message({
              type: 'error',
              message: res.body.msg || res.msg
            })
          }.bind(this)
        })
      },
    sealSample(){
        let selections = JSON.parse(JSON.stringify(this.$refs.tableRef.selection));
        if(!selections.length){
          this.$message('请选择行数据');
          return;
        }
        for(let item of selections){
          if(!item.sampleImportId){
            this.$message('所选行暂不可封样');
            return;
          } else if(item.sealSample =='Y'){
            this.$message('所选行已封样');
            return;
          }else if(!item.checkResult){
            this.$message('请选择样品验证结果');
            return;
          }  else {
            item.sealSample = 'Y';
            item.trialQuantity = this.$common.delcommafy(item.trialQuantity);
            item.outputQuantity = this.$common.delcommafy(item.outputQuantity);
          }
        }

        this.$ajax.post({
            domain: 'crmUrl',
            url: 'sampleImport.updateSealSample',
            data: selections,
            requestType: 'body',
            showLoad: true,
            success: function (res) {
              if (res.errorCode === 200) {
                this.$message({
                  type: 'success',
                   message: '封样成功'
                });
                this.doQuery();
              }
            }.bind(this),
            error: function (res) {
              this.$message({
                type: 'error',
                message: res.body.msg || res.msg
              })
            }.bind(this)
        })
      },
      handleDelete(row){

        this.$confirm('确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

            this.$ajax.post({
              domain: 'crmUrl',
              url: 'sampleImport.deleteSampleLine',
              data: {id: row.id},
              requestType: 'body',
              showLoad: true,
              success: function (res) {
                if (res.errorCode === 200) {
                  this.$message.success('删除成功');
                  this.doQuery();
                }
              }.bind(this),
              error: function (res) {
                this.$message({
                  type: 'error',
                  message: res.body.msg || res.msg
                })
              }.bind(this)
            })

        }).catch(() => { });

      },
      handleEdit(row, flag){
        this.$router.push({name: 'sampleApply', params: {id: row.id, flag} });
      },
      updateSample(row,flag){
        this.$router.push({name: 'sampleApply', params: {id: row.id,flag,isChange:true}});
      },
      handleSave(){
        let selections = JSON.parse(JSON.stringify(this.$refs.tableRef.selection));
        if(!selections.length){
          this.$message('请选择行数据');
          return;
        }
        for(let item of selections){
          if(!item.sampleImportId){
            this.$message('所选行暂不可保存');
            return;
          } else if(!item.checkResult){
            this.$message('请选择样品验证结果');
            return;
          } else {
            item.trialQuantity = this.$common.delcommafy(item.trialQuantity);
            item.outputQuantity = this.$common.delcommafy(item.outputQuantity);
          }
        }
        this.updateSampleLineAndItem(selections, 'save');
      },
      // handleUpload(row){

      //   if(!row.sampleImportId){
      //     this.$message('所选行暂不可更新');
      //     return;
      //   } else if(!row.checkResult){
      //     this.$message('请选择样品验证结果');
      //     return;
      //   } else {
      //     row.trialQuantity = this.$common.delcommafy(row.trialQuantity);
      //     row.outputQuantity = this.$common.delcommafy(row.outputQuantity);
      //   }
      //   this.updateSampleLineAndItem([row], 'upload');
      // },
      handleDetail(row, flag){
        this.$router.push({
          name: 'sampleApply',
          params: {
            id: row.sampleImportId ? row.sampleImportId : row.id,
            flag: flag,
            disabledForm: true,
          },
        });
      },
      cellStyle({row, column, rowIndex, columnIndex}){
        if(column.label === '审批状态' ){
          if(row.status ==='canceled'){
            return 'color: #909399;';
          } else if(row.status === 'audited' || row.status ==='filed'){
            return 'color: #67C23A;';
          } else if(row.status ==='rejected'){
            return 'color: #F56C6C;';
          } else if( row.status ==='auditing'){
            return 'color: #409EFF;';
          } else {
            return '';
          }
        }
      },
      cellDblclick(row, column, cell, event){
        if( row.sampleLineStatus == 'draft'){
          this.$router.push({name: 'sampleApply', params: {id: row.id, flag: 'line'} });
        } else if(row.sampleLineStatus != 'draft'){
          this.$router.push({
            name: 'sampleApply',
            params: {
              id: row.sampleImportId ? row.sampleImportId : row.id,
              flag: row.sampleImportId ? 'item' : 'line',
              disabledForm: true,
            },
          });
        }
      },
      select(selection, row){
          if(row.sampleLineStatus == 'draft'){
            this.$message('样品尚未提交');
            this.$refs.tableRef.toggleRowSelection(row, false);
          }
      },
      updateSampleLineAndItem(ary, operat){

        this.$ajax.post({
           domain: 'crmUrl',
           url: 'sample.updateSampleLineAndItem',
           data: ary,
           requestType: 'body',
           showLoad: true,
           success: function (res) {
              if (res.errorCode === 200) {
                 this.$message({
                   type: 'success',
                   message: operat == 'save'?'保存成功':'更新成功'
                 });
                 this.doQuery();
              }
           }.bind(this),
           error: function (res) {
             this.$message({
               type: 'error',
               message: res.body.msg || res.msg
             })
           }.bind(this)
        })
      },
      //承认样品时间 change
      recTimeChange(val, index){
        if(val){
           let recDate = Date.parse(val);
           let actualDate =  Date.parse(this.tableData[index].actualDate);
           let trialDate = Date.parse(this.tableData[index].trialDate);
           if( !isNaN(actualDate) && actualDate > recDate ){
             this.$message.warning('承认样品时间必须大于等于实际送样时间');
             this.tableData[index].recDate = '';
             return;
           }
           if( !isNaN(trialDate) && recDate > trialDate ){
             this.$message.warning('小批试产时间必须大于等于承认样品时间');
             this.tableData[index].recDate = '';
           }
        }

      },
      //实际送样时间 change
      actualTimeChange(val, index){
        if(val){
           let actualDate  = Date.parse(val);
           let recDate = Date.parse(this.tableData[index].recDate);
           if( !isNaN(recDate) && actualDate > recDate ){
             this.$message.warning('实际送样必须小于等于承认样品时间');
             this.tableData[index].actualDate = '';
           }
        }
      },
      //小批试产 时间 change
      trialTimeChange(val, index){
        if(val){
           let trialDate  = Date.parse(val);
           let actualDate =  Date.parse(this.tableData[index].actualDate);
           let outputDate = Date.parse(this.tableData[index].outputDate);
           if( !isNaN(actualDate) &&  actualDate  > trialDate){
             this.$message.warning('小批试产时间必须大于等于承认样品时间');
             this.tableData[index].trialDate = '';
             return;
           }
           if( !isNaN(outputDate) &&  outputDate  < trialDate){
             this.$message.warning('小批试产时间必须小于等于实际量产时间');
             this.tableData[index].trialDate = '';
           }
        }
      },
      //实际量产时间
      outputTimeChange(val, index){
        if(val){
           let outputDate  = Date.parse(val);
           let trialDate = Date.parse(this.tableData[index].trialDate);
           if( !isNaN(trialDate) && trialDate > outputDate ){
             this.$message.warning('实际量产时间必须大于等于小批试产时间');
             this.tableData[index].outputDate = '';
           }
        }
      },

      formatter(row, column, cellValue, index){

        if(column.property == 'sealSample'){
             if(row.sealSample === 'Y'){
               return '是';
             } else{
               return '否';
             }
         }else if(column.property == 'statusKey'){
          if(row.approver ){
            return row.statusKey + " (" + row.approver +")" ;
          } else {
            return row.statusKey;
          }
        }  else {
           return cellValue;
         }
      },


    },
    props:["projectid", "projectStatus"],
    data() {
      return {
        approverList:[],
        //分页参数
        pager: {
          curPage: 1,
          size: 10,
          pageOptions: [10, 20, 50],
          totals: 0
        },
        tableData: [],

        colunms: [//表格列
          { prop: 'customer', label: '客户名称', width: 120, fixed: 'left', tooltip: true},
          { prop: 'projectName', label: '项目名称', width: 120, fixed: false, tooltip: true},
          { prop: 'projectCode', label: '项目编码', width: 120, fixed: false, tooltip: true},
          { prop: 'projectLineCode', label: '子行编码', width: 150, fixed: false, tooltip: true},
          { prop: 'platformKey', label: '芯片平台', width: 130, fixed: false, tooltip: true},
          { prop: 'chipModelKey', label: '芯片型号', width: 120, fixed: false, tooltip: true},
          { prop: 'samplePurposeKey', label: '样品用途', width: 100, fixed: false, tooltip: true},
          { prop: 'fwVersion', label: 'FW版本', width: 100, fixed: false, tooltip: true},
          { prop: 'itemLevel', label: '产品等级', width: 100, fixed: false, tooltip: true},
        ],
        colunms2: [
          { prop: 'productPN', label: '产品PN', width: 100, fixed: false, tooltip: true},
          { prop: 'projectType', label: '产品类别', width: 100, fixed: false, tooltip: true},
          { prop: 'capacity', label: '容量', width: 100, fixed: false, tooltip: true},
          { prop: 'applyQuantity', label: '申请数量', width: 100, fixed: false, tooltip: true},
          { prop: 'sampleQuantity', label: '样品数量', width: 100, fixed: false, tooltip: true},
          { prop: 'sampleLineCode', label: '样品行编号', width: 150, fixed: false, tooltip: true},
          { prop: 'num', label: '料号', width: 100, fixed: false, tooltip: true},
        ],

        sampleResultList: [
          {
            value: '通过',
            label: '通过'
          },
          {
            value: '未通过',
            label: '未通过'
          },
        ],

      }
    },

  }
</script>

<style  lang="scss">
 .detail-smaple-table {

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: unset;
  }

  .el-textarea__inner {
  //   padding-right: 0px;
  //   padding-bottom: 20px;
  }

}
 .seal {
    display: inline-block;
    // padding: 5px;
    width: 24px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    color: #fff;
    background: #E6A23C;
    border-radius: 5px;
    margin-right: 8px;
  }
</style>
