<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <div class="tab-header webtop">
        <!-- 标题 -->
        <div>{{title}}采购订单</div>
        <!-- start 添加修改按钮 -->
        <div>
          <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">申请人</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>
                <el-date-picker v-model="formobj.createTime" type="date" class="addinputw addinputInfo"
                  value-format="yyyy-MM-dd" placeholder="选择日期">
                </el-date-picker></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="supplierName"> <el-select v-model="formobj.supplierName" filterable clearable
                  placeholder="请选择供应商" class="addinputw addinputInfo" @change="supplierNameSelect">
                  <el-option v-for="(item,index ) in supplierList" :key="index" :label="item.supplierName"
                    :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="wareHouseName">
                <el-select v-model="formobj.wareHouseName" placeholder="请选择收货仓库" class="addinputw addinputInfo"
                  @change="selectWarehouseName">
                  <el-option v-for="(item,index ) in warehouseList" :key="index" :label="item.warehouseName"
                    :value="item.sid" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="must">*</span> 业务员</div>
              <el-form-item prop="purchaserName">
                <el-select v-model="formobj.purchaserName" filterable clearable placeholder="请选择业务员"
                  class="addinputw addinputInfo" @change="allOrgperSelect">
                  <el-option v-for="(item,index ) in allOrgperList" :key="index" :label="item.name" :value="item.sid">
                  </el-option>
                </el-select>

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

          <el-row>
            <el-col :span="16">
              <div class="span-sty">银行账号</div>
              <el-form-item prop="bankAccount"> <el-input class="addinputw addinputInfo"
                  v-model="formobj.purchaseBillAmount.bankAccount" clearable placeholder=""
                  oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" /></el-form-item>

            </el-col>
            <el-col :span="8">
              <div class="span-sty">货币类别</div>
              <el-form-item prop="currencyValue">
                <el-select v-model="formobj.purchaseBillAmount.currencyValue" placeholder="请选择货币类别"
                  class="addinputw addinputInfo" @change="selectCurrency">
                  <el-option v-for="(item,index) in currencyTypeList" :key="index" :label="item.dictValue"
                    :value="item.dictKey" />
                  </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" style="margin-top: 10px;">
            <div>商品列表</div>
            <el-button type="primary" size="mini" class="btntopblueline" @click="goodsAdd()">添加</el-button>
          </div>
          <el-table v-loading="listLoading" :data="formobj.purchaseBillDetailList" border style="width: 100%;"
            show-summary :summary-method="getSummaries">
            <!-- <el-table-column fixed width="50" type="selection" align="center" /> -->
            <el-table-column fixed width="80" 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="deleteGoods(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column label="商品编码" prop="goodsSkuCode" width="150" align="center" />
            <el-table-column label="商品名称" prop="goodsSkuTitle" width="150" align="center" />
            <el-table-column label="商品规格" prop="goodsSkuOwnSpec" width="150" align="center" />
            <el-table-column label="单位" prop="unit" width="120" align="center" />
            <el-table-column label="采购数量" align="center" prop="count" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.count" clearable placeholder=""
                  oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" @input="calculation(scope.row,'count',$event)" />
              </template>
            </el-table-column>
            <el-table-column label="数量(pcs)" prop="pcsCount" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.pcsCount" clearable placeholder=""
                  oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" />
              </template>
            </el-table-column>
            <!-- <el-table-column label="数量(pcs)" prop="pcsNum" width="120" align="center" /> -->
            <el-table-column label="吊牌价" prop="tagPrice" width="120" align="center" />
            <!-- <el-table-column label="单价" prop="cost" width="120" align="center" /> -->
            <el-table-column label="单价" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.cost" clearable placeholder=""
                  @input="calculation(scope.row,'cost',$event)"
                  oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" />
              </template>
            </el-table-column>
            <el-table-column label="折扣率(%)" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.discountRate" clearable placeholder=""
                  @input="calculation(scope.row,'count',$event)"
                  oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" />
              </template>
            </el-table-column>
            <el-table-column prop="discountPrice" label="折扣单价" width="120" align="center" />
            <el-table-column prop="shareAmount" label="分摊金额" width="150" align="center" />
            <el-table-column prop="amount" label="总价" width="120" align="center" />
            <!-- <el-table-column prop="taxRate" label="税率" width="120" align="center" /> -->
            <el-table-column label="税率(%)" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.taxRate" clearable placeholder=""
                  @input="calculation(scope.row,'count',$event)"
                  oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" />
              </template>
            </el-table-column>
            <el-table-column prop="unTaxPrice" label="未含税价" width="120" align="center" />
            <el-table-column prop="taxAmount" label="总税额" width="120" align="center" />
            <el-table-column prop="unTaxTotalAmount" label="未含总税价" width="120" align="center" />
            <!-- <el-table-column prop="cycle" label="采购周期" width="120" align="center" /> -->
            <el-table-column label="采购周期" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.cycle" clearable placeholder="" @input="computeDate(scope.row)"
                  oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" /> </template>
            </el-table-column>
            <el-table-column prop="deliveryDate" label="预计到货日期" width="180" align="center" />
            <!--  <el-table-column label="预计到货日期" align="center" min-width="250">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.deliveryDate" type="date" value-format="yyyy-MM-dd"
                  placeholder="选择日期" />
              </template>
            </el-table-column> -->
            <!-- <el-table-column prop="manufactureDate" label="生产日期" width="120" align="center" /> -->
            <el-table-column label="生产日期" align="center" min-width="250">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.madeDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"
                  @change="manufactureDateChange(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="expireDate" label="过期日期" width="120" align="center" />
            <el-table-column prop="batchNumber" label="批次号" width="200" align="center" />
            <el-table-column prop="goodsNum" label="货号" width="120" align="center" />
            <el-table-column label="备注" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" clearable placeholder="" />
              </template>
            </el-table-column>
          </el-table>

          <el-row class="first_row" style="margin-top: 10px;">
            <el-col :span="8">
              <div class="span-sty">采购运费</div>
              <el-form-item prop="freight"> <el-input class="addinputw addinputInfo"
                  v-model="formobj.purchaseBillAmount.freight" clearable placeholder="" @change="computeShareAmount"
                  oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" /></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">运费分摊方式</div>
              <el-form-item prop="freightShareTypeValue">
                <el-select v-model="formobj.purchaseBillAmount.freightShareTypeValue" placeholder="请选择分摊方式"
                  class="addinputw addinputInfo" @change="selectFreightShareType">
                  <el-option v-for="(item,index ) in shareTypeList" :key="index" :label="item.dictValue"
                    :value="item.dictKey" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"> 结算账户</div>
              <el-form-item prop="settleAccountValue">
                <el-select v-model="formobj.purchaseBillAmount.settleAccountValue" filterable clearable
                  placeholder="请选择结算账户" class="addinputw addinputInfo" @change="selectSettleAccount">
                  <el-option v-for="(item,index ) in settlementList" :key="index" :label="item.dictValue"
                    :value="item.dictKey" />
                  </el-option>
                </el-select>

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

          <el-row>
            <el-col :span="8">
              <div class="span-sty">其他费用</div>
              <el-form-item prop="otherAmount"> <el-input class="addinputw addinputInfo"
                  v-model="formobj.purchaseBillAmount.otherAmount" clearable placeholder="" @change="computeShareAmount"
                  oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" />
              </el-form-item>

            </el-col>
            <el-col :span="8">
              <div class="span-sty">其他费用分摊方式</div>
              <el-form-item prop="otherShareTypeValue">
                <el-select v-model="formobj.purchaseBillAmount.otherShareTypeValue" placeholder="请选择分摊方式"
                  class="addinputw addinputInfo" @change="selectOtherShareType">
                  <el-option v-for="(item,index ) in shareTypeList" :key="index" :label="item.dictValue"
                    :value="item.dictKey" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">预付金额</div>
              <el-form-item prop="prepayment"> <el-input class="addinputw addinputInfo"
                  v-model="formobj.purchaseBillAmount.prepayment" clearable placeholder=""
                  oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="24">
              <div class="span-sty">附件</div>
              <el-form-item prop="imgList">
                <upload-img ref="uploadImg" class="addinputw" v-model="imgList" :limit="50" bucket="map"
                  :upload-data="{ type: '0001' }" @change="backData2" />
              </el-form-item>
            </el-col>

          </el-row>

        </el-form>

      </div>
    </div>
    <!-- 选择商品 -->
    <chooseproducts v-show="viewState == 2" ref="divSp" @backData="backData" @doback="resetState" />
  </div>
</template>

<script>
  import req from '@/api/purchase/purchaseOrder.js'
  import chooseproducts from './relation/chooseproducts'
  import {
    choiceSupplierInfo,
    getWarehouses,
    selAllByOrgSidPath,
    typeValues
  } from '@/api/Common/dictcommons'
  import uploadImg from '@/components/uploadFile/uploadImg'
  import {
    getCurrentDate
  } from '@/utils/index.js'
  export default {
    components: {
      chooseproducts,
      uploadImg
    },
    data() {
      return {
        title: "【新增】",
        viewState: 1,
        listLoading: false,
        submitdisabled: false,
        formobj: {
          "sid": "",
          "remarks": "",
          "createTime": getCurrentDate(),
          "createBySid": window.sessionStorage.getItem('userSid'),
          "createByName": window.sessionStorage.getItem('name'),
          "sourceBillSid": "",
          "sourceBillNo": "",
          "billNo": "",
          "purchaseTypeKey": "",
          "purchaseTypeValue": "",
          "purchaseReasonKey": "",
          "purchaseReasonValue": "",
          "payTypeKey": "",
          "payTypeValue": "",
          "supplierSid": "",
          "supplierName": "",
          "supplierPhone": "",
          "purchaserSid": "",
          "purchaserName": "",
          "deliveryDate": "",
          "wareHouseSid": "",
          "wareHouseName": "",
          "deptSid": window.sessionStorage.getItem('defaultDeptSid'),
          "deptName": window.sessionStorage.getItem('defaultDeptName'),
          "useOrgSid": window.sessionStorage.getItem('orgSid'),
          "createOrgSid": window.sessionStorage.getItem('defaultDeptSid'),
          "orgPath": window.sessionStorage.getItem('orgSidPath'),
          "purchaseBillAmount": {
            "sid": "",
            "billSid": "",
            "errorAmount": "",
            "discountAmount": "",
            "payableAmount": "",
            "freight": "",
            "freightShareTypeKey": "",
            "freightShareTypeValue": "",
            "otherAmount": "",
            "otherShareTypeKey": "",
            "otherShareTypeValue": "",
            "settleAccountKey": "",
            "settleAccountValue": "",
            "prepayment": "",
            "paymentTerm": "",
            "bankName": "",
            "bankAccountName": "",
            "bankAccount": "",
            "currencyKey": "",
            "currencyValue": ""
          },
          "purchaseBillExtend": {
            "sid": "",
            "billSid": "",
            "logisticsNum": "",
            "productProgress": "",
            "receiveStateKey": "",
            "receiveStateValue": "",
            "deliveryStateKey": "",
            "deliveryStateValue": ""
          },
          "purchaseBillDetailList": [],
          "purchaseAppendixList": [

          ]
        },
        supplierList: [],
        warehouseList: [],
        allOrgperList: [],
        currencyTypeList: [],
        settlementList: [],
        shareTypeList: [],
        rules: {
          createTime: [{
            required: true,
            message: '请选择日期',
            trigger: 'change'
          }],
          supplierName: [{
            required: true,
            message: '请选择供应商',
            trigger: 'change'
          }],
          wareHouseName: [{
            required: true,
            message: '请选择收货仓库',
            trigger: 'change'
          }],
          purchaserName: [{
            required: true,
            message: '请选择业务员',
            trigger: 'change'
          }],

        },
        imgList: [],
        allCount: 0,
        allPcsNum: 0,
        allShareAmount: 0,
        allAmount: 0,
        allNotTaxPprice: 0,
        allTotalTax: 0,
        allTotalNotTaxPprice: 0,
      }
    },
    created() {

    },
    methods: {

      init() {
        // 供应商
        choiceSupplierInfo({
          createOrgSid: window.sessionStorage.getItem('orgSidPath')
        }).then((resp) => {
          if (resp.success) {
            this.supplierList = resp.data
          }
        })

        // 仓库
        getWarehouses({
          orgPath: window.sessionStorage.getItem('orgSidPath'),
        }).then((res) => {
          if (res.success) {
            this.warehouseList = res.data
          }
        })

        // 业务员
        selAllByOrgSidPath({
          orgSidPath: window.sessionStorage.getItem('orgSidPath')
        }).then((res) => {
          if (res.success) {
            this.allOrgperList = res.data
          }
        })

        // 货币
        typeValues({
          type: 'currencyType'
        }).then((res) => {
          if (res.success) {
            this.currencyTypeList = res.data
          }
        })

        // 结算账户
        typeValues({
          type: 'settlementAccount'
        }).then((res) => {
          if (res.success) {
            this.settlementList = res.data
          }
        })

        // 分摊方式
        typeValues({
          type: 'shareType'
        }).then((res) => {
          if (res.success) {
            this.shareTypeList = 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)) {
                this.allCount = prev + curr
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                this.allCount = prev
                return Number(prev).toFixed(2)
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'pcsNum') { // 数量pcs
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                this.allPcsNum = prev + curr
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                this.allPcsNum = prev
                return Number(prev).toFixed(2)
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'shareAmount') { //分摊金额
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                this.allShareAmount = prev + curr
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                this.allShareAmount = prev
                return Number(prev).toFixed(2)
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'amount') { //总价
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                this.allAmount = prev + curr
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                this.allAmount = prev
                return Number(prev).toFixed(2)
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'unTaxPrice') { //未含税价
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                this.allNotTaxPprice = prev + curr
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                this.allNotTaxPprice = prev
                return Number(prev).toFixed(2)
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'taxAmount') { //总税额
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                this.allTotalTax = prev + curr
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                this.allTotalTax = prev
                return Number(prev).toFixed(2)
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'unTaxTotalAmount') { //未含税总价
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                this.allTotalNotTaxPprice = prev + curr
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                this.allTotalNotTaxPprice = prev
                return Number(prev).toFixed(2)
              }
            }, 0)
            sums[index] += ''
          }
        })
        return sums
      },

      // 清除分摊金额 并反算
      calculation(row, updateProp, event) {

        this.formobj.purchaseBillAmount.freight = 0.00
        this.formobj.purchaseBillAmount.otherAmount = 0.00

        // 重新计算
        //  除去修改单价时 修改其他字段都先计算出单价 然后其他价格数据在计算一次
        //  如果修改的是单价 则先把本条数据直接赋值单价  然后其他价格数据在计算一次
        //  后需要把列表其他数据先计算出单价字段 然后其他价格数据在计算一次
        for (var i = 0; i < this.formobj.purchaseBillDetailList.length; i++) {

          var item = this.formobj.purchaseBillDetailList[i]

          if (row.sid != item.sid) {
            // 列表其他数据 先计算单价
            // item.cost = (Number(item.cost) - Number(item.shareAmount) / Number(item.count)).toFixed(2)
            item.cost = Number(item.cost1)
            this.calculation2(item)

          } else {

            // if (updateProp == 'count') {
            //   // 修改的是数量
            //   item.cost = Number(item.cost1)
            //   this.calculation2(item)
            // }

            if (updateProp == 'cost') {
              // 修改的不是单价
              this.calculation2(item)
            } else {
              item.cost = Number(item.cost1)
              this.calculation2(item)
            }

            // if (updateProp == 'discountRate') {
            //   // 修改的是折扣率
            //   item.cost = Number(item.cost1)
            //   this.calculation2(item)
            // }

            // if (updateProp == 'taxRate') {
            //   // 修改的是税率
            //   item.cost = Number(item.cost1)
            //   this.calculation2(item)
            // }



          }

          // 最后把列表所有的分摊金额赋值成0
          item.shareAmount = 0.00
          item.cost1 = Number(item.cost)
          item.count1 = Number(item.count)

        }

      },

      calculation2(row) {

        //  折后单价 = 单价*折扣率 / 100
        row.discountPrice = (Number(row.cost) * Number(row.discountRate) / 100).toFixed(2)
        // console.log("calculation》》》》", row.discountPrice)

        // 总价 = 单价* 数量*折扣率 / 100
        row.amount = (Number(row.count) * Number(row.cost) * Number(row.discountRate) / 100).toFixed(2)
        // console.log("calculation》》》》", row.amount)

        // 总税额 = 总价/(1+税率)*税率
        row.taxAmount = (Number(row.amount) / (1 + Number(row.taxRate) / 100) * Number(row.taxRate) / 100)
          .toFixed(2)
        // console.log("calculation2》》》》", row.taxAmount)

        // 未含税价 =(总价-总税额)/数量
        row.unTaxPrice = ((Number(row.amount) - Number(row.taxAmount)) / row.count).toFixed(2)
        // console.log("calculation2》》》》", row.unTaxPrice)

        // 未含税总价 = 总价-总税额
        row.unTaxTotalAmount = (Number(row.amount) - Number(row.taxAmount)).toFixed(2)
        // console.log("calculation2》》》》", row.unTaxTotalAmount)

      },

      computeDate(row) {
        // 预计到货日期 = 当前日期+采购周期
        row.deliveryDate = this.addDate(getCurrentDate(), Number(row.cycle))

      },
      manufactureDateChange(row) {

        console.log("manufactureDateChange》》》》", row.madeDate)
        console.log("manufactureDateChange》》》》", row.shelfLife)
        row.expireDate = this.addDate(row.madeDate, Number(row.shelfLife))

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

        row.batchNumber = row.madeDate.replace(reg, '') + " - " + row.expireDate.replace(reg, '')

      },
      //  days 只能是int
      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
      },

      // 计算分摊金额
      computeShareAmount() {
        // 分摊金额 =  (采购运费+其他费用)*单价*数量/所有商品总价

        var price = Number(this.formobj.purchaseBillAmount.freight) + Number(this.formobj.purchaseBillAmount
          .otherAmount)

        var all = 0 // 除去最后一个的分摊总和
        var totalAmount = 0 // 原所有商品总价
        for (var i = 0; i < this.formobj.purchaseBillDetailList.length; i++) {

          var item = this.formobj.purchaseBillDetailList[i]
          totalAmount = (Number(totalAmount) + Number(Number(item.cost1) * Number(item.count1))).toFixed(2)
        }

        console.log("price》》》》", price)
        console.log("totalAmount》》》》", totalAmount)
        // 分摊金额 =  (采购运费+其他费用)*单价*数量/ 原所有商品总价

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

          var item = this.formobj.purchaseBillDetailList[i]

          if (i == this.formobj.purchaseBillDetailList.length - 1) {
            // 最后一条数据
            item.shareAmount = (Number(price) - Number(all)).toFixed(2)
            item.cost = (Number(item.cost1) + (Number(item.shareAmount) / Number(item.count))).toFixed(2)

          } else {

            item.shareAmount = (Number(price) * Number(item.cost1) * Number(item.count) / Number(totalAmount))
              .toFixed(2)
            item.cost = (Number(item.cost1) + (Number(item.shareAmount) / Number(item.count))).toFixed(2)
            all += Number(item.shareAmount)


          }

          // this.calculation(item)
          this.calculation2(item)

        }

      },

      goodsAdd() {
        this.viewState = 2
        this.$refs['divSp'].showAdd(this.formobj.createOrgSid)
      },
      deleteGoods(row) {
        console.log("deleteGoods》》》》", row)

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

        })
      },
      backData2(value) {
        console.log('backData2》》》》', value)
        console.log('imgList', this.imgList)

        for (var i = 0; i < this.imgList.length; i++) {
          this.formobj.purchaseAppendixList.push({
            url: this.imgList[i].url
          })
        }


      },
      backData(value) {
        this.viewState = 1
        console.log('>>>>>>>>>backData', value)


        for (var i = 0; i < value.length; i++) {

          this.formobj.purchaseBillDetailList.push({
              "sid": value[i].sid != null ? value[i].sid : '',
              "goodsSkuCode": value[i].goodsSkuCode != null ? value[i].goodsSkuCode : '',
              "goodsSkuTitle": value[i].goodsName != null ? value[i].goodsName : '',
              "goodsSN": value[i].barCode != null ? value[i].barCode : '',
              "goodsSkuOwnSpec": value[i].goodsSkuOwnSpec != null ? value[i].goodsSkuOwnSpec : '',
              "unit": value[i].unit != null ? value[i].unit : '',
              "count": value[i].count != null ? value[i].count : '0',
              "count1": value[i].count != null ? value[i].count1 : '0',
              "pcsCount": value[i].pcsNum != null ? value[i].pcsNum : '0',
              "tagPrice": value[i].tagPrice != null ? value[i].tagPrice : '',
              "cost": value[i].cost != null ? value[i].cost : '',
              "cost1": value[i].cost != null ? value[i].cost1 : '',
              "discountRate": value[i].discountRate != null ? value[i].discountRate : '100',
              "discountPrice": value[i].discountPrice != null ? value[i].discountPrice : '0.00',
              "shareAmount": value[i].shareAmount != null ? value[i].shareAmount : '0.00',
              "amount": value[i].amount != null ? value[i].amount : '0.00',
              "taxRate": value[i].taxRate != null ? value[i].taxRate : '',
              "unTaxPrice": value[i].notTaxPprice != null ? value[i].notTaxPprice : '',
              "taxAmount": value[i].totalTax != null ? value[i].totalTax : '',
              "unTaxTotalAmount": value[i].totalNotTaxPprice != null ? value[i].totalNotTaxPprice : '',
              "cycle": value[i].purchaseCycle != null ? value[i].purchaseCycle : '',
              "deliveryDate": value[i].deliveryDate != null ? value[i].deliveryDate : '',
              "madeDate": value[i].manufactureDate != null ? value[i].manufactureDate : '',
              "shelfLife": value[i].shelfLife != null ? value[i].shelfLife : '',
              "expireDate": value[i].overdueDate != null ? value[i].overdueDate : '',
              "batchNumber": value[i].batchNumber != null ? value[i].batchNumber : '',
              "goodsNum": value[i].itemNumber != null ? value[i].itemNumber : '',
              "remarks": value[i].remarks != null ? value[i].remarks : ''
            }

          )

        }

      },

      resetState() {
        this.viewState = 1
      },

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

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

            if (this.formobj.purchaseBillDetailList.length == 0) {
              this.$message({
                showClose: true,
                type: 'warning',
                message: '请添加采购商品'
              })
              return
            }

            for (var i = 0; i < this.formobj.purchaseBillDetailList.length; i++) {
              var item = this.formobj.purchaseBillDetailList[i]
              if (Number(item.count) == 0) {
                this.$message({
                  showClose: true,
                  type: 'warning',
                  message: '商品采购数量不能为0或空'
                })
                return
              }

              if (Number(item.discountRate) == 0) {
                this.$message({
                  showClose: true,
                  type: 'warning',
                  message: '商品折扣率不能为0或空'
                })
                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
            })
          }
        })
      },

      handleReturn(isreload) {
        if (isreload === 'true') this.$emit('reloadlist')
        this.submitdisabled = false
        this.imgList = []
        this.formobj = {
          "sid": "",
          "remarks": "",
          "createTime": getCurrentDate(),
          "createBySid": window.sessionStorage.getItem('userSid'),
          "createByName": window.sessionStorage.getItem('name'),
          "sourceBillSid": "",
          "sourceBillNo": "",
          "billNo": "",
          "purchaseTypeKey": "",
          "purchaseTypeValue": "",
          "purchaseReasonKey": "",
          "purchaseReasonValue": "",
          "payTypeKey": "",
          "payTypeValue": "",
          "supplierSid": "",
          "supplierName": "",
          "supplierPhone": "",
          "purchaserSid": "",
          "purchaserName": "",
          "deliveryDate": "",
          "wareHouseSid": "",
          "wareHouseName": "",
          "deptSid": window.sessionStorage.getItem('defaultDeptSid'),
          "deptName": window.sessionStorage.getItem('defaultDeptName'),
          "useOrgSid": window.sessionStorage.getItem('orgSid'),
          "createOrgSid": window.sessionStorage.getItem('defaultDeptSid'),
          "orgPath": window.sessionStorage.getItem('orgSidPath'),
          "purchaseBillAmount": {
            "sid": "",
            "billSid": "",
            "errorAmount": "",
            "discountAmount": "",
            "payableAmount": "",
            "freight": "",
            "freightShareTypeKey": "",
            "freightShareTypeValue": "",
            "otherAmount": "",
            "otherShareTypeKey": "",
            "otherShareTypeValue": "",
            "settleAccountKey": "",
            "settleAccountValue": "",
            "prepayment": "",
            "paymentTerm": "",
            "bankName": "",
            "bankAccountName": "",
            "bankAccount": "",
            "currencyKey": "",
            "currencyValue": ""
          },
          "purchaseBillExtend": {
            "sid": "",
            "billSid": "",
            "logisticsNum": "",
            "productProgress": "",
            "receiveStateKey": "",
            "receiveStateValue": "",
            "deliveryStateKey": "",
            "deliveryStateValue": ""
          },
          "purchaseBillDetailList": [],
          "purchaseAppendixList": [

          ]
        }
        this.$emit('doback')
      },

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

        this.title = '【新增】'

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

        this.title = '【编辑】'

        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

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

              loading.close()
              this.imgList = []
              for (var i = 0; i < resp.data.purchaseAppendixList.length; i++) {
                this.imgList.push({
                  url: resp.data.purchaseAppendixList[i].url
                })
              }

            }
          })
          .catch(e => {
            loading.close()
            this.formobj = {}
          })
      },

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

      },
      selectWarehouseName(val) {

        console.log("selectWarehouseName", val);
        const choose = this.warehouseList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>selectWarehouseName', choose)
        this.formobj.wareHouseName = choose[0].warehouseName
        this.formobj.wareHouseSid = choose[0].sid


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

        const choose = this.allOrgperList.filter((item) => item.sid == val)
        console.log('>>>>>>>>>allOrgperSelect', choose)
        this.formobj.purchaserName = choose[0].name
        this.formobj.purchaserSid = choose[0].sid

      },
      selectCurrency(val) {
        const choose = this.currencyTypeList.filter((item) => item.dictKey == val)
        console.log('>>>>>>>>>selectCurrency', choose)
        this.formobj.purchaseBillAmount.currencyValue = choose[0].dictValue
        this.formobj.purchaseBillAmount.currencyKey = choose[0].dictKey

      },
      selectFreightShareType(val) {
        const choose = this.shareTypeList.filter((item) => item.dictKey == val)
        console.log('>>>>>>>>>selectFreightShareType', choose)
        this.formobj.purchaseBillAmount.freightShareTypeValue = choose[0].dictValue
        this.formobj.purchaseBillAmount.freightShareTypeKey = choose[0].dictKey
      },
      selectSettleAccount(val) {
        const choose = this.settlementList.filter((item) => item.dictKey == val)
        console.log('>>>>>>>>>selectSettleAccount', choose)
        this.formobj.purchaseBillAmount.settleAccountValue = choose[0].dictValue
        this.formobj.purchaseBillAmount.settleAccountKey = choose[0].dictKey
      },
      selectOtherShareType(val) {
        const choose = this.shareTypeList.filter((item) => item.dictKey == val)
        console.log('>>>>>>>>>selectOtherShareType', choose)
        this.formobj.purchaseBillAmount.otherShareTypeValue = choose[0].dictValue
        this.formobj.purchaseBillAmount.otherShareTypeKey = choose[0].dictKey
      }
    }
  }
</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;
  }
</style>
