<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <div class="tab-header webtop">
        <div>{{ title }}收货单</div>
        <div>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate">保存</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="submit">确认</el-button>
          <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
        </div>
      </div>
      <div class="listconadd">
        <el-form ref="form_obj" :model="formobj" :rules="rules" class="formaddcopy02">
          <el-row class="first_row">
            <el-col :span="8">
              <div class="span-sty">制单人</div>
              <el-form-item><span class="addinputInfo">{{ formobj.createByName }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">制单部门</div>
              <el-form-item><span class="addinputInfo">{{ formobj.deptName }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">单据日期</div>
              <el-form-item><span class="addinputInfo">{{ formobj.createTime }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty">预期到货通知单号</div>
              <el-form-item><span class="addinputInfo">{{ formobj.sourceBillNo }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">业务类型</div>
              <el-form-item><span class="addinputInfo">{{ formobj.busTypeValue }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="must">*</span>供应商</div>
              <el-form-item prop="supplierName">
                <el-select v-model="formobj.supplierName" filterable clearable placeholder="请选择" class="addinputInfo" @change="supplierNameSelect">
                  <el-option v-for="item in supplierList" :key="item.sid" :label="item.supplierName" :value="item.sid">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty"><span class="must">*</span>到货日期</div>
              <el-form-item prop="deliveryDate">
                <el-date-picker v-model="formobj.deliveryDate" type="date" class="addinputInfo" value-format="yyyy-MM-dd" placeholder="选择日期" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">单据状态</div>
              <el-form-item><span class="addinputInfo">{{ formobj.billState }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="must">*</span> 收货人是否与上架人一致</div>
              <el-form-item prop="isUpShelf">
                <el-radio-group v-model="formobj.isUpShelf" size="small" class="addinputInfo">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="2">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">备注</div>
              <el-form-item>
                <el-input v-model="formobj.remarks" placeholder="" class="addinputw addinputInfo" type="textarea" :rows="4" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <div class="title">商品列表</div>
          <el-table v-loading="listLoading" :data="formobj.list" border style="width: 100%;" ref="dataTable">
            <el-table-column fixed width="60" label="序号" type="index" :index="indexMethod" align="center"/>
            <el-table-column label="操作" align="center" width="120">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="doGoods(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="goodsSpuName" align="center" width="200" />
            <el-table-column label="商品编码" prop="goodsSkuCode" align="center" width="150" />
            <el-table-column label="规格" prop="goodsSkuOwnSpec" align="center" width="150" />
            <el-table-column label="单位" prop="unit" align="center" width="120"/>
            <el-table-column label="入库单价" align="center" width="150">
              <template slot-scope="scope">
                <el-input @input="commodityComputeYHAndXSJE(scope.row)" @keyup.native="scope.row.cost = getNumber(scope.row.cost, 2)" v-model="scope.row.cost" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column label="预期到货数量" prop="orderCount" align="center" width="120" />
            <el-table-column label="实收数量" align="center" width="120">
              <template slot-scope="scope">
                <el-input @input="commodityComputeYHAndXSJE(scope.row)" @keyup.native="scope.row.actualInCount = getNumber(scope.row.actualInCount, 0)" v-model="scope.row.actualInCount" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column label="拒收数量" align="center" width="120">
              <template slot-scope="scope">
                <el-input @keyup.native="scope.row.rejectCount = getNumber(scope.row.rejectCount, 0)" v-model="scope.row.rejectCount" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column label="拒收原因" align="center" width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.rejectReason" clearable placeholder=""/>
              </template>
            </el-table-column>
            <el-table-column label="是否质检" align="center" width="180">
              <template slot-scope="scope">
                <el-radio-group v-model="scope.row.isQuality" size="small">
                  <el-radio :label="0">是</el-radio>
                  <el-radio :label="1">否</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column label="质检状态" align="center" width="180">
              <template slot-scope="scope">
                <el-radio-group v-model="scope.row.qualityState" size="small">
                  <el-radio :label="0">合格</el-radio>
                  <el-radio :label="1">不合格</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column label="载具说明" align="center" width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.packageRemark" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column label="税率" align="center" width="150">
              <template slot-scope="scope">
                <el-input @keyup.native="scope.row.taxAmount = getNumber(scope.row.taxAmount, 2)" v-model="scope.row.taxAmount" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column label="入库金额" prop="amount" align="center" width="150"/>
          </el-table>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import req from '@/api/storage/receivingGoods.js'
import deliveryNotice from '@/api/storage/deliveryNotice'
import { getCurrentDate } from '@/utils/index.js'
import { choiceSupplierInfo, getOrgSidByPath } from '@/api/Common/dictcommons'

export default {
  data() {
    return {
      viewState: 1,
      title: '',
      listLoading: false,
      submitdisabled: false,
      formobj: {
        sid: '',
        billNo: '',
        sourceBillSid: '',
        sourceBillNo: '',
        createBySid: '',
        createByName: '',
        deptName: '',
        deptSid: '',
        createTime: getCurrentDate(),
        busTypeKey: '',
        busTypeValue: '',
        supplierSid: '',
        supplierName: '',
        deliveryDate: getCurrentDate(),
        billState: '新建',
        remarks: '',
        isUpShelf: '',
        useOrgSid: '',
        createOrgSid: '',
        list: [],
        pcList: []
      },
      supplierList: [],
      commodityData: [],
      rules: {
        supplierName: [{ required: true, message: '请选择供应商', trigger: 'change' }],
        deliveryDate: [{ required: true, message: '到货日期不能为空', trigger: 'change' }],
        isUpShelf: [{ required: true, message: '请选择是或否', trigger: 'change' }]
      }
    }
  },
  methods: {
    getNumber(val, limit) {
      val = val.replace(/[^0-9.]/g, '') // 保留数字
      val = val.replace(/^00/, '0.') // 开头不能有两个0
      val = val.replace(/^\./g, '0.') // 开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') // 两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); // 只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' // 两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    },
    init() {
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.formobj.createOrgSid = res.data
          this.formobj.useOrgSid = res.data
        }
      })
      choiceSupplierInfo({ deptSid: window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1) }).then((resp) => {
        if (resp.success) {
          this.supplierList = resp.data
        }
      })
    },
    indexMethod(index) {
      return index + 1
    },
    saveOrUpdate() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          if (this.formobj.list.length === 0) {
            this.$message({ showClose: true, type: 'error', message: '商品列表不能为空' })
            return
          }
          for (var i = 0; i < this.formobj.list.length; i++) {
            if (this.formobj.list[i].actualInCount === '' ) {
              this.$message({ showClose: true, type: 'error', message: '实收数量不能为空' })
              return
            } else if (parseFloat(this.formobj.list[i].actualInCount) < 1) {
              this.$message({ showClose: true, type: 'error', message: '实收数量不能为零' })
            }
          }
          this.submitdisabled = true
          req.save(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '保存成功' })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    submit() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          if (this.formobj.list.length === 0) {
            this.$message({ showClose: true, type: 'error', message: '商品列表不能为空' })
            return
          }
          for (var i = 0; i < this.formobj.list.length; i++) {
            if (this.formobj.list[i].actualInCount === '' ) {
              this.$message({ showClose: true, type: 'error', message: '实收数量不能为空' })
              return
            } else if (parseFloat(this.formobj.list[i].actualInCount) < 1) {
              this.$message({ showClose: true, type: 'error', message: '实收数量不能为零' })
            }
          }
          this.submitdisabled = true
          req.submit(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '保存成功' })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {
        sid: '',
        billNo: '',
        sourceBillSid: '',
        sourceBillNo: '',
        createBySid: '',
        createByName: '',
        deptName: '',
        deptSid: '',
        createTime: getCurrentDate(),
        busTypeKey: '',
        busTypeValue: '',
        supplierSid: '',
        supplierName: '',
        deliveryDate: getCurrentDate(),
        billState: '新建',
        remarks: '',
        isUpShelf: '',
        useOrgSid: '',
        createOrgSid: '',
        list: [],
        pcList: []
      }
      this.submitdisabled = false
      this.$emit('doback')
    },
    showAdd(row) {
      this.title = '【新增】'
      this.init()
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      deliveryNotice.getInitDetails(row.sid).then(resp => {
        if (resp.success) {
          this.formobj = resp.data
          this.formobj.createByName = window.sessionStorage.getItem('name')
          this.formobj.createBySid = window.sessionStorage.getItem('userSid')
          this.formobj.deptName = window.sessionStorage.getItem('defaultOrgPathName').substring(window.sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1)
          this.formobj.deptSid = window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1)
        }
      }).catch(e => {
        this.formobj = {}
      })
    },
    showEdit(row) {
      this.title = '【修改】'
      this.init()
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      req.init(row.sid).then(resp => {
        if (resp.success) {
          this.formobj = resp.data
          this.formobj.createByName = window.sessionStorage.getItem('name')
          this.formobj.createBySid = window.sessionStorage.getItem('userSid')
          this.formobj.deptName = window.sessionStorage.getItem('defaultOrgPathName').substring(window.sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1)
          this.formobj.deptSid = window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1)
        }
      }).catch(e => {
        this.formobj = {}
      })
    },
    supplierNameSelect(val) {
      const choose = this.supplierList.filter((item) => item.sid === val)
      this.formobj.supplierName = choose[0].supplierName
      this.formobj.supplierSid = choose[0].sid
    },
    doGoods(row) {
      this.$confirm('是否确定删除此商品？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.formobj.list.findIndex((item) => item === row)
        this.formobj.list.splice(index, 1)
        for (var i = this.formobj.pcList.length - 1; i >= 0; i--) {
          if (this.formobj.pcList[i].xh === (index + 1)) {
            this.formobj.pcList.splice(i, 1)
          }
        }
      })
    },
    commodityComputeYHAndXSJE(row) {
      row.amount = Math.round((parseFloat(row.actualInCount !== '' ? row.actualInCount : 0) * parseFloat(row.cost !== '' ? row.cost : 0)) * 100) / 100
    }
  }
}
</script>
<style scoped>
/deep/ .el-form-item__error {
  margin-left: 120px !important;
}

.must {
  color: #f00;
}

.span-sty {
  width: 130px !important;
}

.addinputInfo {
  margin-left: 120px !important;
}

.formaddcopy02 .el-row .el-col /deep/ .el-form-item .addinputw {
  margin-left: 120px !important;
  width: calc(100% - 115px);
}

.first_row {
  border-top: 1px solid #E0E3EB;
}

.titleOne {
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.formaddcopy02 .el-row .el-col /deep/ .el-form-item .el-radio-group {
  display: inline;
  line-height: 1px;
  vertical-align: middle;
}
</style>
