<template>
  <div class="u-OA-jixiao">
    <div class="head">第一部分　试验项目输入</div>
    <table class="main-table">
      <tr>
        <td class="title" style="width: 100px">委托单位</td>
        <td class="content" style="width: 360px">
          {{ stepEdit.itdmWeituoInfo.weituoClient }}
        </td>
        <td class="title white" style="width: 100px">输入类型</td>
        <td class="content" style="width: 450px">
          详见委托管理
          <!-- <input v-model="stepEdit.shuruLeixing" style="text-align: center" /> -->
        </td>
      </tr>
      <tr>
        <td class="title" style="width: 100px;">实验信息</td>
        <td class="content">
          <!-- <input v-model="stepEdit.shiyanXinxi" :disabled="stepParameter.disabled" style="text-align: center" /> -->
          详见委托管理
        </td>
        <td class="title">定制需求</td>
        <td class="content">
          <div style="display: flex; align-items: center; justify-content: center">
            方案设计：
            <input type="radio" name="fangan" value="需要" v-model="stepEdit.fanganSheji" :disabled="stepParameter.disabled" />需要&nbsp;<input
              type="radio"
              name="fangan"
              value="不需要"
              v-model="stepEdit.fanganSheji"
              :disabled="stepParameter.disabled"
            />不需要&nbsp;&nbsp; 工装设计：
            <input type="radio" name="gongzhuang" value="需要" v-model="stepEdit.gongzhuangSheji" :disabled="stepParameter.disabled" />需要 &nbsp;<input
              type="radio"
              name="gongzhuang"
              value="不需要"
              v-model="stepEdit.gongzhuangSheji"
              :disabled="stepParameter.disabled"
            />不需要
          </div>

          <div style="display: flex; align-items: center; justify-content: center">
            试验评审：
            <input type="radio" name="shiyan" value="需要" v-model="stepEdit.shiyanPingshen" :disabled="stepParameter.disabled"/>需要 &nbsp;<input
              type="radio"
              name="shiyan"
              value="不需要"
              v-model="stepEdit.shiyanPingshen"
              :disabled="stepParameter.disabled"
            />不需要&nbsp;&nbsp; 用餐安排：
            <input type="radio" name="yongcan" value="需要" v-model="stepEdit.yongcanAnpai" :disabled="stepParameter.disabled"/>需要 &nbsp;<input
              type="radio"
              name="yongcan"
              value="不需要"
              v-model="stepEdit.yongcanAnpai"
              :disabled="stepParameter.disabled"
            />不需要
          </div>

          <div style="display: flex; align-items: center; justify-content: center">
            用车安排： <input type="radio" name="yongche" value="需要" v-model="stepEdit.yongcheAnpai" :disabled="stepParameter.disabled"/>需要
            &nbsp;<input
              type="radio"
              name="yongche"
              value="不需要"
              v-model="stepEdit.yongcheAnpai"
              :disabled="stepParameter.disabled"
            />不需要&nbsp;&nbsp; 住宿安排：
            <input type="radio" name="zhusu" value="需要" v-model="stepEdit.zhusuAnpai" :disabled="stepParameter.disabled"/>需要 &nbsp;<input
              type="radio"
              name="zhusu"
              value="不需要"
              v-model="stepEdit.zhusuAnpai"
              :disabled="stepParameter.disabled"
            />不需要
          </div>
        </td>
      </tr>
      <tr>
        <td class="title">客户<br />联系信息</td>
        <td class="content">
          姓名：{{ stepEdit.itdmWeituoInfo.weituoLxr }}　　电话：{{ stepEdit.itdmWeituoInfo.weituoPhone }}
        </td>
        <td class="title">合同编号</td>
        <td class="content">
          <input style="width: 100%; text-align: center" v-model="stepEdit.hetongBianhao" :disabled="stepParameter.disabled"/>
        </td>
      </tr>
      <tr>
        <td class="title">试验要求</td>
        <td class="content" colspan="3">
          <input style="width: 100%; text-align: center" v-model="stepEdit.shiyanYaoqiu" :disabled="stepParameter.disabled"/>
        </td>
      </tr>
      <tr>
        <td class="title">报告体系</td>
        <td class="content">
          <el-radio-group v-model="stepEdit.baogaoTixi" :disabled="stepParameter.disabled">
            <el-radio :label="0">海检版</el-radio>
            <el-radio :label="1">瑞莱版</el-radio>
            <el-radio :label="2">瑞莱海检版</el-radio>
          </el-radio-group>
        </td>
        <td class="title">资质要求</td>
        <td class="content">
          <el-checkbox-group v-model="stepEdit.zizhiYaoqiu" :disabled="stepParameter.disabled">
            <el-checkbox label="CNAS"></el-checkbox>
            <el-checkbox label="CMA"></el-checkbox>
            <el-checkbox label="ISTA"></el-checkbox>
            <el-checkbox label="船级社"></el-checkbox>
            <el-checkbox label="无"></el-checkbox>
          </el-checkbox-group>
        </td>
      </tr>
      <tr>
        <td class="title" style="width: 100px;">项目<br />虚拟结算额</td>
        <td class="content" colspan="3">
          <div style="display: flex;align-items: flex-end;">
            <el-form ref="xmShuruForm" :model="stepEdit" :rules="rules">
              <el-table :data="stepEdit.xnJiesuanPrice" class="u-dynamic-table" show-summary :summary-method="getSummaries" border ref="table" style="width: 800px;">
                <el-table-column type="index" label="序号" align="center" min-width="60"></el-table-column>
                <el-table-column prop="eqName" label="试验设备" align="center" min-width="100">
                  <template slot-scope="scope">
                    <el-form-item :prop="'xnJiesuanPrice.'+scope.$index+'.eqName'" :rules="rules.eqName">
                      <el-select v-model="scope.row.eqName" placeholder="请选择"   value-key="id" @change="chooseEquipment($event, scope.$index)" style="width: 100%;" :disabled="stepParameter.disabled">
                        <el-option
                          v-for="item in equipmentOptions"
                          :key="item.id"
                          :label="item.deviceName"
                          :value="item">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="typeName" label="重要性标准" align="center" min-width="120"></el-table-column>
                <el-table-column prop="time" label="试验时间(h)" align="center" min-width="120">
                  <template slot-scope="scope">
                    <el-form-item :prop="'xnJiesuanPrice.'+scope.$index+'.time'" :rules="rules.time">
                      <el-input-number v-model="scope.row.time" controls-position="right" @change="handleCheng(scope.row, scope.$index)" :min="1" :disabled="stepParameter.disabled"></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="unitPrice" label="试验单价(rmb/h)" align="center" min-width="140"></el-table-column>
                <el-table-column prop="costPrice" label="试验费用" align="center" min-width="100"></el-table-column>
                <el-table-column label="操作" min-width="100">
                  <template slot-scope="scope">
                    <el-button v-if="stepEdit.xnJiesuanPrice.length>1" type="text" size="small" @click="handleDelete(scope.row, scope.$index)" :disabled="stepParameter.disabled">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            
            <!-- <div class="addRow" @click="addRow" :style="{'pointer-events':stepParameter.disabled?'none':'auto'}">添加</div> -->
            <el-button class="addRow" @click="addRow" :disabled='stepParameter.disabled'>添加</el-button>
          </div>
        </td>
      </tr>
      <tr>
        <td class="title" style="width: 100px;">预计报价</td>
        <td class="content" colspan="3">
          <input style="width: 100%; text-align: center" v-model="stepEdit.yujiBaojia" :disabled="stepParameter.disabled"/>
          <div class="btn" style="margin-top:1%" @click="submitData" :style="{'pointer-events':stepParameter.disabled?'none':'auto'}">保存</div>
        </td>
      </tr>
      <tr>
        <td class="title">评审结论</td>
        <td class="content">
          <input style="width: 100%; text-align: center" v-model="stepReview.reviewResult"  :disabled="stepReview.disabled"/>
        </td>
        <td class="title">主审人</td>
        <td class="content">
            {{ stepReview.fqUserName }}
            {{stepReview.shenheTime}}
            <div class="btn" @click="submitReview" :style="{'pointer-events':stepReview.disabled?'none':'auto'}">保存</div>
        </td>
      </tr>
    </table>

  </div>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getDeviceList } from '@/api/api'

export default {
  name: 'itdmXmShuru',
  // mixins: [JeecgListMixin, mixinDevice],
  props: {
    // json
    tableData1: {
      type: Array,
      default: [],
      required: false
    }
  },
  data() {
    return {
      // 获取的流程数据
      stepParameter: {
        disabled: null
      },
      // 数据编辑信息
      stepEdit: {
        itdmWeituoInfo: {
          weituoClient: undefined,
          weituoLxr: undefined,
          weituoPhone: undefined,
        },
        xnJiesuanPrice: [{}],
        baogaoTixi: null,
        zizhiYaoqiu: [],
        // 第五部分
        hZXnJiesuanE: [],
        jixiaoData: null,
        xnJixiaoZonge: null,
        xnJixiaoZongeArr: [],
      },
      // 重要性标准
      defineXishu: [
        { type: 0, xishu: 0.40 },
        { type: 1, xishu: 0.70 },
        { type: 2, xishu: 1 },
      ],
      // 评审信息
      stepReview: {
        id: null,
        disabled: true,
        reviewResult: null,
        fqUserName: null,
        shenheTime: null
      },
      // 试验设备数据
      equipmentOptions: [],
      rules: {
        eqName: [
          { required: true, message: "不能为空", trigger: "change" }
        ],
        time: [
          { required: true, message: "不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getDevicePrice()
  },
  computed: {
    // importExcelUrl: function () {
    //   return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    // },
  },
  watch: {
    tableData1: {
      handler(newV, oldV){
        if(newV && newV[0]){
          console.log(newV)
          console.log(JSON.parse(newV[0].saveData))
          var arrData = newV
          this.stepParameter = arrData[0]
          this.stepParameter.disabled = !(arrData[0].dangqian && arrData[0].isUpdate)
          this.stepEdit = arrData[0].saveData ? JSON.parse(arrData[0].saveData) : this.stepEdit
          this.stepReview = arrData[1]
          this.stepReview.disabled = !(arrData[1].dangqian && arrData[1].isUpdate)
          this.stepReview.reviewResult = arrData[1].saveData ? JSON.parse(arrData[1].saveData).reviewResult : ''
          console.log(this.stepReview)
          
          if(!arrData[0].saveData){
            this.stepEdit.itdmWeituoInfo = arrData[0].itdmWeituoInfo
          }
        }
      },
      // deep: true,
      immediate: true
    }
  },
  methods: {
    // 获取试验设备列表
    getDevicePrice(){
      getDeviceList().then(response => {
        this.equipmentOptions = response
      })
    },
    // 设备下拉选择改变时改变对应值
    chooseEquipment(value, index){
      var row = this.stepEdit.xnJiesuanPrice[index]
      this.stepEdit.xnJiesuanPrice[index].type = value.zyxbz
      this.stepEdit.xnJiesuanPrice[index].typeName = value.zyxbzText
      this.stepEdit.xnJiesuanPrice[index].unitPrice = value.danjia
      this.stepEdit.xnJiesuanPrice[index].costPrice = row.unitPrice * row.time || 0
    },
    // input改变时计算相乘
    handleCheng(value, index){
      console.log(value)
      this.stepEdit.xnJiesuanPrice[index].costPrice = value.unitPrice * value.time || 0
    },
    // 项目虚拟结算额求和
    getSummaries(param){
      const { columns, data } = param;
      // console.log(columns, data)
      const len = columns.length;
      const sums = [];
      columns.forEach((column, index) => {
        // 第一列显示合计
        if (index === 0) {
          sums[index] = '合计';
          return;
        }else if(index === len - 2){ // 返回数据长度的最后一个
          const times = data.map(item => Number(item['time']));
          const prices = data.map(item=>Number(item['unitPrice']))
          const eqName = data.map(item => item['eqName']); // 谁改变也要写在这，要不不能触发
          // if (!times.every(value => isNaN(value))) {
            //通过reduce求和,curr为每一列的每个元素的值,return prev返回值给到sums[index]
            sums[index] = times.reduce((prev, curr, index) => {
              const value = Number(curr);
              //确定数据是否为空,不为空进行计算,为空返回原值
              if (!isNaN(value) && !isNaN(prices[index])) {
                //curr为工时,prices为单价,求得每行的金额,再通过reduce累加求和
                console.log(curr*prices[index], prev + curr*prices[index])
                return prev + curr*prices[index];
              } else {
                return prev;
              }
            }, 0);
          // } else {
          //   sums[index] = 0;
          // }
        }
      });
      return sums;
    },
    // 删除当前行
    handleDelete(row, index){
      this.stepEdit.xnJiesuanPrice.splice(index, 1)
    },
    // 添加一行
    addRow() {
      this.stepEdit.xnJiesuanPrice.push({})
    },
    submitData() {
      this.$refs["xmShuruForm"].validate(valid => {
        if (valid) {
          console.log(valid)
          // 计算核准虚拟结算额
          this.stepEdit.hZXnJiesuanE = this.changeData(this.stepEdit.xnJiesuanPrice, 'costPrice')
          // 项目绩效基础计算
          this.computeJixiaoData()
          // 计算虚拟结算绩效总额
          this.computeJXXishuZonge()


          var saveData = {
            runFlowPathStep: this.stepParameter.id,
            saveData: JSON.stringify(this.stepEdit),
          }
          this.$emit('save', saveData)
        }
      })
    },
    // 将试验类型相同的金额相加，用于：核准虚拟结算额和虚拟结算绩效总额
    changeData(array, key){
      let totalArr = []
      array.forEach(element => {
        var itemObj = { type: element.type, typeName: element.typeName, price: element[key] }
        if(totalArr.length === 0){
          totalArr.push(itemObj)
        } else {
          var index = totalArr.findIndex(res => res.type === element.type)
          if(index === -1){
            // 原来没有  push
            totalArr.push(itemObj)
          } else {
            // 原来有  相加
            totalArr[index].price += itemObj.price
          }
        }
      });
      // console.log(totalArr)
      return totalArr
    },
    // 项目绩效基础计算
    computeJixiaoData(){
      var dataLists = []
      for (let i = 0; i < this.stepEdit.hZXnJiesuanE.length; i++) {
        const item = this.stepEdit.hZXnJiesuanE[i];
        const money = item.price * 0.8
        if(money > 500000){
          // 50万以上
          console.log(money+':50万以上')
          var arr = [
            {
              type: item.type,
              typeName: item.typeName,
              fenduan: item.fenduan,
              bili: 0.05,
              ticheng: 50000 * 0.05,
              yue: 50000
            },
            {
              type: item.type,
              typeName: item.typeName,
              fenduan: item.fenduan,
              bili: 0.04,
              ticheng: 50000 * 0.04,
              yue: 50000
            },
            {
              type: item.type,
              typeName: item.typeName,
              fenduan: item.fenduan,
              bili: 0.03,
              ticheng: 400000 * 0.03,
              yue: 400000
            },
            {
              type: item.type,
              typeName: item.typeName,
              fenduan: item.fenduan,
              bili: 0.02,
              ticheng: (money - 500000) * 0.02,
              yue: money - 500000
            },
          ]
          dataLists.push(...arr)
        } else if (money > 100000){
          // 10万-50万之间
          console.log(money+':10万-50万之间')
          var arr = [
            {
              type: item.type,
              typeName: item.typeName,
              fenduan: item.fenduan,
              bili: 0.05,
              ticheng: 50000 * 0.05,
              yue: 50000
            },
            {
              type: item.type,
              typeName: item.typeName,
              fenduan: item.fenduan,
              bili: 0.04,
              ticheng: 50000 * 0.04,
              yue: 50000
            },
            {
              type: item.type,
              typeName: item.typeName,
              fenduan: item.fenduan,
              bili: 0.03,
              ticheng: (money - 100000) * 0.03,
              yue: money - 100000
            },
          ]
          dataLists.push(...arr)
        } else if (money > 50000){
          // 5万-10万（包含）之间
          console.log(money+':5万-10万（包含）之间')
          var arr = [
            {
              type: item.type,
              typeName: item.typeName,
              fenduan: item.fenduan,
              bili: 0.05,
              ticheng: 50000 * 0.05,
              yue: 50000
            },
            {
              type: item.type,
              typeName: item.typeName,
              fenduan: item.fenduan,
              bili: 0.04,
              ticheng: (money - 50000) * 0.04,
              yue: money - 50000
            },
          ]
          dataLists.push(...arr)
        } else if (money >= 0){
          // 0-5万（包含）之间
          console.log(money+':0-5万（包含）之间')
          var arr = [
            {
              type: item.type,
              typeName: item.typeName,
              fenduan: item.fenduan,
              bili: 0.05,
              ticheng: money * 0.05,
              yue: money
            },
          ]
          dataLists.push(...arr)
        }
      }
      this.stepEdit.jixiaoData = dataLists
    },
    // 计算虚拟结算绩效总额
    computeJXXishuZonge(){
      // 将试验类型相同的金额相加
      var noHasXishuZonge = this.changeData(this.stepEdit.jixiaoData, 'ticheng')
      var total = 0
      var arr = noHasXishuZonge.map(item => {
        var obj = this.defineXishu.find(res => res.type === item.type)
        // 根据试验类型*对应系数
        item.price = this.multiply(item.price, obj.xishu)
        console.log(item.price)
        // 计算出总和
        total += item.price
        return item
      })
      this.stepEdit.xnJixiaoZongeArr = arr
      console.log(total)
      this.stepEdit.xnJixiaoZonge = total
    },
    // 解决经度丢失
    multiply(num1, num2) {
      const num1Str = num1.toString();
      const num2Str = num2.toString();
      const num1Digits = num1Str.includes('.') ? num1Str.length - num1Str.indexOf('.') - 1 : 0;
      const num2Digits = num2Str.includes('.') ? num2Str.length - num2Str.indexOf('.') - 1 : 0;
      const precision = num1Digits + num2Digits;

      const num1Int = parseInt(num1Str.replace('.', ''));
      const num2Int = parseInt(num2Str.replace('.', ''));

      let result = num1Int * num2Int;
      result /= Math.pow(10, precision);

      return result;
    },

    submitReview() {
      var saveData = {
        runFlowPathStep: this.stepReview.id,
        saveData: JSON.stringify({reviewResult: this.stepReview.reviewResult}),
      }
      console.log(saveData)
      this.$emit('save', saveData)
    },
  },
}
</script>

<style lang="less">
.u-OA-jixiao{
  .el-radio-group{
    .el-radio__input.is-disabled+span.el-radio__label{
      color: rgba(0, 0, 0, 0.65) !important;
      cursor: auto !important;
    }
  }
  .el-checkbox-group{
    .el-checkbox__input.is-disabled+span.el-checkbox__label{
      color: rgba(0, 0, 0, 0.65) !important;
      cursor: auto !important;
    }
  }
  .el-input__inner{
    background: transparent !important;
  }
  .el-select{
    .el-input.is-disabled .el-input__inner{
      color: #606266 !important;
      background-color: transparent !important;
      cursor: auto !important;
    }
  }
  .el-table{
    background-color: transparent !important;
    border: solid 1px #808080 !important;
    thead{
      color: #3d3d3d !important;
    }
    tr{
      background-color: transparent !important;
    }
    th.el-table__cell{
      background-color: transparent !important;
      border-color: #808080 !important;
    }
    td.el-table__cell{
      border-color: #808080 !important;
    }
    .el-input__inner{
      background: transparent !important;
    }
    // 并且-有校验错误时显示
    .is-error {
      margin-bottom: 22px;
      .el-input__inner{
        border: 1px solid #F56C6C;
      }
    }
  }
}
</style>

<style scoped>
@import '~@assets/less/common.less';

table * {
  box-sizing: border-box;
  font-size: 14px;
}
table {
  border: 1px solid rgb(30, 53, 65);
  width: 100%;
  table-layout:fixed;
}
input {
  padding: 0 20px;
  height: 50px;
  outline: none;
  border: none;
  background: transparent;
}
td {
  text-align: center;
  border: 1px solid #1e3541;
}

tr {
  height: 50px;
}
.head {
    height: 35px;
    background-color: #FFFF00;
    text-align: center;
    line-height: 35px;
    font-weight: bold;
    font-size: 18px;
    border: 1px solid rgb(30, 53, 65);
}

.main-table {
  background-color: rgb(219, 238, 244);
}
.title {
  background-color: #fff;
  font-weight: bold;
  width: 100px;
}
.addRow {
  padding: 6px 10px;
  text-align: center;
  font-size: 12px;
  margin-left: 20px;
  /* width: 60px;
  height: 24px;
  background-color: #fff;
  border-radius: 4px;
  text-align: center;
  line-height: 24px;
  font-size: 12px;
  margin-left: 20px;
  cursor: pointer; */
}
.btn {
  display: inline-block;
  padding: 2px 10px;
  font-size: 13px;
  border: 1px solid rgb(3, 188, 244);
  color: rgb(8, 187, 241);
  border-radius: 4px;
  cursor: pointer;
  position: absolute;
  right: 3%;
}
</style>