<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="confirm()">提交</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> -->

          <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>
              <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.outPlatName }}</span></el-form-item>
            </el-col>
            <!-- <el-col :span="5">
              <div class="span-sty2"><span class="must">*</span> 调入分公司</div>
              <el-form-item prop="inOrgName"> <el-select v-model="formobj.inOrgName" placeholder="请选择分公司"
                  @change="selectInOrg" class="addinputInfo2 addinputw2">
                  <el-option v-for="(item,i) in orgList" :key="i" :label="item.name" :value="item.sid">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="8">
              <div class="span-sty"><span class="must">*</span> 调入站点</div>
              <el-form-item prop="inPlatName">
                <el-select v-model="formobj.inPlatName" placeholder="请选择调入站" @change="selectInDeptName"
                  class="addinputInfo addinputw">
                  <el-option v-for="(item,i) in deptList" :key="i" :label="item.name" :value="item.sid">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="must">*</span> 经办人</div>
              <el-form-item prop="confirmName"> <el-select v-model="formobj.confirmName" placeholder="请选择经办人" clearable
                  @change="selectOperatorName" class="addinputInfo addinputw">
                  <el-option v-for="(item,i) in operatorNameList" :key="i" :label="item.name" :value="item.sid">
                  </el-option>
                </el-select>
              </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="seleGoods()">添加</el-button>
          </div>

          <el-table :data="formobj.wmsInventoryAllocateBillDetailNewList" :index="index" border style="width: 100%;"
            show-summary :summary-method="getSummaries">
            <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>
                    <pagination v-show="commodityData.length > 0" :total="commodityQuery.total"
                      :limit.sync="commodityQuery.size" class="pagination"
                      @pagination="commodityInput(scope.row.goodsSpuName)" />
                  </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 fixed label="操作" wid align="center" width="100">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="deleteGoods(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="goodsID" label="商品ID" width="100" align="center" />
            <el-table-column prop="goodsSpuName" label="商品名称" width="100" align="center" />
            <el-table-column prop="goodsSkuCode" label="商品编码" width="100" align="center" />
            <el-table-column prop="goodsSkuOwnSpec" label="规格" align="center" />
            <el-table-column prop="unit" label="单位" align="center" />
            <el-table-column prop="warehouseName" label="仓库" width="150" align="center"/>
            <el-table-column prop="warehouseZoneName" label="区域" width="150" align="center"/>
            <el-table-column prop="warehouseArea" label="库区" width="150" align="center"/>
            <el-table-column prop="warehouseRackCode" label="库位" align="center"/>
            <el-table-column prop="stockCount" label="库存数量" width="100" align="center" />
            <!-- <el-table-column prop="taxPrice" label="单价" width="100" align="center" /> -->
            <el-table-column prop="markUpRatio" label="加价比例(%)" width="120" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.markUpRatio" clearable placeholder=""
                  oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                  @input="commodityComputeYHAndXSJE(scope.row)" />
              </template>
            </el-table-column>
            <!-- <el-table-column label="调入仓库" align="center" width="200">
              <template slot-scope="scope">
                <el-select v-model="scope.row.inWarehouseName" placeholder="请选择"
                  @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="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.inWarehouseRackCode" placeholder="请选择"
                  @change="selectWarehouseAreaCode(scope.row,$event)">
                  <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 prop="requAmount" label="调拨单价" align="center" width="100" />
            <el-table-column prop="count" label="调拨数量" width="120" align="center">
              <template slot-scope="scope">
                <el-input @input="commodityComputeYHAndXSJE2(scope.row)" 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-form>
      </div>
    </div>
    <!-- 选择商品 -->
    <chooseproducts v-show="viewState == 2" ref="divSp" @backData="backData" @doback="resetState" />
  </div>
</template>

<script>
  import req from '@/api/storage/allocation.js'
  import chooseproducts from './relation/chooseproducts'
  import {
    getCurrentDate
  } from '@/utils/index.js'
  import {
    getServiceStationByOrgSid,
    selAllByOrgSidPath,
    getOrgSidByPath,
    fetchBySid,
    tranTwo
  } from '@/api/Common/dictcommons'
  export default {
    components: {
      chooseproducts,
    },
    data() {
      return {
        viewTitle: '',
        viewState: 1,
        submitdisabled: false,
        activeNames: '1',
        index: 0,
        formobj: {
          "sid": "",
          "billNo": "",
          "useOrgSid": "",
          "createBySid": window.sessionStorage.getItem('userSid'),
          "createByName": window.sessionStorage.getItem('name'),
          "deptName": window.sessionStorage.getItem('defaultOrgPathName').substring(window
            .sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1),
          "deptSid": window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage
            .getItem('defaultOrgPath').lastIndexOf('/') + 1),
          "createTime": getCurrentDate(),
          "outOrgName": '',
          "outOrgSid": '',
          "outPlatName": window.sessionStorage.getItem('defaultOrgPathName').substring(window
            .sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1),
          "outPlatSid": window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage
            .getItem('defaultOrgPath').lastIndexOf('/') + 1),
          "inOrgName": '',
          "inOrgSid": '',
          "inPlatName": "",
          "inPlatSid": "",
          "inOrgAttributeKey": "",
          "inOrgAttributeValue": "",
          "confirmName": "",
          "confirmSid": "",
          "remarks": "",
          "grade": "2",
          "createOrgSid": "",
          "procDefId": "",
          "nodeId": "",
          "procInstId": "",
          "nodeState": "待提交",
          "taskId": "",
          "wmsInventoryAllocateBillDetailNewList": []
        },
        rules: {
          inOrgName: [{
            required: true,
            message: '调入分公司不能为空',
            trigger: 'change'
          }],
          inPlatName: [{
            required: true,
            message: '调入站点不能为空',
            trigger: 'change'
          }],
          confirmName: [{
            required: true,
            message: '经办人不能为空',
            trigger: 'change'
          }],
        },
        orgList: [],
        deptList: [],
        operatorNameList: [],
        warehouseList: [],
        warehouseRackList: []
      }
    },
    methods: {
      init() {

        getOrgSidByPath({
          orgPath: window.sessionStorage.getItem('defaultOrgPath')
        }).then((resp) => {
          if (resp.success) {
            this.formobj.createOrgSid = resp.data
            this.formobj.inOrgSid = resp.data
            this.formobj.outOrgSid = resp.data
            fetchBySid(resp.data).then((respsone) => {
              if (respsone.success) {
                this.formobj.inOrgName = respsone.data.name
                this.formobj.outOrgName = respsone.data.name
              }
            })
          }
        })

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

        selAllByOrgSidPath({
          orgSidPath: window.sessionStorage.getItem('defaultOrgPath')
        }).then((res) => {
          if (res.success) {
            console.log("selAllByOrgSidPath", res);
            this.operatorNameList = res.data
          }
        })
      },
      // 合计
      getSummaries(param) {
        const {
          columns,
          data
        } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (column.property === 'count') {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'amount') {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          }
        })
        return sums
      },

      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

        getServiceStationByOrgSid(choose[0].sid).then((res) => {
          if (res.success) {
            this.formobj.inDeptSid = ''
            this.formobj.inDeptName = ''
            this.formobj.inOrgAttributeKey = ''
            this.formobj.inOrgAttributeValue = ''
            console.log("getListDeptByOrgSid", res);
            this.deptList = res.data
          }
        })

      },

      selectInDeptName(val) {
        console.log("selectInDeptName", val);

        const choose = this.deptList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>selectInDeptName', choose)
        this.formobj.inPlatSid = choose[0].sid
        this.formobj.inPlatName = choose[0].name
        this.formobj.inOrgAttributeKey = choose[0].orgAttributeKey
        this.formobj.inOrgAttributeValue = choose[0].orgAttributeValue

      },
      selectOperatorName(val) {
        console.log("selectOperatorName", val);
        const choose = this.operatorNameList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>selectOutOrg', choose)
        this.formobj.confirmSid = choose[0].sid
        this.formobj.confirmName = choose[0].name
      },

      getWarehouseAreaList(sid) {
        var query = {
          ckSid: sid
        }
        req.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('>>>>>>>>>selectInOrg', choose)
        row.inWarehouseSid = choose[0].sid
        row.inWarehouseName = choose[0].warehouseName
        row.inWarehouseRackSid = ''
        row.inWarehouseRackCode = ''


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

        const choose = this.warehouseRackList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>selectInOrg', choose)
        row.inWarehouseRackSid = choose[0].sid
        row.inWarehouseRackCode = choose[0].areaCode

      },
      showAdd() {

        this.init(),
          this.viewTitle = '【新增】商品调拨申请'
        this.$nextTick(() => {
          this.$refs['form_obj'].clearValidate()
        })
      },
      showEdit(sid) {

        this.init()

        this.viewTitle = '【修改】商品调拨申请'
        this.$nextTick(() => {
          this.$refs['form_obj'].clearValidate()
        })
        req.init(sid).then((res) => {
          if (res.success) {
            this.formobj = res.data
          }
        })
      },

      backData(value) {
        this.viewState = 1
        if (value.length > 0) {
          value.forEach((e) => {
            this.formobj.wmsInventoryAllocateBillDetailNewList.push({
              goodsSpuSid: e.goodsSpuSid,
              goodsSpuName: e.goodsSpuName,
              goodsSkuCode: e.goodsSkuCode,
              goodsSkuOwnSpec: e.goodsSkuOwnSpec,
              goodsSkuSid: e.goodsSkuSid,
              goodsSkuTitle: e.goodsSkuTitle,
              billSid: this.formobj.sid,
              inventorySid: e.inventorySid,
              warehouseSid: e.warehouseSid,
              warehouseName: e.warehouseName,
              warehouseZoneSid: e.warehouseZoneSid,
              warehouseZoneName: e.warehouseZoneName,
              warehouseAreaSid: e.warehouseAreaSid,
              warehouseArea: e.warehouseArea,
              warehouseRackSid: e.warehouseRackSid,
              warehouseRackCode: e.warehouseRackCode,
              taxPrice: e.taxPrice,
              stockCount: e.count,
              inWarehouseSid: '',
              inWarehouseName: '',
              inWarehouseRackSid: '',
              inWarehouseRackCode: '',
              count: 0,
              amount: 0,
              requAmount: e.taxPrice,
              markUpRatio: 0,
              unit: e.unit,
              goodsID: e.goodsID,
              manufacturerSid: e.manufacturerSid,
              manufacturerName: e.manufacturerName
            })
          })
        }
      },
      deleteGoods(index) {
        this.formobj.wmsInventoryAllocateBillDetailNewList.splice(index, 1)
      },
      resetState() {
        this.viewState = 1
      },
      seleGoods() {
        this.viewState = 2
        const aa = []
        this.$refs['divSp'].showData(aa, this.formobj.deptSid)
      },

      // 计算调拨单、调拨金额
      commodityComputeYHAndXSJE(row) {
        console.log("commodityComputeYHAndXSJE", row);
        row.requAmount = (Number(row.taxPrice) * Number(1 + Number(row.markUpRatio) / 100)).toFixed(2)
        row.amount = (Number(row.count) * Number(row.requAmount)).toFixed(2)
      },
      // 计算调拨金额
      commodityComputeYHAndXSJE2(row) {

        if (Number(row.stockCount) < Number(row.count)) {
          row.count = Number(row.stockCount)
        } else {
          row.amount = (Number(row.count) * Number(row.requAmount)).toFixed(2)
        }

      },
      saveOrUpdate() {
        console.log("saveOrUpdate", this.formobj);

        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
            })
          }
        })
      },
      confirm() {
        console.log("saveOrUpdate", this.formobj);
        this.$refs['form_obj'].validate((valid) => {
          if (valid) {

            if (this.formobj.wmsInventoryAllocateBillDetailNewList.length == 0) {
              this.$message({
                type: "warning",
                showClose: true,
                message: '调拨商品不能为空'
              })
              return
            }

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

              if (Number(item.count) == 0) {
                this.$message({
                  type: "warning",
                  showClose: true,
                  message: '调拨数量不能为空或0'
                })
                return
              }

            }

            this.submitdisabled = true
            req.allocation(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": "",
          "useOrgSid": "",
          "createBySid": window.sessionStorage.getItem('userSid'),
          "createByName": window.sessionStorage.getItem('name'),
          "deptName": window.sessionStorage.getItem('defaultOrgPathName').substring(window
            .sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1),
          "deptSid": window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage
            .getItem('defaultOrgPath').lastIndexOf('/') + 1),
          "createTime": getCurrentDate(),
          "outOrgName": '',
          "outOrgSid": '',
          "outPlatName": window.sessionStorage.getItem('defaultOrgPathName').substring(window
            .sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1),
          "outPlatSid": window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage
            .getItem('defaultOrgPath').lastIndexOf('/') + 1),
          "inOrgName": '',
          "inOrgSid": '',
          "inPlatName": "",
          "inPlatSid": "",
          "inOrgAttributeKey": "",
          "inOrgAttributeValue": "",
          "confirmName": "",
          "confirmSid": "",
          "remarks": "",
          "grade": "2",
          "createOrgSid": "",
          "procDefId": "",
          "nodeId": "",
          "procInstId": "",
          "nodeState": "待提交",
          "taskId": "",
          "wmsInventoryAllocateBillDetailNewList": []
        }
        this.submitdisabled = false
        this.$emit('doback')
      }
    }
  }
</script>

<style scoped>
  .formaddcopy02 .el-row .el-col /deep/ .el-form-item__error {
    margin-left: 120px !important;
  }

  .must {
    color: #f00;
  }

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

  .span-sty2 {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    line-height: 42px;
    text-align: right;
    font-size: 14px;
    color: #606266;
    font-weight: 600;
    width: 70px;
    padding-right: 5px;
    border-right: 1px solid #e0e3eb;
    width: 110px !important;
  }

  .addinputInfo2 {
    margin-left: 110px !important;
  }

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



  .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>
