<template>
  <el-row class="deploy-details-box">
    <el-row class="deploy-details-ps-top">
      <i class="el-icon-back" @click="routerGoClick"></i>
      <span>检验项模板管理{{testId?'编辑' :'新增'}}</span>
    </el-row>
    <el-row class="deploy-details-main" style="flex: 1">
      <!-- 油剂调配信息 -->
      <DoorView title="基础信息">
        <el-form slot="main" ref="formOne" :model="fromData" :rules="rules" :inline="true" label-position="top"
                 class="el-from-flex">
          <el-form-item label="检验项名称" prop="itemName">
            <el-input v-model="fromData.itemName" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="试样量">
            <el-input-number v-model="fromData.sampleVolume" controls-position="right"
                             :controls="false" :min="0" :max="99999999999"
                             style="width: 300px"></el-input-number>
          </el-form-item>
          <el-form-item></el-form-item>
        </el-form>
      </DoorView>
      <DoorView title="品管检验结果">
        <div slot="main">
          <el-table
            slot="main"
            :data="fromData.tinspectionParamsList"
            style="width: 100%">
            <el-table-column
              prop="name"
              label="名称"
            >
              <template slot-scope="scope">
                <el-form  @submit.native.prevent :model="scope.row" :ref="'a'+scope.$index" v-if="scope.row.isCompile">
                  <el-form-item
                    style="margin: 0"
                    prop="name"
                    :show-message="false"
                    :rules="[{ required: true,trigger: 'blur' }]"
                  >
                    <el-input v-model="scope.row.name" placeholder="请输入内容"
                              style="max-width: 200px"></el-input>
                  </el-form-item>
                </el-form>
                <span v-else>{{scope.row.name}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="symbol"
              label="符号"
            >
              <template slot-scope="scope">
                <el-form  @submit.native.prevent :model="scope.row" :ref="'b'+scope.$index" v-if="scope.row.isCompile">
                  <el-form-item
                    style="margin: 0"
                    prop="symbol"
                    :show-message="false"
                    :rules="[{
            required: true,
            validator:sumbrules,
            trigger: 'blur'
          }]"
                  >
                    <el-input v-model="scope.row.symbol" placeholder="请输入内容"
                              style="max-width: 200px"></el-input>
                  </el-form-item>
                </el-form>
                <span v-else>{{scope.row.symbol}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="decimalPlaces"
              label="保留小数位数">
              <template slot-scope="scope">
                <el-form  @submit.native.prevent :model="scope.row" :ref="'c'+scope.$index" v-if="scope.row.isCompile">
                  <el-form-item
                    style="margin: 0"
                    prop="decimalPlaces"
                    :show-message="false"
                    :rules="[{ required: true,trigger: 'blur' }]"
                  >
                    <el-input-number v-model="scope.row.decimalPlaces" controls-position="right"
                                     :controls="false" :min="0" :max="9"
                                     style="width: 200px"></el-input-number>
                  </el-form-item>
                </el-form>
                <span v-else>{{scope.row.decimalPlaces}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="num"
              label="操作">
              <template slot-scope="scope">
                <el-link type="primary" v-if="fromData.id" @click="goTestListDetails(scope)">
                  {{scope.row.isCompile?`保存`:`编辑`}}
                </el-link>
                <el-popconfirm
                  title="确定删除这条数据吗？"
                  @onConfirm="deleteTestList(scope)"
                >
                  <el-link slot="reference" type="primary">删除</el-link>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <div class="add-border" @click="addTestInfoList">+ 添加中间值</div>
          <el-form slot="main" :rules="rules" ref="formTwo" :model="fromData" :inline="true" label-width="180px"
                   label-position="top" class="el-from-flex">
            <el-form-item label="计算结果公式" prop="calculationResultFormula">
              <el-input v-model="fromData.calculationResultFormula" style="width: 300px"
                        @change="formulaChange"></el-input>
            </el-form-item>
            <el-form-item label="保留小数位" prop="decimalPoint">
              <el-input-number v-model="fromData.decimalPoint" controls-position="right" :controls="false" :min="0"
                               :max="9"
                               style="width: 300px"></el-input-number>
            </el-form-item>
            <el-form-item label="单位" prop="unit">
              <el-input v-model="fromData.unit" style="width: 300px"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </DoorView>
    </el-row>
    <TabBar>
      <el-row class="deploy-details-ps-bottom" slot="tabBar-Right">
        <el-button size="small" @click="routerGoClick">返回</el-button>
        <el-button size="small" type="primary" @click="affirmClick">{{testId?'保存':'新增'}}</el-button>
      </el-row>
    </TabBar>
  </el-row>
</template>

<script>
  import DoorView from '@/components/YuComponents/DoorView.vue'
  import TabBar from '@/components/MingComponents/TabBar.vue'
  import * as inspectionItemTemplate from '@/api/business/baseData/inspectionItemTemplate'

  export default {
    name: 'DeployDetails',
    data() {
      const self = this
      const formulaVerify = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('计算结果公式不能为空'))
        }
        //出现连续运算符报错
        if (/[\+\-\*\/\^]{2,}/.test(value)) {
          return callback(new Error('请检查计算公式是否正确或使用了未定义的符号'))
        }
        let calc = value
        self.fromData.tinspectionParamsList.forEach((item) => {
          let reg = new RegExp(item.symbol, 'g')
          calc = calc.replace(reg, '(1)')
        })

        //修改数学公式符号为js符号
        calc = calc.replace(/\^/g, '**')
        calc = calc.replace(/[\{,\[]/g, '(')
        calc = calc.replace(/[\},\]]/g, ')')
        calc = calc.replace(/\d+\%/g, '0.01')

        try {
          eval(calc)
        } catch {
          return callback(new Error('请检查计算公式是否正确或使用了未定义的符号'))
        }
        callback()
      }
      return {
        testId: null,
        //提交保存的数据
        fromData: {
          id: null,
          itemName: null,
          sampleVolume: null,
          calculationResultFormula: null,
          decimalPoint: 0,
          unit: null,
          tinspectionParamsList: [{ id: null, name: null, symbol: null, decimalPlaces: null, isCompile: true }]
        },
        //表格数据
        tableData: [{
          num: 'A',
          statusName: true,
          isCompile: false
        }],
        //校验数据
        rules: {
          itemName: [{ required: true, message: '请输入检验项名称', trigger: 'blur' }],
          calculationResultFormula: [{
            required: true,
            validator: formulaVerify,
            trigger: 'change'
          }],
          decimalPoint: [{ required: true, message: '请输入保留小数位', trigger: 'blur' }],
          unit: [{ required: true, message: '请输入单位', trigger: 'blur' }]
        },
        sumbrules: (rule, value, callback) => {
          if(value===null){
            return callback(new Error())
          }
          if (/[\+\-\*\/\^\%\=\.]/.test(value)) {
            this.$message.error('请勿在符号中使用运算符')
            return callback(new Error())
          }
          if (/^[0-9]+.?[0-9]*$/.test(value)) {
            this.$message.error('请勿在符号中使用纯数字')
            return callback(new Error())
          }
          let num =0
          this.fromData.tinspectionParamsList.forEach(item=>{
            console.log('是不是这里',item)
            if (item.symbol&&item.symbol.indexOf(value)>-1||value.indexOf(item.symbol)>-1){
              ++num;
            }
          })
          if(num>1){
            this.$message.error('存在字段包含或重复的符号')
            return callback(new Error('存在重复符号'))
          }
          callback()
        }
      }
    },
    components: { DoorView, TabBar },
    created(e) {
      this.testId = this.$route.query.id || null
      if (this.testId) {
        this.update()
      }
    },
    methods: {
      update() {
        inspectionItemTemplate.getInspectionItemTemplate(this.testId).then(res => {
          this.fromData = { ...res.data, tinspectionParamsList: res.data.inspectionParamsVOList }
          delete this.fromData.inspectionParamsVOList
          this.fromData.tinspectionParamsList.forEach((item, index) => {
            this.fromData.tinspectionParamsList[index].isCompile = false
          })
        })
      },
      // 返回按钮
      routerGoClick() {
        this.$router.push({ url: '/baseData/testSelect' })
      },
      //检验结果校验,isAll是否检查全部，为false时候index必传
      verify(isAll=true,index){
        let self = this
        let isGo = true
        for (let i = 0; i < this.fromData.tinspectionParamsList.length; i++) {
          if (!isAll&&index!=i){
            continue
          }
          let item = this.fromData.tinspectionParamsList[i]
          if (item.isCompile) {
            this.$refs['a' + i].validate(v => {
              if (!v) {
                if (item.name == null&&isGo) {
                  self.$message.error('品管检验结果名称不能为空,请检查检验结果列表')
                }
                isGo = false
              }
            })
            this.$refs['b' + i].validate(v => {
              if (!v) {
                if (item.symbol == null&&isGo) {
                  self.$message.error('品管检验结果符号不能为空,请检查检验结果列表')
                } else if (/[\+\-\*\/\^]/.test(item.symbol)&&isGo) {
                  self.$message.error('品管检验结果符号不能存在运算符')
                }
                isGo = false
              }
            })
            this.$refs['c' + i].validate(v => {
              if (!v) {
                if (item.decimalPlaces == null&&isGo) {
                  self.$message.error('品管检验结果保留小数位不能为空,请检查检验结果列表')
                }
                isGo = false
              }
            })
          }
        }
        return isGo
      },
      // 保存按钮
      affirmClick() {
        let allow = true
        this.$refs['formTwo'].validate((v) => {
          if (!v) {
            allow = false
            return false
          }
        })
        this.$refs.formOne.validate(v => {
          if (!v) {
            allow = false
            return false
          }
        })
        console.log('看看allow',allow)

        if (!allow||!this.verify()) return
        if (this.testId) {
          inspectionItemTemplate.saveInspectionItemTemplate(this.fromData).then(res => {
            this.$message({
              message: '检验项模板编辑成功',
              type: 'success'
            })
            this.update()
            this.routerGoClick()
          })
        } else {
          inspectionItemTemplate.saveInspectionItemTemplate(this.fromData).then(res => {
            this.$message({
              message: '检验项模板新增成功',
              type: 'success'
            })
            this.routerGoClick()
          })
        }
      },
      //列表编辑
      goTestListDetails(s) {
        if (this.fromData.tinspectionParamsList[s.$index].isCompile) {
          if(!this.verify(false,s.$index))return
          this.$set(this.fromData.tinspectionParamsList, s.$index, {
            ...this.fromData.tinspectionParamsList[s.$index],
            isCompile: !this.fromData.tinspectionParamsList[s.$index].isCompile
          })
          inspectionItemTemplate.saveInspectionParams({ ...s.row, inspectionId: this.testId }).then(res => {
            this.fromData.tinspectionParamsList[s.$index]=res.data
          })
        } else {
          this.$set(this.fromData.tinspectionParamsList, s.$index, {
            ...this.fromData.tinspectionParamsList[s.$index],
            isCompile: !this.fromData.tinspectionParamsList[s.$index].isCompile
          })
        }
      },
      //列表删除
      deleteTestList(s) {
        console.log(s.row)
        if (this.fromData.id) {
          if (this.fromData.calculationResultFormula.indexOf(s.row.symbol) >= 0) {
            this.$message.error('计算结果公式中存在该检验项符号,请先修改公式')
            return
          }
          if (s.row.id){
            inspectionItemTemplate.deleteInspectionParams(s.row.id).then(res => {
              this.fromData.tinspectionParamsList.splice(s.$index, 1)
            })
          }else {
            this.fromData.tinspectionParamsList.splice(s.$index, 1)
          }
        } else {
          this.fromData.tinspectionParamsList.splice(s.$index, 1)
        }
      },
      formulaChange(val) {
        this.fromData.formula = val.replace(/\s/g, '')
      },
      //添加中间值按钮
      addTestInfoList() {
        this.fromData.tinspectionParamsList.push({
          id: null,
          name: null,
          symbol: null,
          decimalPlaces: null,
          isCompile: true
        })
      }
    }

  }
</script>

<style lang="scss" scoped>
  .deploy-details-box {
    background-color: #ecf0f3;
    width: 100%;
    height: 100%;
    /*position: absolute;*/
    display: flex;
    flex-direction: column;

    .deploy-details-ps-top {
      width: auto;
      height: 60px;
      padding: 0 16px;
      position: sticky;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      font-size: 20px;
      background: #fff;
      z-index: 20;

      .el-icon-back {
        display: block;
        font-size: 26px;
        margin-right: 8px;
        cursor: pointer;
      }
    }

    .deploy-details-main {
      padding: 16px;
      overflow-y: auto;


      .add-border {
        margin-top: 16px;
        width: auto;
        height: 38px;
        text-align: center;
        line-height: 38px;
        color: #555555;
        font-size: 14px;
        border: 1px dashed rgba(0, 0, 0, 0.15);
      }

      .add-border:hover {
        border: 1px dashed rgba(0, 0, 0, 0.32);
        cursor: pointer;
      }
    }

    .deploy-details-ps-bottom {
      width: auto;
      height: 46px;
      padding: 0 16px;
      position: sticky;
      bottom: 0;
      left: 0;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      font-size: 20px;
      background: #fff;
      z-index: 20;
    }
  }

  .el-from-flex {
    display: flex;
    flex-wrap: wrap;
    display: -webkit-flex;

    & > div {
      flex: 1;
    }
  }
</style>
