<template>
  <div class="delist_wrap">
    <div class="cd_ps_top">
      <i class="el-icon-back" @click="goToPreviousPage()"></i>
      <span>{{ $route.query.type }}取样登记</span>
    </div>
    <div class="basis_wrap">
      <el-form :inline="true" :model="basisViewForm" :rules="basisViewRules" ref="basisViewForm" class="demo-form-inline" label-position="top">
        <div class="inq-child block_wrap">
          <h5>样品基础信息</h5>
          <el-form-item label="所属分厂" prop="branchName">
            <el-select v-model="basisViewForm.branchName" placeholder="请选择" clearable class="fiw">
              <el-option
                v-for="(item, j) in branchObj.branch"
                :key="j"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="样品分类" prop="sampleType">
            <el-select v-model="basisViewForm.sampleType" placeholder="请选择" clearable class="fiw">
              <el-option
                v-for="(item, j) in branchObj.sampleTypes"
                :key="j"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="样品名称" prop="sampleName">
            <el-select v-model="basisViewForm.sampleName" placeholder="请选择" clearable class="fiw">
              <el-option
                v-for="(item, j) in branchObj.sampleTemplateInfoVOS"
                :key="j"
                :label="item.sampleName"
                :value="item.sampleName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="交接人" prop="handover">
            <el-select v-model="basisViewForm.handover" filterable placeholder="请选择" clearable class="fiw">
              <el-option
                v-for="(item, j) in revieoptionwer"
                :key="j"
                :label="item.nickName"
                :value="item.userName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="取样人" prop="sampler">
            <el-input v-model="basisViewForm.sampler" placeholder="" class="fiw" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="审核人" prop="reviewer">
            <el-select v-model="basisViewForm.reviewer" filterable placeholder="请选择" clearable class="fiw">
              <el-option
                v-for="(item, j) in checkerOption"
                :key="j"
                :label="item.nickName"
                :value="item.userName">
              </el-option>
            </el-select>
          </el-form-item>

<!--          <el-form-item label="车牌号" prop="reviewer">-->
<!--            <el-select v-model="basisViewForm.reviewer" filterable placeholder="请选择" clearable class="fiw">-->
<!--              <el-option-->
<!--                v-for="(item, j) in checkerOption"-->
<!--                :key="j"-->
<!--                :label="item.userName"-->
<!--                :value="item.userName">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="车牌号" prop="licensePlate">-->
<!--            <el-input v-model="basisViewForm.licensePlate" placeholder="如果没有'车牌号'请输入'无'" class="fiw"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="供货单位" prop="supplier">-->
<!--            <el-input v-model="basisViewForm.supplier" placeholder="" class="fiw"></el-input>-->
<!--          </el-form-item>-->
        </div>
        <div class="inq-child block_wrap">
          <div class="inspection">
            <h5></h5>
            <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEditTable('新增')">新增表单</el-button>
          </div>
          <el-table class="production_wrap" :cell-class-name="addClass" :data="gridData" style="width: 100%">
            <el-table-column
              prop="number"
              width="50"
              label="序号">
            </el-table-column>
            <el-table-column
              width="200"
              prop="samplingTime"
              label="取样时间">
            </el-table-column>
            <el-table-column
              prop="sample"
              label="取样编号">
            </el-table-column>
            <el-table-column
              prop="sampleAddressName"
              label="取样地点">
            </el-table-column>
            <el-table-column
              prop="licensePlate"
              label="车牌号">
            </el-table-column>
            <el-table-column
              prop="supplier"
              label="供货单位">
            </el-table-column>
            <el-table-column
              width="160"
              prop="remark"
              label="备注">
              <template slot-scope="scope">
                <span v-if="!scope.row.remark">
                  {{ scope.row.remark }}
                </span>
                <el-popover v-else width="300" class="reference" placement="bottom" trigger="hover" :content="scope.row.remark">
                  <div style="width:100%;height:100%;overflow:hidden" slot="reference">{{ scope.row.remark }}</div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              width="200"
              label="操作">
              <template slot-scope="scope">
                <el-link @click="handleEditTable('编辑', scope.row, scope.$index)" type="primary">编辑</el-link>
                <el-link @click="handleEditTable('复制', scope.row,  scope.$index)" type="primary">复制</el-link>
                <el-popconfirm title="确认删除该条数据？" @onConfirm="handledeleteTable(scope.row)">
                  <el-link slot="reference" type="primary">删除</el-link>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <el-dialog class="addBatchfiw" :title="dialogTitle" destroy-on-close :visible.sync="dialogVisible" width="400px">
      <el-row>
        <el-form :model="addBatchForm" :rules="addBatchRules" ref="addBatchForm" label-width="100px" class="demo-ruleForm">
          <el-col :span="24">
            <el-form-item label="取样时间:" prop="samplingTime">
              <el-date-picker v-model="addBatchForm.samplingTime" type="datetime" placeholder="选择日期时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              class="fiw"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="取样编号:" prop="sample">
              <el-input type="text" placeholder="请输入" v-model="addBatchForm.sample" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="取样地点:" prop="sampleAddressId">
              <el-select v-model="addBatchForm.sampleAddressId" placeholder="请选择" clearable class="fiw">
                <el-option
                  v-for="(item, j) in sampleoptions"
                  :key="j"
                  :label="item.address"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="车牌号:" prop="licensePlate">
              <el-input type="text" placeholder="请输入" v-model="addBatchForm.licensePlate" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="供货单位:" prop="supplier">
              <el-input type="text" placeholder="请输入" v-model="addBatchForm.supplier" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">
              <el-input type="textarea" v-model="addBatchForm.remark" maxlength="1024" :rows="4" class="fiw"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitChanpinForm()">保 存</el-button>
      </span>
    </el-dialog>
    <div class="cd_ps_bottom">
      <el-button size="small" @click="goToPreviousPage()">返回</el-button>
      <el-button size="small" @click="preservation('保存')" type="primary">保存</el-button>
    </div>
  </div>
</template>
<script>
import * as api from '@/api/business/laboratory/samplRegistration/index'
import moment from 'moment'
export default  {
  data() {
    return {
      dialogVisible: false,
      dialogTitle: null,
      gridDataIndex: '',
      gridData: [],
      branchObj: {}, // 所属分厂三联动options
      revieoptionwer: [], // 交接人
      checkerOption: [], // 审核人options
      sampleoptions: [], // 取样地点options
      basisViewForm: {
        branchName: null, // 所属分厂
        sampleType: null, // 样品分类
        sampleName: null, // 样品名称
        sampleId: null, // 样品名称ID
        handover: null, // 交接人
        sampler: this.$store.state.user.nickName, // 取样人
        reviewer: null, // 审核人
        licensePlate: null, // 车牌号
        supplier: null // 供货单位
      },
      basisViewRules: {
        branchName: [
          { required: true, message: '请选择所属分厂', trigger: 'change' }
        ],
        sampleType: [
          { required: true, message: '请选择样品分类', trigger: 'change' }
        ],
        sampleName: [
          { required: true, message: '请选择样品名称', trigger: 'change' }
        ],
        handover: [
          { required: false, message: '请选择交接人', trigger: 'change' }
        ],
        reviewer: [
          { required: true, message: '请选择审核人', trigger: 'change' }
        ],
        // licensePlate: [
        //   { required: true, message: '请输入车牌号', trigger: 'blur' },
        //   {
        //     validator: (rule, value, callback) => {
        //       let xreg=/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/
        //       let creg =/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/
        //       if (xreg.test(value) || creg.test(value) || value == '无') {
        //         callback()
        //       } else {
        //         callback('请输入正确的车牌号格式')
        //       }
        //     }
        //   }
        // ],
        // supplier: [
        //   { required: true, message: '请输入供货单位', trigger: 'blur' }
        // ]
      },
      addBatchForm: {
        samplingTime: null, // 取样时间
        sample: null, // 取样编号
        sampleAddressName: null, // 取样地点
        sampleAddressId: null, // 取样地点ID
        licensePlate: null,   // 车牌号
        supplier: null,  // 供货单位
        remark: null // 备注
      },
      addBatchRules: {
        samplingTime: [
          { required: true, message: '请选择取样时间', trigger: 'blur' }
        ],
        sample: [
          { required: true, message: '请输入取样编号', trigger: 'blur' }
        ],
        sampleAddressId: [
          { required: true, message: '请选择取样地点', trigger: 'change' }
        ],
        licensePlate: [
          { required: true, message: '请输入车牌号', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let xreg=/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/
              let creg =/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/
              if (xreg.test(value) || creg.test(value) || value == '无') {
                callback()
              } else {
                callback('请输入正确的车牌号格式')
              }
            }
          }
        ],
        supplier: [
          { required: true, message: '请输入供货单位', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.branchFactory() // 所属分厂三联动
    api.getRevusers().then(res => { // 交接人
      if (res.code === 200) {
        this.revieoptionwer = res.data
      }
    })
    api.getTemplateInfoUsers().then(res => { // 审核人options
      if (res.code === 200) {
        this.checkerOption = res.data
      }
    })
  },
  methods: {
    addClass({
      row,
      column,
      rowIndex,
      columnIndex
    }) {
      //第八列添加 red 类
      if (columnIndex == 3) {
        return 'addclassName'
      }
    },
    branchFactory(obj = {}) { // 所属分厂三联动
      obj.userId = this.$store.state.user.userId
      api.getTemplateBranchInfoVO(obj).then(res => {
        if (res.code === 200) {
          this.branchObj = res.data
          if (res.data.branch.length == 1) {
            this.basisViewForm.branchName = res.data.branch[0] // 所属分厂
          }
          if (res.data.sampleTypes.length == 1) {
            this.basisViewForm.sampleType = res.data.sampleTypes[0] // 样品分类
          }
          if (res.data.sampleTemplateInfoVOS.length == 1) {
            this.basisViewForm.sampleName = res.data.sampleTemplateInfoVOS[0].sampleName // 样品名称
          }
        }
      })
    },
    handledeleteTable(val) { // 删除
      this.gridData.splice(val.number - 1, 1)
      this.gridData.forEach((res, j) => {
        this.gridData[j].number = j + 1
      })
    },
    handleEditTable(type, val,index) {
      switch(type) {
        case '新增':
          if (this.basisViewForm.sampleId === null) {
            this.$message({ message: '请先选择样品名称', type: 'warning' })
            return
          }
          this.dialogTitle = type
          this.dialogVisible = true
          this.addBatchForm.samplingTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss') // 取样时间
          this.addBatchForm.remark = null
          this.addBatchForm.licensePlate = null
          this.addBatchForm.supplier = null
          this.addBatchForm.sample = null
          break
        case '编辑':
          if (this.basisViewForm.sampleId === null) {
            this.$message({ message: '请先选择样品名称', type: 'warning' })
            return
          }
          this.dialogTitle = type
          this.gridDataIndex = index
          this.addBatchForm = {
            number: this.gridData && this.gridData[index].number || null,
            samplingTime: this.gridData && this.gridData[index].samplingTime || null, // 取样时间
            sample: this.gridData && this.gridData[index].sample || null, // 取样编号
            sampleAddressName: this.gridData && this.gridData[index].sampleAddressName || null, // 取样地点
            sampleAddressId: this.gridData && this.gridData[index].sampleAddressId || null, // 取样地点ID
            licensePlate : this.gridData && this.gridData[index].licensePlate || null,
            supplier : this.gridData && this.gridData[index].supplier || null,
            remark: this.gridData && this.gridData[index].remark || null // 备注
          }
          this.dialogVisible = true
          break
        case '复制':
          this.gridData.unshift({ ...val })
          this.gridData.forEach((res, j) => {
            this.gridData[j].number = j + 1
          })
          break
      }
    },
    goToPreviousPage() { // 返回上一页
      this.$router.push({ path: this.$router.pullPath })
    },
    submitChanpinForm() {
      this.$refs['addBatchForm'].validate(valid => {
        if (valid) {
          this.sampleoptions.forEach(item => {
            if (item.id == this.addBatchForm.sampleAddressId) {
              this.addBatchForm.sampleAddressName = item.address
            }
          })
          if (this.dialogTitle === '新增') {
            this.gridData.unshift({ ...this.addBatchForm })
            this.gridData.forEach((item, j) => {
              this.gridData[j].number = j + 1
            })
          } else {
            // this.gridData[this.addBatchForm.number - 1] = this.addBatchForm
            // this.gridData = [...this.gridData]

           let index = this.gridDataIndex
            this.gridData[index].samplingTime = this.addBatchForm.samplingTime
            this.gridData[index].remark = this.addBatchForm.remark
            this.gridData[index].licensePlate = this.addBatchForm.licensePlate
            this.gridData[index].supplier = this.addBatchForm.supplier
            this.gridData[index].sample = this.addBatchForm.sample

          }
          this.dialogVisible = false
        }
      })
    },
    preservation(type) {
      this.$refs['basisViewForm'].validate(valid => {
        if (valid) {
          if (this.gridData.length == 0) {
            this.$message.error('表单不能为空')
            return
          }
          let obj = {
            handover: this.basisViewForm.handover, // 交接人
            reviewer: this.basisViewForm.reviewer, // 审核人
            sampleId: this.basisViewForm.sampleId, // 样品模板ID
            sampleName: this.basisViewForm.sampleName, // 样品名称
            // sampler: this.basisViewForm.sampler, // 取样人
            sampler: this.$store.state.user.name,
            licensePlate: this.basisViewForm.licensePlate, // 车牌号
            supplier: this.basisViewForm.supplier, // 供货单位
            particulars: []
          }
          this.gridData.forEach(item => {
            obj.particulars.push({
              sample: item.sample, // 取样编号
              sampleAddressId: item.sampleAddressId, // 取样地点ID
              samplingTime: item.samplingTime, // 取样时间
              licensePlate: item.licensePlate,
              supplier: item.supplier,
              remark: item.remark // 备注
            })
          })
          api.saveBatchRegisterInfo(obj).then(res => {
            if (res.code === 200) {
              this.$message({ message: '批量新增成功', type: 'success' })
              this.goToPreviousPage()
            }
          })
        }
      })
    }
  },
  watch: {
    'basisViewForm.branchName': function(val) {
      this.basisViewForm.sampleType = null // 样品分类
      this.basisViewForm.sampleName = null // 样品名称
      this.branchFactory({ branch: val }) // 所属分厂三联动
    },
    'basisViewForm.sampleType': function(val) {
      this.basisViewForm.sampleName = null // 样品名称
      this.branchFactory({ branch: this.basisViewForm.branchName, sampleType: val }) // 所属分厂三联动
    },
    'basisViewForm.sampleName': function(val) {
      this.basisViewForm.sampleId = null
      this.basisViewForm.reviewer = null // 审核人
      this.sampleoptions = [] // 取样地点options
      this.branchObj.sampleTemplateInfoVOS.forEach(item => {
        if (item.sampleName === val) {
          this.basisViewForm.sampleId = item.id
        }
      })
      if (this.basisViewForm.sampleId !== null) {
        api.getReviewer(this.basisViewForm.sampleId).then(res => { // 当前审核人
          if (res.code === 200) {
            this.basisViewForm.reviewer = res.data
          }
        })
        api.getSampleTemplate(this.basisViewForm.sampleId).then(res => { // 取样地点options、样品自定义信息和检验项
          if (res.code === 200) {
            // this.sampleoptions = res.data
            this.sampleoptions = res.data.sampleAddressList || [] // 取样地点options
            this.sampleoptions.forEach(item => {
              if (item.isDef) {
                this.addBatchForm.sampleAddressId = item.id // 带出默认的id
              }
            })
          }
        })
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.addBatchfiw {
  .fiw {
    width: 100%;
  }
}
.addclassName {
  div {
    width: 160px;
    white-space:nowrap;
    text-overflow:ellipsis;
    overflow: hidden;
  }
}
</style>
