<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <div class="tab-header webtop">
        <div>{{ viewTitle }}</div>
        <div>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate()">保存</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="settle()">调拨</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">
          <div style="display: flex;flex-direction: row;align-items: center;padding: 10px;">

            <div>
              <span>调出门店：</span>
              <el-select v-model="commodityQuery.params.inOrg" placeholder="请选择" @change="selectOutOrg">
                <el-option v-for="(item,i) in orgList" :key="i" :label="item.name" :value="item.sid">
                </el-option>
              </el-select>
            </div>
            <div style="margin-left: 30px;">
              <span>调入门店：</span>
              <el-select v-model="commodityQuery.params.outOrg" placeholder="请选择" @change="selectInOrg">
                <el-option v-for="(item,i) in orgList" :key="i" :label="item.name" :value="item.sid">
                </el-option>
              </el-select>
            </div>

          </div>

          <div
            style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;padding: 10px;">
            <div>商品列表</div>
            <div v-if="formobj.billNo!=''">单号：{{formobj.billNo}}</div>
          </div>


          <el-table :key="commodityKey" :data="formobj.wmsInventoryAllocateBillDetailNewList" :index="index" border
            style="width: 100%;">
            <el-table-column fixed width="60" label="序号" type="index" :index="index + 1" align="center" />
            <el-table-column align="center" width="70" :render-header="commodityHeader">
              <template slot-scope="scope">
                <i class="el-icon-delete" @click="commodityDelete(scope.$index)"></i>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" align="center" min-width="200">
              <template slot-scope="scope">
                <el-popover placement="right" width="900" trigger="click">
                  <div>
                    <el-table :data="commodityData" v-loading="commodityLoading" highlight-current-row
                      @current-change="commodityCurrentChange($event, scope.row)">
                      <el-table-column fixed prop="goodsSpuName" label="商品名称" align="center" />
                      <el-table-column prop="goodsSkuCode" label="商品编码" align="center" />
                      <el-table-column prop="goodsSkuOwnSpec" label="型号" align="center" />
                      <el-table-column prop="unit" label="单位" align="center" />
                      <el-table-column prop="warehouseName" label="仓库" align="center" />
                      <el-table-column prop="warehouseRackCode" label="库位" align="center" />
                      <el-table-column prop="count" label="库存数量" align="center" />
                    </el-table>
                    <el-pagination :page.sync="commodityQuery.current" :page-size="commodityQuery.size"
                      layout="total, pager" :total="commodityQuery.total" />
                  </div>
                  <el-input slot="reference" v-model="scope.row.goodsSpuName"
                    @input="commodityInput(scope.row.goodsSpuName)" clearable placeholder="商品名称" />
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="goodsSkuCode" label="商品编码" align="center" />
            <el-table-column prop="goodsSkuOwnSpec" label="型号" align="center" />
            <el-table-column prop="unit" label="单位" align="center" />
            <el-table-column prop="warehouseName" label="仓库" align="center" />
            <el-table-column prop="warehouseArea" label="库位" align="center" />
            <el-table-column prop="stockCount" label="库存数量" align="center" />
            <el-table-column label="调入仓库" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.inWarehouseName" placeholder="请选择" @change="selectWarehouseName">
                  <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">
              <template slot-scope="scope">
                <el-select v-model="scope.row.inWarehouseRackCode" 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="调拨数量" align="center">
              <template slot-scope="scope">
                <el-input @input="commodityComputeYHAndXSJE(scope.row,$event)" v-model="scope.row.count" clearable
                  placeholder="" oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="调拨金额" align="center" width="100" />
          </el-table>
          <el-row>
            <el-col :span="24">
              <el-form-item><span>调拨数量：{{ totalQuantity }} , 调拨金额：{{ materialCost }}</span></el-form-item>
            </el-col>
            <el-col :span="1">
              <el-form-item><span>备注</span></el-form-item>
            </el-col>
            <el-col :span="23">
              <el-form-item><el-input v-model="formobj.remarks" clearable placeholder="请填写备注..." /></el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
  import req from '@/api/storage/allocation.js'
  export default {
    data() {
      return {
        viewTitle: '',
        viewState: 1,
        submitdisabled: false,
        settleVisible: false, //
        activeNames: '1',
        index: 0,

        // commodity商品
        commodityKey: 1,
        commodityLoading: false,
        commodityQuery: {
          current: 1,
          size: 2,
          total: 0,
          params: {
            name: '',
            inOrg: "",
            outOrg: ""
          }
        },
        commodityData: [],
        formobj: {
          "sid": "",
          "billNo": "",
          "createBySid": window.sessionStorage.getItem('userSid'),
          "createDate": "",
          "createUserSid":window.sessionStorage.getItem('userSid'),
          "outOrgSid": "",
          "inOrgSid": "",
          "count": "",
          "amount": "",
          "confirmSid": "",
          "confirmName": "",
          "finishTime": "",
          "useOrgSid": window.sessionStorage.getItem('orgSid'),
          "createOrgName": window.sessionStorage.getItem('Orgname'),
          "wmsInventoryAllocateBillDetailNewList": []
        },
        rules: {},
        orgList: [{
            name: "撒记得",
            sid: "123"
          },
          {
            name: "阿萨德",
            sid: "12323"
          },
          {
            name: "我饿请问请问",
            sid: "23423"
          },
          {
            name: "特尔味道",
            sid: "1234"
          },
          {
            name: "提问额外撒大声地",
            sid: "12324233"
          }
        ],
        warehouseList: [],
        warehouseRackList: []
      }
    },
    computed: {
      // 调拨数量
      totalQuantity() {
        let quantity = 0
        if (this.formobj.wmsInventoryAllocateBillDetailNewList.length > 0) {
          this.formobj.wmsInventoryAllocateBillDetailNewList.forEach((e) => {
            quantity += Number(e.count)
          })
        }

        this.formobj.count = quantity

        return quantity
      },
      // 调拨金额
      materialCost() {
        let material = 0
        if (this.formobj.wmsInventoryAllocateBillDetailNewList.length > 0) {
          this.formobj.wmsInventoryAllocateBillDetailNewList.forEach((e) => {
            material += Number((Number(e.count) * Number(e.taxPrice)))
          })
        }

        this.formobj.amount = material.toFixed(2)

        return material.toFixed(2)
      },

    },
    methods: {
      selectInOrg(val) {
        console.log("selectInOrg", val);

        const choose = this.orgList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>selectInOrg', choose)
        this.formobj.inOrgSid = choose[0].sid
        this.formobj.inOrgName = choose[0].name
      },

      selectOutOrg(val) {
        console.log("selectOutOrg", val);
        this.formobj.inOrgSid = val

        const choose = this.orgList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>selectOutOrg', choose)
        this.formobj.outOrgSid = choose[0].sid
        this.formobj.outOrgName = choose[0].name

      },

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

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

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

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

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

        this.getWarehouseAreaList(val)
      },
      selectWarehouseAreaCode(val) {
        console.log("selectWarehouseAreaCode", val);
      },
      showAdd() {
        this.viewTitle = '【新增】调拨记录'
        this.$nextTick(() => {
          this.$refs['form_obj'].clearValidate()
        })
        this.getWarehouseList()
      },
      showEdit(row) {
        this.viewTitle = '【修改】调拨记录'
        this.$nextTick(() => {
          this.$refs['form_obj'].clearValidate()
        })
        req.init(row.sid).then((res) => {
          if (res.success) {
            this.formobj = res.data

            this.commodityQuery.params.inOrg =  this.formobj.inOrgName
            this.commodityQuery.params.outOrg =  this.formobj.outOrgName
          }
        })
        this.getWarehouseList()
      },
      // 在头部标题上添加“新增”图标
      commodityHeader(h, {
        column
      }) {
        return h(
          'div',
          [
            h('span', column.label),
            h('i', {
              class: 'add-btn-icon el-icon-plus',
              style: 'color: red;font-size:20px',
              on: {
                click: this.commodityAdd // 点击执行函数
              }
            })
          ]
        )
      },
      commodityAdd() {
        this.formobj.wmsInventoryAllocateBillDetailNewList.push({
          "sid": "",
          "billSid": "",
          "inventorySid": "",
          "goodsSpuName": "",
          "goodsSkuCode": "",
          "goodsSkuOwnSpec": "",
          "carModel": "",
          "unit": "",
          "warehouseSid": "",
          "warehouseName": "",
          "warehouseAreasid": "",
          "warehouseArea": "",
          "taxPrice": "",
          "stockCount": "",
          "inWarehouseSid": "",
          "inWarehouseName": "",
          "inWarehouseRackSid": "",
          "inWarehouseRackCode": "",
          "count": "",
          "amount": ""
        })
      },
      commodityInput(value) {
        this.commodityQuery.params.name = value
        this.commodityLoading = true
        req.getGoods(this.commodityQuery).then((response) => {
          if (response.success) {
            this.commodityLoading = false
            this.commodityData = response.data.records
            this.commodityQuery.total = response.data.total
          } else {
            this.serviceLoading = false
            this.commodityData = []
            this.commodityQuery.total = 0
          }
        })
      },
      commodityDelete(index) {
        this.formobj.wmsInventoryAllocateBillDetailNewList.splice(index, 1)
      },
      commodityCurrentChange(value, row) {
        row.inventorySid = value.sid
        row.goodsSpuName = value.goodsSpuName
        row.goodsSkuCode = value.goodsSkuCode
        row.goodsSkuOwnSpec = value.goodsSkuOwnSpec
        row.unit = value.unit
        row.warehouseName = value.warehouseName
        row.warehouseSid = value.warehouseSid
        row.warehouseArea = value.warehouseRackCode
        row.warehouseAreasid = value.warehouseRackSid
        row.taxPrice = value.taxPrice
        row.stockCount = value.count
        row.count = ''
        row.amount = ''
        document.body.click()
      },
      // 计算优惠、销售金额
      commodityComputeYHAndXSJE(row, val) {

        console.log("aaaaaaaaa", row);
        console.log("aaaaaaaaa", val);
        Number()
        if (Number(row.stockCount) < Number(row.count)) {
          row.count = ''
          row.amount = ''
        } else {

          row.amount = (Number(row.count) * Number(row.taxPrice)).toFixed(2)

        }

      },
      saveOrUpdate() {
        this.$refs['form_obj'].validate((valid) => {
          if (valid) {
            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
            })
          }
        })
      },
      settle() {
        this.settleVisible = true
        this.formobj.settlementVo.receivableAmount = this.amountReceivable
      },
      confirm() {
        this.$refs['form_obj'].validate((valid) => {
          if (valid) {
            this.submitdisabled = true
            req.settlement(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": "",
          "createBySid": "",
          "createDate": "",
          "createUserSid": "",
          "outOrgSid": "",
          "inOrgSid": "",
          "count": "",
          "amount": "",
          "confirmSid": "",
          "confirmName": "",
          "finishTime": "",
          "useOrgSid": "",
          "createOrgName": "",
          "wmsInventoryAllocateBillDetailNewList": []
        }
        this.commodityQuery.params.inOrg = ''
        this.commodityQuery.params.outOrg = ''
        this.submitdisabled = false
        this.settleVisible = false
        this.$emit('doback')
      }
    }
  }
</script>

<style scoped>
  .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);
  }
</style>
