<!--suppress ALL -->
<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="rules" :model="taskForm" label-well-code="right" label-width="100px" >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目名称" prop="projectId">
            <el-select v-model="taskForm.projectId" disabled filterable placeholder="项目名称" clearable value="">
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备型号" prop="devmodeId">
            <el-select v-model="taskForm.devmodeId" disabled filterable placeholder="设备型号" clearable value="">
              <el-option
                v-for="item in modelList"
                :key="item.id"
                :label="item.productModel"
                :value="item.productModel"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" >
          <el-form-item label="设备类型" prop="devtypeId">
            <el-select v-model="taskForm.devtypeId" disabled filterable placeholder="设备类型" clearable value="" value-key="id" @change="changeModel($event)">
              <el-option
                v-for="item in deviceTypeList"
                :key="item.id"
                :label="item.productName"
                :value="item"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备数量" prop="devcount">
            <el-input v-model.trim="taskForm.devcount" disabled type="text" placeholder="必填">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form ref="dataForm" :model="taskForm" :rules="rules">
      <el-row class="table-title">
        <el-col :span="6"><div class="title-header"><i class="el-icon-menu"/>数据列表</div></el-col>
        <el-button class="edit_btn" size="small" @click="addlist">新增</el-button>
      </el-row>

      <el-table :data="taskForm.batches"  class="tableBox" border >
        <!--<el-table-column :index="indexMethod" v-if="!isZero()" align="center" type="index" label="批次号" width="120"/>-->
        <el-table-column v-if="!isZero()" align="center" label="批次号" width="100">
        <template scope="scope">
          <el-form-item :prop="'batches.' + scope.$index + '.batchNumber'" :rules="rules.batchNumber">
            {{scope.row.batchNumber}}
            <!--<el-input v-model.trim="scope.row.batchNumber"  type="text" placeholder="必填" oninput="value=value.replace(/^\.+|[^\d.]/g,'')" />-->
          </el-form-item>
        </template>
        </el-table-column>
        <el-table-column v-if="isZero()" align="center" label="批次号" width="100">
        <template scope="scope">
          <el-form-item :prop="'batches.' + scope.$index + '.batchNumber'" :rules="rules.batchNumber">
            0
          </el-form-item>
        </template>
        </el-table-column>
        <el-table-column label="数量" width="100" align="center">
          <template scope="scope">
            <el-form-item :prop="'batches.' + scope.$index + '.batchCount'" :rules="rules.batchCount">
              <el-input v-model.trim="scope.row.batchCount"  type="text" placeholder="必填" oninput="value=value.replace(/^\.+|[^\d.]/g,'')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="关联合同" align="center" width="250">
          <template scope="scope">
            <el-form-item :prop="'batches.' + scope.$index + '.contractId'" :rules="rules.contractId">
              <el-select v-model="scope.row.contractId" filterable placeholder="选择合同" clearable value="">
                <el-option
                  v-for="item in contractList"
                  :key="item.id"
                  :label="item.contractNumber"
                  :value="item.id"
                   style="width: 250px"/>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" :disabled="checkDetail(scope.row)" @click="detailContract(scope.row.contractId)">合同详情</el-button>
            <el-button type="text" @click="deletelist(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="subBtn" type="primary" @click="saveData">提交</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { updateBatch,getProjectList,getModelList,getContractList,getBatchNumber,getBatchList,getContractDetail } from '@/api/batch'
import { getDeviceList } from '@/api/factory'
export default {
  name: 'CreateDevice',
  data() {
    return {
      startnumber : 231,
      listitem:{},
      subBtn: true,
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      deviceList: null, // 在产设备列表
      devTypeId: '',
      projectName: '',
      isstored: '',
      devTypeName: '',
      taskForm: {
        batches: [], // 列表数据
        taskId:'',
        devtypeId: '',
        projectId: '',
        devmodeId: '',
        devcount: '',
        isstored:''
      }, // 表单
      equipmentFile: null,
      textMap: {
        update: '生成设备',
        create: '',
        detail: ''
      }, // 表头显示标题
      deviceTypeList: null, // 设备类型列表
      contractList: null,
      rules: {
        devtypeId: [{ required: true, message: '设备类型不能为空', trigger: ['blur', 'change'] }],
        projectId: [{ required: true, message: '项目名称不能为空', trigger: ['blur', 'change'] }],
        devmodeId: [{ required: true, message: '设备型号不能为空', trigger: ['blur', 'change'] }],
        devcount: [{ required: true, message: '设备数量不能为空', trigger: ['blur', 'change'] }],
        batchNumber: [{ required: true, message: '批次号不能为空', trigger: [ 'blur','change'] }],
        batchCount: [{ required: true, message: '数量不能为空', trigger: [ 'blur','change'] }],
        contractId: [{ required: true, message: '关联合同不能为空', trigger: [ 'blur','change'] }],
      }, // 前端校验规则
      isEditMode: false,
      projectList:null,
      modelList:null
    }
  },
  watch: {
  },
  mounted() {
  },
  created() {
    this.subBtn = true
    this.fetchList()
  },
  methods: {
    isZero(){
      if(this.devTypeName === '电子标识器' || this.isstored === '1') {
        return true
      }else{
        return false
      }
    },
    // 获取项目名称
    fetchList() {
      getProjectList().then(response => {
        this.projectList = response.data
      })
      getDeviceList().then(response => {
        this.deviceTypeList = response.data
        console.log(this.deviceTypeList)
      })
      getContractList().then(response => {
        this.contractList = response.data
        console.log(this.contractList)
      })
    },
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.subBtn= true
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.taskForm = {
          taskId: row.taskId,
          devtypeId: row.devTypeName,
          projectId: row.projectId,
          devmodeId: row.devmodeId,
          devcount: row.devcount,
          isstored: row.isstored,
          batches:[]
        }
        this.isstored = row.isstored
        this.devTypeName = row.devTypeName
        this.devTypeId = row.devtypeId
        this.projectName = row.projectName
        getBatchList(row.devtypeId, row.taskId).then(response => {
          console.log(response)
          this.taskForm.batches = response.data
          console.log(this.taskForm.batches)
        })
        getBatchNumber(row.devtypeId).then(response => {
          this.startnumber = Number(response.data)
          console.log(this.startnumber)
        })
        this.isEditMode = true
      }
    },
    addlist(){
      this.listitem = {'batchNumber': this.startnumber.toString(),'batchCount': '','remaincount': '','contractId': ''}
      this.startnumber++
      this.taskForm.batches.push(this.listitem)
    },
    detailContract(id){
      getContractDetail(id).then(response => {
        console.log(response)
        let data = ['合同编号：'+response.data.contractNumber,'合同名称：'+ response.data.contractName,'合同内容：'+response.data.contractContent]
        let newDatas = [];
        const h = this.$createElement;
        for(let i in data){
          newDatas.push(h('p',null,data[i]));
        };
        this.$msgbox({
          title: '合同详情',
          message: h('div',null, newDatas),
          showCancelButton: false,
          confirmButtonText: '确定',
        }).then(action => {
        });
      })
    },
    checkDetail(row){
      if(row.contractId !== ''){
        return false
      }else{
        return true
      }
    },
    deletelist(e){
      var isNew = false
      console.log(e)
      if(!this.taskForm.batches[e].taskId)
      {
        isNew = true
        var num = Number(this.taskForm.batches[e].batchNumber)
        for(var i=e; i<this.taskForm.batches.length;i++) {
          if(Number(this.taskForm.batches[i].batchNumber) > num)
          {
            this.taskForm.batches[i].batchNumber = (Number(this.taskForm.batches[i].batchNumber)-1).toString()
          }
        }
      }
      if(isNew) {
        this.startnumber--
      }
      this.taskForm.batches.splice(e,1)
    },
    indexMethod(index) {
        return this.taskForm.batches[index].batchNumber
    },
    countChange(e,index){
      this.taskForm.batches[index].batchCount = e.target.value
    },

    // 保存数据
    saveData: function() {
      if (this.dialogStatus === 'update') {
        this.updateData()
      }
    },

    // 修改数据
    updateData: function() {
      // this.subBtn= false
      var sum = 0
      for(var i=0; i<this.taskForm.batches.length;i++){
        // this.taskForm.batches[i].id = this.startnumber + i
        sum += Number(this.taskForm.batches[i].batchCount)
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(sum.toString() === this.taskForm.devcount)
          {
            this.subBtn= false
            console.log(this.taskForm)
            var item = this.taskForm.devtypeId
            this.taskForm.devtypeId= this.devTypeId
            if(this.isZero()){
              for(var i=0;i<this.taskForm.batches.length;i++){
                this.taskForm.batches[i].batchNumber = '0'
                this.taskForm.batches[i].remaincount = this.taskForm.batches[i].batchCount
              }
            }else{
              for(var i=0;i<this.taskForm.batches.length;i++){
                this.taskForm.batches[i].remaincount = this.taskForm.batches[i].batchCount
              }
            }
            console.log(this.taskForm.batches)
            updateBatch(this.taskForm,this.taskForm.batches).then(response => {
              if (response.code === 200) {
                this.subBtn= true
                this.taskForm.devtypeId = item
                this.$message.success('修改成功')
                this.$emit('watchChild')
                this.dialogFormVisible = false
                this.$router.push({ path: '/devicelist/' + this.projectName })
              }else if(response.code == 400){
                this.$message.error(response.message)
              }
            })
          }
          else{
            this.subBtn= true
            this.$message({
              message: '各批次累加后与设备数量不符',
              type: 'warning'
            });
          }
        }
      })
    },

    changeModel(event)
    {
      var str = event.productName
      getModelList(str).then(response => {
        this.modelList = response.data
        this.taskForm.devmodeId = this.modelList[0].productModel
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .tableBox{
    div{
      height: 18px !important;
      line-height: 18px !important;
    }
  }
  .el-select{
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
  .labeltext{
    vertical-align: -webkit-baseline-middle;
  }
  $tableTitleHeight:46px;
  .table-title{
    background-color:rgba(243, 243, 243, 1);
    height: $tableTitleHeight;
    .title-header{
      line-height:$tableTitleHeight;
      color: #606266;
      font-size: 15px;
      i{
        margin-left: 5px;
        margin-right: 5px;
      }
    }
  }
  .edit_btn{
    float:right;
    margin:7px 3px;//为了需要居中显示margin-top和bottom要用$tableTitleHeight减去按钮原高度除以2
  }
</style>
