<template>
  <div>
    <el-dialog @close="closeDialog"  :visible.sync="dialogTableVisible" width='70%'>
      <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 :model="form" ref="form" v-show="showButton" :rules="rules" label-width="80px" :inline="true" size="normal">
        <el-form-item prop='ruleTypeNo' label="规则类型">
          <el-select v-model="form.ruleTypeNo" filterable @change="filterData" collapse-tags size="small">
            <el-option v-for="item in ruleTypeNameType" :key="item.baseCode" :label="item.baseName" :value="item.baseCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop='ruleNo' label="规则名称" size="normal">
          <el-select v-model="form.ruleNo" filterable collapse-tags size="small">
            <el-option v-for="item in ruleTypeName" :key="item.ruleNo" :label="item.ruleName" :value="item.ruleNo">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="goon" size="mini" :loading='classifyLoading' @click="searchRule">查询</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="20">
        <el-col :span="12" >
          <div class="common-title-name">
            <img style="width: 25px; height: 25px; margin-left: 20px" src='../../../../assets/img/imgScreen/logo.png' />
            <span>输入项目</span> 
            <el-button icon="el-icon-check" type="goon" v-show="showButton" :loading='accountLoading' size="mini" @click="accounting">核算</el-button>
          </div>
          <el-table v-loading="dataLoading" ref="dataTable" highlight-current-row border :icore-filter-flag="icoreFilterFlag" :height="300" :data="sample.tableData1"  :header-cell-style="tableHeaderCellStyle">
            <el-table-column type="index" label="NO" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="ruleItemName" label="输入项目" align="center"></el-table-column>
            <el-table-column sortable :show-overflow-tooltip="true"  min-width="160px" prop="ruleItemValue" label="输入结果" align="center">
              <template slot-scope="{row}">
                <el-input v-model="row.ruleItemValue" oninput ="value=value.replace(/[^0-9.]/g,'')" style="width:100%" size="mini"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="12" >
          <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 v-loading="dataLoading2" ref="dataTable2" border :icore-filter-flag="icoreFilterFlag" :height="300" :data="sample.tableData2" :header-cell-style="tableHeaderCellStyle">
            <el-table-column type="index" label="NO" align="center"></el-table-column>
            <el-table-column sortable min-width="80px" :show-overflow-tooltip="true" prop="ruleItemName" label="输出项目" align="center"></el-table-column>
            <el-table-column sortable min-width="160px" :show-overflow-tooltip="true" prop="ruleItemValue" label="输出结果" align="center"></el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="goon" size="mini" icon="el-icon-check" v-show="showButton" :loading='addLoading' @click="aginAddData">重新抽样</el-button>
        <el-button type="goon" size="mini" icon="el-icon-check" v-show="showButton" :loading='addLoading' @click="addData">确定</el-button>
        <el-button size="mini" type="goon" icon="el-icon-remove-outline" @click="closeDialog">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ["showFlag", "Params"],
  data(){
    return {
      table: {
        list: [],
        list2: [],
        data:[],
        subList:[]
      },
      sample:{
        tableData1:[],
        tableData2:[]
      },
      printLoading:false,
      printTest:false,
      subTableData:[],
      saveAccount:{},
      ruleDatas:[],
      ruleTypeName:[],
      rules:{
        ruleTypeNo: [{ required: true, message: '不能为空', trigger: 'change' }],
        ruleNo: [{ required: true, message: '不能为空', trigger: 'change' }],
      },
      showButton:true,
      accountLoading:false,
      saveLoading:false,
      dataLoading: false,
      dataLoading2: false,
      icoreFilterFlag: true,
      dialogTableVisible:false,
      form:{
        ruleTypeNo:'',
        ruleNo:''
      },
      addLoading:false,
      classifyLoading:false,
      ruleTypeNameType:[],
      search: {
        entrTime: '',
        matName: ''
      },
      activeMenu:''
    }
  },
  created(){
    this.search.entrTime = [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:4838}, {individualType: 'json'}).then(res => {
      this.ruleTypeNameType = res.data;
    }) 
    this.ruleData()
  },
  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}`;
    },
    getCode (code, arr, codeKey, nameKey) {
        if (!code) {
          return '';
        }
        let targetRow = arr.find(item => {
          return item[codeKey] === code;
        });
        return targetRow ? targetRow[nameKey] : '';
    },
    //筛选出规则名称
    filterData(val){
      this.ruleTypeName = []
      this.form.ruleNo = ''
      if(!val){
        this.ruleTypeName = this.ruleDatas
        return
      }
      this.ruleDatas.map(item=>{
        if (item.ruleTypeCode == val) {
          this.ruleTypeName.push(item)
        }
      })
    },
    //业务规则按条件查询出符合的数据
    searchRule(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.saveAccount = {}
          this.sample.tableData1 = []
          this.sample.tableData2 = []
          this.subTableData = []
          this.classifyLoading = true
          this.axios.post('pass/baseManagement/v1/limsbaseruleds/queryLimsBaseRuleDList',{ruleNo:this.form.ruleNo}, {individualType: 'json'}).then(res => {
            if (res.code == 0 ||res.code == 200) {
              let data  = res.data
              this.subTableData = data
              data.forEach(item =>{
                item.ruleItemValue = item.ruleItemValue ? item.ruleItemValue : item.defaultValue
                if (item.isPara == 1) {
                  this.sample.tableData1.push(item)
                }else{
                  this.sample.tableData2.push(item)
                }
                this.classifyLoading = false
              })
            } else {
              this.classifyLoading = false
             this.$message.error(res.message)
            }
            this.saveLoading = false
          }).catch(e => {
            this.saveLoading = false
            this.$message.error(e.message)
          })
        } 
      });
    },
     //核算
    accounting(){
      if (this.sample.tableData1.length < 1) {
        this.$message.warning('表格中无数据,无法进行核算')
        return
      }
      let flag = false
      let data1 = ''
      let data2 = ''
      this.sample.tableData1.forEach(item =>{
        if (!item.ruleItemValue) {
          flag = true
        }
        if (item.ruleItemOrder == 1) {
          data1 = item.ruleItemValue
        }else if (item.ruleItemOrder == 2) {
           data2 =  item.ruleItemValue
        }
      })
      if (flag) {
        this.$message.warning('表格中的输入结果不能为空')
        return
      }
       this.accountLoading = true
      let data = this.getCode(this.form.ruleNo,this.ruleTypeName,'ruleNo','callApi')
      let objdata = {
        method : data,
        parameter : {
          'proportion': data1,
          'sampleNum':data2,
        }
      }
      this.axios.post('pass/testManagement/v1/api/reflection/executeDyMethodUtil',objdata,{individualType: 'json'}).then(res => {
        if (res.code == 0 || res.code == 200) {
          //将数组重新赋值，解决DOM树不重新渲染的问题
          let data = JSON.parse(JSON.stringify(this.sample.tableData2))
          this.sample.tableData2 = []
          //如果规则名称为比率抽样,则将返回的数据进行拆分
          if (this.form.ruleNo == 'R0004') {
            //1.将返回的字符串转换成对象 2.将对象的key,value循环出来
            let resultData = JSON.parse(res.data)
            let resultKeys = Object.keys(resultData)
            let resultValues = Object.values(resultData)
            data.forEach((item,index) =>{
              let indexs = resultKeys.findIndex(items => item.ruleItemName == items)
              item.ruleItemValue = resultValues[indexs] instanceof Array ? JSON.stringify(resultValues[indexs]) : resultValues[indexs]
            })
          }else{
            data.forEach(item =>{
              item.ruleItemValue = res.data
            })
          }
          this.sample.tableData2 = data
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message)
        }
        this.accountLoading = false
        }).catch(e => {
          this.accountLoading = false
          this.$message.error(e.message)
      })
    },
    //抽样保存
    addData(){
      if (this.sample.tableData2.length < 1) {
        this.$message.warning('输出项目中无数据，请先查询要执行此操作的数据')
        return
      }
      for(let i = 0; i< this.sample.tableData2.length; i++){
        if (!this.sample.tableData2[i].ruleItemValue) {
          this.$message.warning('输出项目中无输出结果，不能进行确定操作')
          return
        }
      }
       // 合并已接收任务数据
      let obj =  Object.assign({},this.baseData)
      //通过规则名称查询出对应的数据行
      let tempData = this.ruleTypeName.find(item =>{
        if(item.ruleNo == this.form.ruleNo){
          return item
        }
      })
      obj.limsBaseRule = tempData
      let tempArr = JSON.parse(JSON.stringify(this.sample.tableData1)) 
      this.sample.tableData2.map(item =>{
        tempArr.push(item)
      })
      obj.limsBaseRuleDS = tempArr
      this.addLoading = true
      this.axios.post('pass/testManagement/v1/limssamplesmps/sampling',obj, {individualType: 'json'}).then(res => {
        if (res.code == 0 || res.code == 200) {
          this.dialogTableVisible = false
          this.$message.success(res.message);
          this.$emit('refresh')
        } else {
         this.$message.error(res.message)
        }
        this.addLoading = false
      }).catch(e => {
        this.addLoading = false
        this.$message.error(e.message)
      })
    },
    //抽样保存
    aginAddData(){
      if (this.sample.tableData2.length < 1) {
        this.$message.warning('输出项目中无数据，请先查询要执行此操作的数据')
        return
      }
      for(let i = 0; i< this.sample.tableData2.length; i++){
        if (!this.sample.tableData2[i].ruleItemValue) {
          this.$message.warning('输出项目中无输出结果，不能进行确定操作')
          return
        }
      }
       // 合并已接收任务数据
      let obj =  Object.assign({},this.baseData)
      //通过规则名称查询出对应的数据行
      let tempData = this.ruleTypeName.find(item =>{
        if(item.ruleNo == this.form.ruleNo){
          return item
        }
      })
      obj.limsBaseRule = tempData
      let tempArr = JSON.parse(JSON.stringify(this.sample.tableData1)) 
      this.sample.tableData2.map(item =>{
        tempArr.push(item)
      })
      obj.limsBaseRuleDS = tempArr
      this.addLoading = true
      this.axios.post('pass/testManagement/v1/limssamplesmps/repeatSampling',obj, {individualType: 'json'}).then(res => {
        if (res.code == 0 || res.code == 200) {
          this.dialogTableVisible = false
          this.$message.success(res.message);
          this.$emit('refresh')
        } else {
         this.$message.error(res.message)
        }
        this.addLoading = false
      }).catch(e => {
        this.addLoading = false
        this.$message.error(e.message)
      })
    },
    closeDialog(){
      this.saveAccount = {}
      this.form={
        ruleNo: '',
        ruleTypeNo:''
      }
      this.sample.tableData1 = []
      this.sample.tableData2 = []
      this.showButton = true
      this.addLoading = false
      this.dialogTableVisible = false
    },
    // 查询规则名称数据
    ruleData () {
      this.ruleDatas = []
      this.ruleTypeName = []
      let obj = {
        object:{
          ruleTypeCode:this.form.ruleTypeNo,
          validFlag:1
        },
        pageIndex:1,
        pageSize:9999,
      }
      this.axios.post('pass/baseManagement/v1/limsbaserules/queryLimsBaseRuleInfoPage',obj, {individualType: 'json'}).then(res => {
        if (res.code == 0 ||res.code == 200) {
          let data  = res.data.list
          data.forEach(item =>{
            item.validFlag1 = item.validFlag == 0 ? '无效' : item.validFlag == 1 ? '有效' : ''
          })
          this.ruleTypeName = this.ruleDatas = data
        } else {
         this.$message.error(res.message)
        }
        this.saveLoading = false
      }).catch(e => {
        this.saveLoading = false
        this.$message.error(e.message)
      })
    },
    //查询
    tableHeaderCellStyle () {
      return 'color: rgb(255,255,255);border-bottom: 1px solid #DCDFE7;'
    }
  },
  watch: {
    showFlag(arg) {
      let _this = this;
      _this.dialogTableVisible = true;
      if (_this.Params !== null) {
        if (typeof(this.Params) == 'object' ) {
          _this.baseData = Object.assign({}, this.Params);
        }
        if (typeof(this.Params) == 'string') {
          this.showButton = false
          this.axios.post('pass/testManagement/v1/limsdataruleds/queryLimsDataRuleDByRuleId?ruleId='+this.Params, {individualType: 'json'}).then(res => {
            if (res.code == 0 ||res.code == 200) {
              let data  = res.data
              data.forEach(item =>{
                if (item.isPara == 1) {
                  this.sample.tableData1.push(item)
                }else{
                  this.sample.tableData2.push(item)
                }
              })
              this.showButton = false
              this.dialogTableVisible = true
            } else {
             this.$message.error(res.message)
            }
          }).catch(e => {
            this.$message.error(e.message)
          })
        }
      }
    },
  },
};
</script>

<style  scoped>

</style>
