<template>
  <div class="app-container">
    <div v-show="viewState == 1">

      <div class="tab-header webtop">
        <!-- 标题 -->
        <div>【新增】维修出库</div>
        <!-- start 添加修改按钮 -->
        <div>
          <!-- <el-button type="primary" size="small" @click="seleMaintenance">选择维修工单</el-button> -->
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate">出库</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"><span class="must">*</span> 操作人</div>
              <el-form-item prop="createByName">
                <span class="addinputw addinputInfo">{{formobj.createByName}}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <div class="span-sty"><span class="must">*</span> 操作部门</div>
              <el-form-item prop="deptName">
                <span class="addinputw addinputInfo">{{formobj.deptName}}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <div class="span-sty">操作日期</div>
              <el-form-item prop="createByName">
                <el-form-item><span class="addinputw addinputInfo">{{ formobj.createTime }}</span></el-form-item>
              </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="warehouseManager">
                <el-select v-model="formobj.warehouseManager" filterable clearable placeholder="请选择"
                  class="addinputw addinputInfo" @change="receivePerSelect">
                  <el-option v-for="item in receivePerList" :key="item.sid" :label="item.name" :value="item.sid">
                  </el-option>
                </el-select>

              </el-form-item>
            </el-col>

            <el-col :span="16">
              <div class="span-sty">备注</div>
              <el-form-item>
                <el-input v-model="formobj.remarks" placeholder="备注" class="addinputw addinputInfo" clearable />
              </el-form-item>
            </el-col>

          </el-row>

          <div class="title titleOne">
            <div>维修工单</div>
          </div>

          <el-row>
            <el-col :span="8">
              <div class="span-sty">维修工单编号</div>
              <el-form-item>
                <span class="addinputw addinputInfo">{{formobj.sourceBillNo}}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <div class="span-sty">单据日期</div>
              <el-form-item>
                <span class="addinputw addinputInfo">{{formobj.billDate}}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <div class="span-sty">服务顾问</div>
              <el-form-item>
                <el-form-item><span class="addinputw addinputInfo">{{ formobj.waitorName }}</span></el-form-item>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>

            <el-col :span="8">
              <div class="span-sty">工单类型</div>
              <el-form-item>
                <span class="addinputw addinputInfo">{{formobj.billType}}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <div class="span-sty">科目</div>
              <el-form-item>
                <span class="addinputw addinputInfo">{{formobj.subject}}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <div class="span-sty">是否外出</div>
              <el-form-item>
                <el-radio-group class="addinputw addinputInfo" :disabled="true" v-model="formobj.isGoOut">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>

            <el-col :span="8">
              <div class="span-sty">客户名称</div>
              <el-form-item>
                <span class="addinputw addinputInfo">{{formobj.customerName}}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <div class="span-sty">车牌号/车架号</div>
              <el-form-item>
                <span class="addinputw addinputInfo">{{formobj.vehMark}}/{{formobj.vinNo}}</span>
              </el-form-item>
            </el-col>

            <!-- <el-col :span="8">
              <div class="span-sty">客户单位</div>
              <el-form-item>
                <el-form-item><span class="addinputw addinputInfo">{{ formobj.customerOrg }}</span></el-form-item>
              </el-form-item>
            </el-col> -->
          </el-row>

          <div class="title titleOne">
            <div>服务项目</div>
          </div>
          <el-table v-loading="listLoading" :data="formobj.sitemVoList" border>
            <!-- <el-table-column type="selection" align="center" width="50"/> -->
            <el-table-column label="序号" type="index" width="80" :index="indexMethod" align="center" />
            <el-table-column label="操作" wid align="center" width="120">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="addGoods(scope.row)">商品出库</el-button>
              </template>
            </el-table-column>
            <el-table-column label="服务项目" prop="serviceItem" align="center" />
            <el-table-column label="工种" prop="serviceType" align="center" />
            <el-table-column label="科目" prop="subject" align="center" />
            <el-table-column label="维修人" prop="repairerName" align="center" />
            <el-table-column label="工时提成" prop="examineHourPrice" align="center" />
            <el-table-column label="工时单价" prop="hourPrice" align="center" />
            <el-table-column label="工时数" prop="hours" align="center" />
            <el-table-column label="销售价" prop="price" align="center" />
            <el-table-column label="折扣" prop="discount" align="center" />
            <el-table-column label="优惠" prop="discountAmount" align="center" />
            <el-table-column label="金额" prop="amount" align="center" />
            <el-table-column label="备注" prop="remarks" align="center" />
          </el-table>

          <div class="title titleOne">
            <div>商品列表</div>
          </div>
          <el-row>
            <el-col :span="24">
              <div class="span-sty span-sty-one" style="width: 300px;!important;">前台登记时对商品要求备注</div>
              <el-form-item><el-input class="addinputInfo-one" style="width: 70%" v-model="formobj.registerRemarks"
                  clearable placeholder="" /></el-form-item>
            </el-col>
          </el-row>
          <el-table v-loading="listLoading" :data="formobj.detailList" border>
            <!-- <el-table-column type="selection" align="center" width="50"/> -->
            <el-table-column label="序号" type="index" width="80" :index="indexMethod" align="center" />
            <el-table-column label="操作" wid align="center" width="80">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="deleteGoods(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column label="项目名称" prop="serviceItem" width="120" align="center" />
            <!-- <el-table-column label="商品名称" prop="goodsSpuName" align="center" /> -->

            <el-table-column label="商品名称" align="center" min-width="180">
              <template slot-scope="scope">
                <el-popover placement="right" width="800" 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="商品名称" width="180" align="center" />
                      <el-table-column fixed prop="goodsSkuCode" label="商品图号" width="100" align="center" />
                      <el-table-column prop="count" label="库存数量" width="100" align="center" />
                      <el-table-column prop="unit" label="单位" align="center" />
                      <el-table-column prop="money" label="入库单价" width="100" align="center" />
                      <el-table-column prop="supplierName" label="供应商" width="200" align="center" />
                      <el-table-column prop="warehouseName" label="仓库" width="150" align="center" />
                      <el-table-column prop="warehouseRackCode" label="库位" width="100" align="center" />
                      <el-table-column prop="goodsID" label="商品ID" width="150" align="center" />
                      <el-table-column prop="goodsSkuOwnSpec" label="规格" width="100" align="center" />
                    </el-table>

                    <pagination v-show="commodityData.length > 0" :total="commodityQuery.total"
                      :page.sync="commodityQuery.current" :limit.sync="commodityQuery.size" class="total pager"
                      @pagination="commodityInput(scope.row)" />

                    <!--  <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)"
                    clearable placeholder="商品名称" />
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="商品编码" prop="goodsSkuCode" width="100" align="center" />
            <el-table-column label="规格" prop="goodsSkuOwnSpec" width="120" align="center" />
            <el-table-column label="单位" prop="unit" align="center" />
            <el-table-column label="仓库" prop="warehouseName" width="150" align="center" />
            <el-table-column label="库位" prop="warehouseRackCode" align="center" />
            <el-table-column label="销售单价" prop="price" width="120" align="center" />
            <el-table-column label="已出数量" prop="outboundCount" width="120" align="center" />
            <el-table-column label="库存数量" prop="inventoryNum" width="120" align="center" />
            <el-table-column label="出库数量" align="center" width="120">
              <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 label="金额" prop="amount" align="center" />
            <el-table-column label="备注" align="center" width="220">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" clearable placeholder="" />
              </template>
            </el-table-column>
          </el-table>

        </el-form>

      </div>
    </div>

    <!-- 选择维修单 -->
    <chooseproducts v-show="viewState == 2" ref="divSp" @backData="backData" @doback="resetState" />

  </div>
</template>

<script>
  import req from '@/api/maintenanceReceive/maintenanceReceive.js'
  import chooseproducts from './relation/chooseproducts'
  import {
    getOrgSidByPath,
    selAllByOrgSidPath
  } from '@/api/Common/dictcommons'
  import {
    getCurrentDate
  } from '@/utils/index.js'
  export default {
    components: {
      chooseproducts,
    },
    data() {
      return {
        viewState: 1,
        listLoading: false,
        submitdisabled: false,

        formobj: {
          "sid": "",
          "createBySid": window.sessionStorage.getItem('userSid'),
          "createByName": window.sessionStorage.getItem('name'),
          "sourceBillSid": "",
          "warehouseManagerSid": "",
          "warehouseManager": "",
          "useOrgSid": "",
          "createOrgSid": "",
          "deptSid": window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage
            .getItem('defaultOrgPath').lastIndexOf('/') + 1),
          "deptName": window.sessionStorage.getItem('defaultOrgPathName').substring(window
            .sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1),
          "createTime": getCurrentDate(),
          "remarks": "",
          "sourceBillNo": "",
          "waitorName": "",
          "billDate": "",
          "billType": "",
          "subject": "",
          "customerName": "",
          "vehMark": "",
          "vinNo": "",
          "customerOrg": "",
          "sitemVoList": [

          ],
          "detailList": [

          ]
        },
        receivePerList: [],
        // commodity商品
        commodityLoading: false,
        commodityQuery: {
          current: 1,
          size: 10,
          total: 0,
          params: {
            name: '',
            useOrgSid: '',
          }
        },
        commodityData: [],

        rules: {
          createByName: [{
            required: true,
            message: '制单人不能为空',
            trigger: 'blur'
          }],
          deptName: [{
            required: true,
            message: '制单部门不能为空',
            trigger: 'blur'
          }],
          createTime: [{
            required: true,
            message: '制单日期不能为空',
            trigger: 'blur'
          }],
          warehouseManager: [{
            required: true,
            message: '请选择领料人',
            trigger: 'change'
          }],

        }
      }
    },
    created() {

    },
    methods: {
      initData() {

        selAllByOrgSidPath({
          orgSidPath: window.sessionStorage.getItem('defaultOrgPath')
        }).then((res) => {
          if (res.success) {
            this.receivePerList = res.data

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

          }
        })

      },

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

        var params = {
          sid: sid
        }
        req.initBill(params)
          .then(resp => {
            if (resp.success) {
              console.log('>>>>>>>>>initBill', resp)

              this.formobj = resp.data
              this.formobj.detailList = []

              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)
              this.formobj.createBySid = window.sessionStorage.getItem('userSid')
              this.formobj.createByName = window.sessionStorage.getItem('name')
              this.formobj.createTime = getCurrentDate()

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

            } else {
              // 根据resp.code进行异常情况处理
            }
          })
          .catch(() => {})


      },
      backData(value) {
        this.viewState = 1
        // 初始化
        var params = {
          sid: value
        }
        req.initBill(params)
          .then(resp => {
            if (resp.success) {
              console.log('>>>>>>>>>initBill', resp)

              this.formobj = resp.data
              this.formobj.detailList = []

              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)
              this.formobj.createBySid = window.sessionStorage.getItem('userSid')
              this.formobj.createByName = window.sessionStorage.getItem('name')
              this.formobj.createTime = getCurrentDate()

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

            } else {
              // 根据resp.code进行异常情况处理
            }
          })
          .catch(() => {})

      },
      resetState() {
        this.viewState = 1
      },
      seleMaintenance() {
        this.viewState = 2
        const aa = []
        this.$refs['divSp'].showData(aa, this.formobj.createOrgSid)
      },

      saveOrUpdate() {
        console.log('>>>>>>>>>saveOrUpdate', this.formobj)

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

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

          if (item.goodSpuSid == '') {
            this.$message({
              showClose: true,
              type: 'warning',
              message: "请添加商品"
            })
            return
          }

          if (Number(item.count) == 0) {
            this.$message({
              showClose: true,
              type: 'warning',
              message: "商品出库数量不能0"
            })
            return
          }
        }

        this.$refs['form_obj'].validate((valid) => {
          if (valid) {
            req.saveOutBill(this.formobj)
              .then(resp => {
                if (resp.success) {
                  this.$message({
                    showClose: true,
                    type: 'success',
                    message: resp.msg
                  })
                  this.handleReturn('true')
                } else {
                  // 根据resp.code进行异常情况处理
                }
              })
              .catch(() => {})

          }
        })
      },
      handleReturn(isreload) {
        if (isreload === 'true') this.$emit('reloadlist')
        this.formobj = {
          "sid": "",
          "createBySid": window.sessionStorage.getItem('userSid'),
          "createByName": window.sessionStorage.getItem('name'),
          "sourceBillSid": "",
          "warehouseManagerSid": "",
          "warehouseManager": "",
          "useOrgSid": "",
          "createOrgSid": "",
          "deptSid": window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem(
            'defaultOrgPath').lastIndexOf('/') + 1),
          "deptName": window.sessionStorage.getItem('defaultOrgPathName').substring(window.sessionStorage.getItem(
            'defaultOrgPathName').lastIndexOf('/') + 1),
          "createTime": getCurrentDate(),
          "remarks": "",
          "sourceBillNo": "",
          "waitorName": "",
          "billDate": "",
          "billType": "",
          "subject": "",
          "customerName": "",
          "vehMark": "",
          "vinNo": "",
          "customerOrg": "",
          "sitemVoList": [

          ],
          "detailList": [

          ]
        }
        this.submitdisabled = false
        this.$emit('doback')
      },
      indexMethod(index) {
        return index + 1
      },
      receivePerSelect(val) {
        const choose = this.receivePerList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>receivePerSelect', choose)
        this.formobj.warehouseManagerSid = choose[0].sid
        this.formobj.warehouseManager = choose[0].name
      },

      commodityInput(row) {
        console.log("commodityInput》》》》", row)
        this.commodityQuery.params.name = row.goodsSpuName
        this.commodityQuery.params.busrepairBillsid = row.sourceBillSid
        this.commodityQuery.params.useOrgSid = window.sessionStorage.getItem('defaultOrgPath').substring(window
          .sessionStorage
          .getItem('defaultOrgPath').lastIndexOf('/') + 1)
        this.commodityLoading = true
        req.getGoodsListPage(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
          }
        })
      },
      commodityCurrentChange(value, row) {
        console.log("commodityCurrentChange》》》》", value)
        console.log("commodityCurrentChange》》》》", row)

        row.inventorySid = value.inventorySid
        row.goodsID = value.goodsID
        row.goodSpuSid = value.goodSpuSid
        row.goodsSpuName = value.goodsSpuName
        row.goodsSkuSid = value.goodsSkuSid
        row.goodsSkuTitle = value.goodsSkuTitle
        row.goodsSkuCode = value.goodsSkuCode
        row.goodsSkuOwnSpec = value.goodsSkuOwnSpec
        row.unit = value.unit
        row.warehouseSid = value.warehouseSid
        row.warehouseName = value.warehouseName
        row.warehouseRackSid = value.warehouseRackSid
        row.warehouseRackCode = value.warehouseRackCode
        row.outboundCount = value.outboundCount // 已出库数量
        row.inventoryNum = value.count // 库存数量
        row.count = 0 //出库数量
        row.amount = 0.00
        row.price = value.price
        row.remarks = ''
        document.body.click()
      },


      addGoods(row) {

        var goods = {
          "sourceBillNo": this.formobj.sourceBillNo,
          "sourceBillSid": this.formobj.sourceBillSid,
          "sitemSid": row.serviceItemSid,
          'serviceItem': row.serviceItem,
          "inventorySid": "",
          "goodsID": "",
          "goodSpuSid": "",
          "goodsSpuName": "",
          "goodsSkuSid": "",
          "goodsSkuTitle": "",
          "goodsSkuCode": "",
          "goodsSkuOwnSpec": "",
          "currentCount": "",
          "unit": "",
          "warehouseSid": "",
          "warehouseName": "",
          "warehouseRackSid": "",
          "warehouseRackCode": "",
          "count": 0,
          "price": '',
          'amount': 0.00,
          "outboundCount": 0,
          "remarks": ""
        }

        this.formobj.detailList.push(goods)

      },
      deleteGoods(row) {

        const index = this.formobj.detailList.findIndex((item) => item.goodSpuSid == row.goodSpuSid)
        console.log('>>>>>>>>>receivePerSelect', index)
        this.formobj.detailList.splice(index, 1)

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

        row.amount = (Number(row.count) * Number(row.price)).toFixed(2)
      },

    }
  }
</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;
  }

  .el-radio /deep/ .el-radio__label {

    font-size: 14px !important;

  }

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

  .span-sty-one {
    width: 180px !important;
  }
</style>
