<template>
  <div>

    <div class="tab-header webtop">
      <!-- 标题 -->
      <div>【新增】收货单</div>
      <!-- start 添加修改按钮 -->
      <div>
        <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate">保存</el-button>
        <el-button type="primary" size="small" :disabled="submitdisabled" @click="submintdate">确认</el-button>
        <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
      </div>
      <!-- end 添加修改按钮 -->
      <!-- end 详情按钮 -->
    </div>

    <div class="listconadd">

      <el-form ref="form_obj" :model="formobj" :rules="rules" class="formaddcopy02">
        <!-- <div class="title">
          <div>基础信息</div>
        </div> -->
        <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">供应商</div>
            <el-select v-model="formobj.supplierName" placeholder="请选择" clearable @change="selectSupplierName"
              class="addinputInfo addinputw">
              <el-option v-for="(item,i) in supplierNameList" :key="item.sid" :label="item.supplierName"
                :value="item.sid">
              </el-option>
            </el-select>

            <!-- <el-form-item><span class="addinputInfo">{{ formobj.supplierName }}</span></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-date-picker>
            </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><span class="addinputInfo">{{ formobj.billState }}</span></el-form-item> -->
            <el-form-item prop="isUpShelf">
              <el-radio-group v-model="formobj.isUpShelf" size="small" class="addinputInfo" @change="changeTheme">
                <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 titleOne">
          <div>商品列表</div>
          <!-- <el-button type="primary" size="mini" class="btntopblueline" @click="batchAddAll()">批次收货</el-button> -->
        </div>
        <el-table v-loading="listLoading" :data="formobj.list" border style="width: 100%;">
          <el-table-column fixed width="50" type="selection" align="center" />
          <el-table-column fixed width="60" label="序号" type="index" :index="indexMethod" align="center" />
          <el-table-column fixed label="操作" wid align="center" width="100">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="doGoods(scope.row)">删除</el-button>
              <!-- <el-button type="primary" size="mini" @click="doAddBatch(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="180">
            <template slot-scope="scope">
              <el-select v-model="scope.row.warehouseName" placeholder="请选择" clearable
                @change="selectWarehouseName(scope.row,$event)">
                <el-option v-for="(item,i) in warehouseList" :key="i" :label="item.warehouseName" :value="item.sid">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="库位" align="center" width="180">
            <template slot-scope="scope">
              <el-select v-model="scope.row.warehouseRackName" :disabled="scope.row.warehouseName==''" clearable
                @focus="getWarehouseAreaList(scope.row.warehouseSid)" placeholder="请选择"
                @change="selectWarehouseAreaCode">
                <el-option v-for="(item,i) in warehouseRackList" :key="i" :label="item.areaCode" :value="item.sid">
                </el-option>
              </el-select>
            </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 ref="focusAssumptionInput" @input="commodityComputeYHAndXSJE(scope.row,$event)"
                v-model="scope.row.actualInCount" clearable placeholder=""
                oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" />
            </template>
          </el-table-column>
          <el-table-column label="拒收数量" align="center" width="120">
            <template slot-scope="scope">
              <el-input ref="focusAssumptionInput" v-model="scope.row.rejectCount" clearable placeholder=""
                @input="commodityComputeYHAndXSJE2(scope.row,$event)"
                oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" />
            </template>
          </el-table-column>
          <el-table-column label="拒收原因" align="center" width="180">
            <template slot-scope="scope">
              <el-input ref="focusAssumptionInput" 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" @change="changeTheme">
                <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" @change="changeTheme2">
                <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 ref="focusAssumptionInput" v-model="scope.row.packageRemark" clearable placeholder="" />
            </template>
          </el-table-column>
          <el-table-column label="入库单价" prop="cost" align="center" width="100" />
          <el-table-column label="税率" prop="taxAmount" align="center" width="100" />
          <!-- <el-table-column label="含税单价" prop="taxPrice" align="center" width="100" /> -->
          <el-table-column label="入库金额" prop="amount" align="center" width="100" />
        </el-table>


        <!--  <div class="title">
          <div>商品-批次</div>
        </div>
        <el-table v-loading="listLoading" :data="formobj.pcList" border style="width: 100%;">
          <el-table-column fixed width="60" label="序号" type="index" :index="indexMethod" align="center" />
          <el-table-column fixed label="操作" wid align="center" width="120">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="doGoodsBatch(scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column label="商品列表序号" prop="xh" align="center" width="120" />
          <el-table-column label="商品名称" prop="goodsSkuTitle" 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="仓库" prop="unit" align="center" width="150" />
          <el-table-column label="库位" prop="unit" align="center" width="150" />
          <el-table-column label="批次号" prop="batchNumber" align="center" width="300" />
          <el-table-column label="生产日期" align="center" width="180">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.manufactureDate" type="date" value-format="yyyy-MM-dd"
                placeholder="选择日期" @change="manufactureDateChange(scope.row,$event)" />
            </template>
          </el-table-column>
          <el-table-column label="有效期" prop="expirationDate" align="center" width="180" />
          <el-table-column label="数量" align="center" width="120">
            <template slot-scope="scope">
              <el-input ref="focusAssumptionInput" v-model="scope.row.batchCount" clearable placeholder=""
                oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" />
            </template>
          </el-table-column>
        </el-table> -->

      </el-form>

    </div>
  </div>
</template>

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

  export default {
    components: {},
    data() {
      return {
        listLoading: false,
        activeNames: ['1'],
        submitdisabled: false,
        formobj: {
          sourceBillNo: "",
          busTypeKey: "",
          busTypeValue: "",
          createTime: '',
          createByName: window.sessionStorage.getItem('name'),
          deptName: '',
          deptSid: '',
          createBySid: window.sessionStorage.getItem('userSid'),
          useOrgSid: '',
          createOrgSid: '',
          billState: '新建',
          billStateKey: 0,
          reviewStatus: "",
          refuseReason: "",
          contact: "",
          mobile: "",
          supplierSid: "",
          supplierName: "",
          goodsOwnerSid: "",
          goodsOwner: "",
          deliveryDate: getCurrentDate(),
          list: [],
          pcList: []
        },
        hideUploadBtn: false,
        warehouseList: [],
        warehouseRackList: [],
        supplierNameList: [],
        rules: {
          deliveryDate: [{
            required: true,
            message: '到货日期不能为空',
            trigger: 'change'
          }],
          isUpShelf: [{
            required: true,
            message: '请选择是或否',
            trigger: 'change'
          }],
        }
      }
    },
    created() {

    },
    methods: {

      init() {
        getOrgSidByPath({
          orgPath: window.sessionStorage.getItem('defaultOrgPath')
        }).then((res) => {
          if (res.success) {
            this.formobj.createOrgSid = res.data
            this.formobj.useOrgSid = res.data
          }
        })
      },

      // getOrgPathSid() {
      //   getOrgSidByPath({
      //     orgPath: window.sessionStorage.getItem('defaultOrgPath')
      //   }).then((res) => {
      //     if (res.success) {
      //       this.formobj.createOrgSid = res.data
      //       this.formobj.useOrgSid = res.data
      //     }
      //   })
      // },
      selectSupplierName(val) {

        console.log("supplierNameSelect", val);
        const choose = this.supplierNameList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>supplierNameSelect', choose)
        this.formobj.supplierName = choose[0].supplierName
        this.formobj.supplierSid = choose[0].sid

      },
      getsupplierLust() {

        // getOrgSidByPath({
        //   orgPath: window.sessionStorage.getItem('defaultOrgPath')
        // }).then((res) => {
        //   if (res.success) {
        //     this.formobj.createOrgSid = res.data
        //     this.formobj.useOrgSid = res.data
        //     req.choiceSupplierInfo(res.data).then((resp) => {
        //       if (resp.success) {
        //         this.supplierNameList = resp.data
        //         console.log("aaaaaa", this.supplierNameList);
        //       }
        //     })

        //   }
        // })


        choiceSupplierInfo({
          deptSid: window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage
            .getItem('defaultOrgPath').lastIndexOf('/') + 1)
        }).then((resp) => {
          if (resp.success) {
            this.supplierNameList = resp.data
            console.log("aaaaaa", this.supplierNameList);
          }
        })


      },
      getWarehouseList() {
        var parpams = {
          orgPath: window.sessionStorage.getItem('defaultOrgPath'),
        }
        req2.getWarehouses(parpams).then((res) => {
          if (res.success) {
            this.warehouseList = res.data

            console.log("aaaaaa", this.warehouseList);

          }
        })
      },
      getWarehouseAreaList(sid) {
        var query = {
          ckSid: sid
        }
        req2.getWarehouseareas(query).then((res) => {
          if (res.success) {
            this.warehouseRackList = res.data

            console.log("aaaaaa", this.warehouseRackList);

          }
        })
      },
      selectWarehouseName(row, val) {
        console.log("selectWarehouseName", row);
        console.log("selectWarehouseName", val);
        const choose = this.warehouseList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>selectWarehouseName', choose)
        row.warehouseName = choose[0].warehouseName
        row.warehouseSid = choose[0].sid

      },
      selectWarehouseAreaCode(val) {
        console.log("selectWarehouseAreaCode", val);

        const choose = this.warehouseRackList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>selectWarehouseAreaCode', choose)
        row.warehouseRackName = choose[0].areaCode
        row.warehouseRackSid = choose[0].sid

      },

      batchAddAll() {

        for (var i = 0; i < this.formobj.list.length; i++) {
          var item = this.formobj.list[i]

          var info = {
            xh: i + 1,
            goodsSkuSid: item.goodsSkuSid,
            goodsSkuTitle: item.goodsSkuTitle,
            goodsSkuCode: item.goodsSkuCode,
            goodsSkuOwnSpec: item.goodsSkuOwnSpec,
            unit: item.unit,
            warehouseSid: item.warehouseSid,
            warehouseName: item.warehouseName,
            warehouseRackSid: item.warehouseRackSid,
            warehouseRackName: item.warehouseRackName,
            shelfLife: item.shelfLife,
            orderCount: item.orderCount,
            batchNumber: '',
            manufactureDate: '',
            batchCount: 0,
          }

          this.formobj.pcList.push(info)

        }

      },
      doGoods(row) {
        console.log("doGoodsDel》》》》", row)

        this.$confirm("是否确定删除此商品？", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const index = this.formobj.list.findIndex((item) => item === row)
          console.log("index》》》》", index)
          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);
            }
          }

        })
      },

      doGoodsBatch(row) {
        console.log("doGoodsDel》》》》", row)

        this.$confirm("是否确定删除此商品？", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const index = this.formobj.pcList.findIndex((item) => item === row)
          console.log("index》》》》", index)
          this.formobj.pcList.splice(index, 1)

        })

      },

      manufactureDateChange(row, val) {

        console.log("manufactureDateChange》》》》", val)

        row.manufactureDate = val
        row.expirationDate = this.addDate(val, row.shelfLife)

        let reg = new RegExp('-', 'g') //g代表全部

        row.batchNumber = this.formobj.deliveryDate.replace(reg, '') + " - " + row.expirationDate.replace(reg, '')



        this.$forceUpdate(); // 强制更新
        console.log("manufactureDateChange》》》》", row)

      },

      addDate(date, days) {
        var dates = new Date(date)
        dates.setDate(dates.getDate() + days)
        var year = dates.getFullYear()
        var month = dates.getMonth() + 1
        var day = dates.getDate()
        if (month < 9) {
          month = "0" + month
        }
        if (day < 9) {
          day = "0" + day
        }
        var time = year + '-' + month + '-' + day
        return time
      },

      doAddBatch(row) {
        const index = (this.formobj.list.findIndex((item) => item === row)) + 1
        console.log("doAddBatch》》》》", index)
        console.log("doAddBatch》》》》", row)

        var info = {
          xh: index,
          goodsSkuSid: row.goodsSkuSid,
          goodsSkuTitle: row.goodsSkuTitle,
          goodsSkuCode: row.goodsSkuCode,
          goodsSkuOwnSpec: row.goodsSkuOwnSpec,
          unit: row.unit,
          warehouseSid: row.warehouseSid,
          warehouseName: row.warehouseName,
          warehouseRackSid: row.warehouseRackSid,
          warehouseRackName: row.warehouseRackName,
          shelfLife: row.shelfLife,
          orderCount: row.orderCount,
          batchNumber: '',
          manufactureDate: '',
          batchCount: 0,
        }

        console.log("aaaaaaaaaaa", info);

        this.formobj.pcList.push(info)

      },
      commodityComputeYHAndXSJE(row, val) {
        console.log("aaa", row);
        console.log("aaa", val);

        // if (Number(row.actualInCount) > Number(row.orderCount)) {
        row.actualInCount = val
        // }

        row.amount = (Number(row.actualInCount) * Number(row.cost)).toFixed(2)


      },

      commodityComputeYHAndXSJE2(row, val) {
        console.log("aaa", row);
        console.log("aaa", val);
        row.rejectCount = val
        // if ((Number(row.rejectCount) + Number(row.actualInCount)) > Number(row.orderCount)) {
        //   row.rejectCount = Number(row.orderCount) - Number(row.actualInCount)
        // }

      },

      changeTheme() {

      },

      changeTheme2() {

      },


      indexMethod(index) {
        return index + 1
      },
      saveOrUpdate() {
        console.log('>>>>>>>>>saveOrUpdate', this.formobj)

        // if (this.formobj.deliveryDate == '') {
        //   this.$message({
        //     showClose: true,
        //     type: 'error',
        //     message: '到货日期不能为空'
        //   })

        //   return
        // }



        this.$refs['form_obj'].validate((valid) => {
          if (valid) {


            for (var i = 0; i < this.formobj.list.length; i++) {

              if (Number(this.formobj.list[i].actualInCount) == 0) {
                this.$message({
                  showClose: true,
                  type: 'error',
                  message: '商品实收数量不能为空'
                })

                return
              }

            }

            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
            })
          }
        })
      },
      submintdate() {
        console.log('>>>>>>>>>saveOrUpdate', this.formobj)


        // if (this.formobj.deliveryDate == '') {
        //   this.$message({
        //     showClose: true,
        //     type: 'error',
        //     message: '到货日期不能为空'
        //   })

        //   return
        // }

        for (var i = 0; i < this.formobj.list.length; i++) {

          if (Number(this.formobj.list[i].actualInCount) == 0) {
            this.$message({
              showClose: true,
              type: 'error',
              message: '商品实收数量不能为空'
            })

            return
          }

        }


        this.$refs['form_obj'].validate((valid) => {
          if (valid) {
            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.submitdisabled = false
        this.formobj = {
          sourceBillNo: "",
          busTypeKey: "",
          busTypeValue: "",
          createByName: "",
          billState: 0,
          reviewStatus: "",
          refuseReason: "",
          contact: "",
          mobile: "",
          supplierSid: "",
          supplierName: "",
          goodsOwnerSid: "",
          goodsOwner: "",
          deliveryDate: "",
          list: [],
          pcList: []
        }
        this.$emit('doback')
      },

      showAdd() {
        this.$nextTick(() => {
          this.$refs['form_obj'].clearValidate()
        })
        this.init()

      },
      showEdit(row) {
        this.$nextTick(() => {
          this.$refs['form_obj'].clearValidate()
        })
        this.init()
        // this.getWarehouseList()
        this.getsupplierLust()
        // this.getOrgPathSid()
        var params = {
          sourceSid: row.sid
        }

        req.getInitDetails(row.sid)
          .then(resp => {
            if (resp.success) {
              this.formobj = resp.data
              this.formobj.deliveryDate = getCurrentDate()

              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 = {}
          })
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-form-item__error {
    margin-left: 120px !important;
  }

  .must {
    color: #f00;
  }

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

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

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

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

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

  /deep/ .el-form-item__error {
    margin-left: 180px !important;
  }

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