<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="handleSave()">保存</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="handleSubmit()">提交</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="handleSubmitAndAdd()">提交并新增</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="handleReset()">重置</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">
          <el-row style="border-top: 1px solid #e0e3eb">
            <el-col :span="6">
              <el-form-item>
                <div style="text-align: right">
                  <el-radio-group v-model="formobj.billTypeValue" size="small">
                    <el-radio-button label="线下订单"></el-radio-button>
                    <el-radio-button label="预售订单"></el-radio-button>
                  </el-radio-group>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">下单时间</div>
              <el-form-item><el-date-picker class="addinputInfo" v-model="formobj.createTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期" /></el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">订单号</div>
              <el-form-item><span class="addinputInfo">{{ formobj.billNo }}</span></el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">店铺名称</div>
              <el-form-item>
                <el-select class="addinputInfo" v-model="formobj.shopName" placeholder="请选择" clearable filterable>
                  <el-option v-for="item in shop_list" :key="item.sid" :label="item.name" :value="item.name"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <div class="span-sty">仓库</div>
              <el-form-item>
                <el-select class="addinputInfo" v-model="formobj.warehouseSid" placeholder="请选择" @change="warehouseChange" clearable filterable>
                  <el-option v-for="item in warehouse_list" :key="item.warehouseSid" :label="item.warehouseName" :value="item.warehouseSid"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">配送方式</div>
              <el-form-item>
                <el-select class="addinputInfo" v-model="formobj.deliveryTypeKey" placeholder="请选择" @change="deliveryTypeChange" clearable filterable>
                  <el-option v-for="item in deliveryType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">快递公司</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.logisticsName" clearable placeholder="" /></el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">业务员</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.salesName" clearable placeholder="" /></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <div class="span-sty">客户</div>
              <el-form-item>
                <div class="addinputInfo" style="display: flex;flex-direction: row;justify-content: space-between;align-items: center">
                  <div>
                    <span>{{ formobj.customerName }}</span>
                  </div>
                  <div style="text-align: right">
                    <el-button type="primary" size="mini" @click="chooseCustomer">选择</el-button>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">收货人</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.shipperName" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">手机号</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.shipperMob" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">固话</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.phone" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div class="span-sty">详细地址</div>
              <el-form-item>
                <div class="addinputInfo" style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center">
                  <el-select v-model="formobj.deliveryProvince" filterable clearable placeholder="请选择省" style="width:120px" @change="provinceChange">
                    <el-option v-for="item in province_list" :key="item.sid" :label="item.name" :value="item.name"/>
                  </el-select>
                  <el-select v-model="formobj.deliveryCity" filterable placeholder="请选择市" style="width:120px" @change="cityChange">
                    <el-option v-for="item in city_list" :key="item.sid" :label="item.name" :value="item.name"/>
                  </el-select>
                  <el-select v-model="formobj.deliveryCounty" filterable placeholder="请选择县" style="width:120px" @change="countyChange">
                    <el-option v-for="item in county_list" :key="item.sid" :label="item.name" :value="item.name"/>
                  </el-select>
                  <el-input style="width: 40%" v-model="formobj.deliveryAddress" clearable placeholder=""/>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">货到付款</div>
              <el-form-item>
                <el-radio-group class="addinputInfo" v-model="formobj.isFirstPay">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">备注</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.remarks" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">附件</div>
              <el-form-item>
                <uploadImg ref="uploadImg" class="addinputInfo" v-model="formobj.files" :limit="50" bucket="map" :upload-data="{ type: '0001' }"/>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="title titleOne">
            <div>商品</div>
            <div>
              <span style="margin-right: 5px">开单价格</span>
              <el-select size="mini" v-model="formobj.billPriceTypeKey" placeholder="请选择" @change="billPriceTypeChange" clearable filterable>
                <el-option v-for="item in billPriceType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
              </el-select>
              <el-button style="margin-left: 10px" type="primary" class="btntopblueline" size="small" @click="chooseCommodity">选择商品</el-button>
            </div>
          </div>
          <el-table :key="commodityKey" :data="formobj.goodsList" :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 label="操作" align="center" width="80">
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="commodityDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="goodsSpuName" label="商品名称"  align="center" min-width="200" />
            <el-table-column prop="goodsSkuOwnSpec" label="规格" align="center" min-width="200" />
            <el-table-column prop="unit" label="单位" align="center" width="100" />
            <el-table-column prop="count" label="数量" align="center" min-width="150">
              <template slot-scope="scope">
                <el-input @input="dueAmountInput(scope.row)" @keyup.native="scope.row.count = getNumber(scope.row.count, 0)" v-model="scope.row.count" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column prop="batchNumber" label="批次号" align="center" min-width="150" />
            <el-table-column prop="price" label="单价" align="center" min-width="150" />
            <el-table-column label="税率(%)" align="center" min-width="150">
              <template slot-scope="scope">
                <el-input @input="taxAmountInput(scope.row)" @keyup.native="scope.row.taxRate = getNumber(scope.row.taxRate, 2)" v-model="scope.row.taxRate" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column prop="taxAmount" label="税额" align="center" min-width="150" />
            <el-table-column prop="dueAmount" label="应收款" align="center" min-width="150" />
            <el-table-column prop="cost" label="商品成本" align="center" min-width="150">
              <template slot-scope="scope">
                <el-input @keyup.native="scope.row.cost = getNumber(scope.row.cost, 2)" v-model="scope.row.cost" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" min-width="300">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column prop="goodsSkuCode" label="商品编码" width="100" align="center" min-width="150" />
            <el-table-column label="折扣率(%)" align="center" min-width="150">
              <template slot-scope="scope">
                <el-input @input="discountPriceInput(scope.row)" @keyup.native="scope.row.discountRtate = getNumber(scope.row.discountRtate, 2)" v-model="scope.row.discountRtate" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column label="辅单位数量" align="center" min-width="150">
              <template slot-scope="scope">
                <el-input @keyup.native="scope.row.auxiliaryUnit = getNumber(scope.row.auxiliaryUnit, 2)" v-model="scope.row.auxiliaryUnit" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column prop="discountPrice" label="折后单价" align="center" min-width="150" />
            <el-table-column prop="discountAmount" label="分摊优惠" align="center" min-width="150" />
            <el-table-column prop="amount" label="惠后金额" align="center" min-width="150" />
            <el-table-column prop="weight" label="重量" align="center" min-width="150" />
            <el-table-column prop="taxTotalAmount" label="未含税总额" align="center"  min-width="150"/>
            <el-table-column prop="unTaxPrice" label="未含税价" align="center" min-width="150" />
          </el-table>
          <el-row class="rowStyle">
            <el-col :span="4">
              <div class="span-sty">折扣率(%):</div>
              <el-form-item><el-input class="addinputInfo addinputw" @input="discountRateInput()" @keyup.native="formobj.discountRate = getNumber(formobj.discountRate , 2)" v-model="formobj.discountRate" clearable placeholder="" /></el-form-item>
            </el-col>
            <el-col :span="4">
              <div class="span-sty">优惠金额:</div>
              <el-form-item><el-input class="addinputInfo addinputw" @input="discountAmountInput()" @keyup.native="formobj.discountAmount = getNumber(formobj.discountAmount , 2)" v-model="formobj.discountAmount" clearable placeholder="" /></el-form-item>
            </el-col>
            <el-col :span="4">
              <div class="span-sty">优惠后金额:</div>
              <el-form-item><span class="addinputInfo">{{ yhhCompute }}</span></el-form-item>
            </el-col>
            <el-col :span="4">
              <div class="span-sty">应收合计:</div>
              <el-form-item><span class="addinputInfo">{{ yhhCompute }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">运费:</div>
              <el-form-item><el-input class="addinputInfo addinputw" @keyup.native="formobj.freight = getNumber(formobj.freight , 2)" v-model="formobj.freight" clearable placeholder="" /></el-form-item>
            </el-col>
          </el-row>
          <el-row class="rowStyle">
            <el-col :span="4">
              <div class="span-sty">本次收款</div>
              <el-form-item><el-input class="addinputInfo addinputw" @keyup.native="formobj.thisPay = getNumber(formobj.thisPay , 2)" v-model="formobj.thisPay" clearable placeholder="" /></el-form-item>
            </el-col>
            <el-col :span="4">
              <div class="span-sty">本次欠款</div>
              <el-form-item><span class="addinputInfo">{{ bcqkCompute }}</span></el-form-item>
            </el-col>
            <el-col :span="4">
              <div class="span-sty">总欠款</div>
              <el-form-item><el-input class="addinputInfo addinputw" disabled @keyup.native="formobj.totalDebt = getNumber(formobj.totalDebt , 2)" v-model="formobj.totalDebt" clearable placeholder="" /></el-form-item>
            </el-col>
            <el-col :span="4">
              <div class="span-sty">预收款余额</div>
              <el-form-item><el-input class="addinputInfo addinputw" disabled @keyup.native="formobj.advanceBalance = getNumber(formobj.advanceBalance , 2)" v-model="formobj.advanceBalance" clearable placeholder="" /></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">结算账户</div>
              <el-form-item>
                <el-select class="addinputInfo" style="width: 25%" v-model="formobj.bankAccountKey" placeholder="请选择" @change="bankAccountChange" clearable filterable>
                  <el-option v-for="item in bankAccount_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
                </el-select>
                <el-button type="primary" size="mini" @click="handleAccount">多账户</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!-- 选择商品 -->
    <el-dialog title="选择商品" :visible.sync="commodityVisible" width="70%" :show-close="false">
      <div>
        <el-form ref="multipleTable" :inline="true" :model="commodityQuery" class="vinNoForm" label-width="100px">
          <el-form-item label="商品名称">
            <el-input v-model="commodityQuery.params.goodsName" clearable style="width: 150px;" placeholder=""/>
          </el-form-item>
          <el-form-item label="商品编码">
            <el-input v-model="commodityQuery.params.goodsSkuCode" clearable style="width: 150px;" placeholder=""/>
          </el-form-item>
          <el-form-item label="规格">
            <el-input v-model="commodityQuery.params.goodsSkuOwnSpec" clearable style="width: 150px;" placeholder=""/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="selectCommodity">查询</el-button>
            <el-button type="primary" size="small" @click="resetCommodity">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :key="commodityKey" v-loading="commodityLoading" :data="commodityData" border fit highlight-current-row style="width: 100%;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" width="50"/>
        <el-table-column :index="commodityMethod" align="center" label="序号" type="index" width="80"/>
        <el-table-column prop="goodsSkuCode" label="商品编码" align="center" width="120" />
        <el-table-column prop="goodsSpuName" label="商品名称" align="center" min-width="120" />
        <el-table-column prop="goodsSkuOwnSpec" label="规格" align="center" width="100" />
        <el-table-column prop="price" label="标准售价" align="center" width="120"/>
        <el-table-column prop="standardPurchasePrice" label="参考进价" align="center" width="120" />
        <el-table-column prop="weight" label="重量" align="center" width="100" />
        <el-table-column prop="costPrice" label="成本均价" align="center" width="120" />
        <el-table-column prop="inventoryCount" label="实际可用库存" align="center" width="160"/>
      </el-table>
      <div class="pages">
        <div class="tit"/>
        <!-- 翻页 -->
        <pagination v-show="commodityData.length > 0" :limit.sync="commodityQuery.size" :page.sync="commodityQuery.current" :total="commodityQuery.total" class="pagination" @pagination="commodityList"/>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" size="small" @click="commodityConfirm">确定</el-button>
        <el-button size="small" @click="commodityVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 选择客户 -->
    <el-dialog title="选择客户" :visible.sync="customerVisible" width="70%">
      <div>
        <el-form ref="multipleTable" :inline="true" :model="customerQuery" class="vinNoForm" label-width="100px">
          <el-form-item label="客户名称">
            <el-input v-model="customerQuery.params.name" clearable style="width: 150px;" placeholder=""/>
          </el-form-item>
          <el-form-item label="客户编码">
            <el-input v-model="customerQuery.params.customerNo" clearable style="width: 150px;" placeholder=""/>
          </el-form-item>
          <el-form-item label="手机">
            <el-input v-model="customerQuery.params.mobile" clearable style="width: 150px;" placeholder=""/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="selectCustomer">查询</el-button>
            <el-button type="primary" size="small" @click="resetCustomer">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :key="customerKey" v-loading="customerLoading" :data="customerData" border fit highlight-current-row style="width: 100%;">
        <el-table-column :index="customerMethod" align="center" label="序号" type="index" width="80"/>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="customerConfirm(scope.row)">确认</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="customerNo" label="客户编码" align="center" width="120" />
        <el-table-column prop="name" label="客户名称" align="center" min-width="120" />
        <el-table-column prop="originalPlat" label="平台" align="center" width="100" />
        <el-table-column prop="buyserNickname" label="昵称" align="center" width="120"/>
        <el-table-column prop="province" label="省" align="center" width="100" />
        <el-table-column prop="city" label="市" align="center" width="100" />
        <el-table-column prop="county" label="区" align="center" width="100" />
        <el-table-column prop="address" label="地址" align="center" min-width="160"/>
        <el-table-column prop="phone" label="固话" align="center" width="120"/>
        <el-table-column prop="mobile" label="手机" align="center" width="120"/>
      </el-table>
      <div class="pages">
        <div class="tit"/>
        <!-- 翻页 -->
        <pagination v-show="customerData.length > 0" :limit.sync="customerQuery.size" :page.sync="customerQuery.current" :total="customerQuery.total" class="pagination" @pagination="customerList"/>
      </div>
    </el-dialog>
    <!-- 多账户 -->
    <el-dialog title="多账户选择" :visible.sync="dialogVisible" width="40%" :show-close="false">
      <el-form class="formaddcopy02">
        <el-table :key="accountKey" :data="formobj.accounts" :index="index" border style="width: 100%">
          <el-table-column fixed width="60" label="序号" type="index" :index="index + 1" align="center" />
          <el-table-column prop="bankAccount" label="收支账户" align="center" min-width="150" />
          <el-table-column label="金额" align="center" min-width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.amount" clearable placeholder="" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" size="small" @click="handleConfirm">确定</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import req from '@/api/sales/salesOrder'
import Pagination from '@/components/pagination'
import uploadImg from '@/components/uploadFile/uploadImg'
import { getProvince, getCity, getCounty, typeValues, getWareHouse, chooseCustomerList } from '@/api/Common/dictcommons'

export default {
  name: 'SalesOrderAdd',
  components: {
    Pagination,
    uploadImg
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      submitdisabled: false,
      shop_list: [], // 店铺名称
      warehouse_list: [], // 仓库
      deliveryType_list: [], // 配送方式
      province_list: [],
      city_list: [],
      county_list: [],
      billPriceType_list: [], // 开票价格
      bankAccount_list: [], // 结算账户
      // commodity商品
      commodityVisible: false,
      commodityKey: 1,
      commodityLoading: false,
      commodityQuery: {
        current: 1,
        size: 5,
        total: 0,
        params: {
          goodsName: '',
          goodsSkuCode: '',
          goodsSkuOwnSpec: '',
          createOrgSid: ''
        }
      },
      dataList: [],
      commodityData: [],
      // customer客户
      customerVisible: false,
      customerKey: 1,
      customerLoading: false,
      customerQuery: {
        current: 1,
        size: 5,
        total: 0,
        params: {
          createOrgSid: '',
          mobile: '',
          name: '',
          customerNo: ''
        }
      },
      customerData: [],
      // 多账户
      dialogVisible: false,
      accountKey: 2,
      index: 0,
      formobj: {
        sid: '',
        billNo: '',
        shopName: '',
        shopSid: '',
        createBySid: '',
        createByName: '',
        useOrgSid: '',
        createOrgSid: '',
        remarks: '',
        deptSid: '',
        deptName: '',
        createTime: '',
        billTypeKey: '',
        billTypeValue: '',
        warehouseSid: '',
        warehouseName: '',
        deliveryTypeKey: '',
        deliveryTypeValue: '',
        logisticsName: '',
        logisticsNameSid: '',
        salesUserSid: '',
        salesName: '',
        isFirstPay: '',
        billPriceTypeKey: '',
        billPriceTypeValue: '',
        customerSid: '',
        customerName: '',
        shipperName: '',
        shipperSid: '',
        shipperMob: '',
        phone: '',
        deliveryProvinceSid: '',
        deliveryProvince: '',
        deliveryCitySid: '',
        deliveryCity: '',
        deliveryCountySid: '',
        deliveryCounty: '',
        deliveryAddress: '',
        postCode: '',
        isInvoicing: '',
        invoiceTypeKey: '',
        invoiceType: '',
        invoiceTitle: '',
        taxpayerNo: '',
        taxRate: '',
        discountRate: '',
        coupon: '',
        discountAmount: '',
        amount: '',
        dueAmount: '',
        freight: '',
        thisPay: '',
        thisDebt: '',
        totalDebt: '',
        advanceBalance: '',
        bankAccount: '',
        bankAccountKey: '',
        settleAmount: '',
        goodsList: [],
        files: [],
        accounts: []
      },
      totalReceivables: '', // 商品列表中应收款总和
      rules: {}
    }
  },
  computed: {
    // 计算优惠后金额 = 商品列表中所有应收款之和 - 优惠金额
    yhhCompute() {
      let yhh = '0'
      if (this.formobj.goodsList.length > 0) {
        this.formobj.goodsList.forEach((e) => {
          if (e.goodsSpuName !== '') {
            yhh = parseFloat(yhh) + parseFloat(e.dueAmount !== '' ? e.dueAmount : '0')
          }
        })
      }
      yhh = Math.round((parseFloat(yhh) - parseFloat(this.formobj.discountAmount !== '' ? this.formobj.discountAmount : '0')) * 100) / 100
      return yhh
    },
    // 计算本次欠款 = 应收合计（优惠后金额） + 运费 - 本次收款
    bcqkCompute() {
      let bcqk = '0'
      bcqk = Math.round((parseFloat(this.yhhCompute) + parseFloat(this.formobj.freight !== '' ? this.formobj.freight : '0') - parseFloat(this.formobj.thisPay !== '' ? this.formobj.thisPay : '0')) * 100) / 100
      return bcqk
    }
  },
  methods: {
    init() {
      typeValues({ type: 'deliveryType' }).then((res) => {
        if (res.success) {
          this.deliveryType_list = res.data
        }
      })
      typeValues({ type: 'billPriceType' }).then((res) => {
        if (res.success) {
          this.billPriceType_list = res.data
        }
      })
      typeValues({ type: 'settlementAccount' }).then((res) => {
        if (res.success) {
          this.bankAccount_list = res.data
        }
      })
      getProvince().then((res) => {
        if (res.success) {
          this.province_list = res.data
        }
      })
      getWareHouse({ createOrgSid: window.sessionStorage.getItem('orgSid') }).then((res) => {
        if (res.success) {
          this.warehouse_list = res.data
        }
      })
    },
    getNumber(val, limit) {
      val = val.replace(/[^0-9.]/g, '') // 保留数字
      val = val.replace(/^00/, '0.') // 开头不能有两个0
      val = val.replace(/^\./g, '0.') // 开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') // 两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); // 只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' // 两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    },
    provinceChange(value) {
      const choose = this.province_list.filter((item) => item.name === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.deliveryProvinceSid = choose[0].sid
        this.getCity(this.formobj.deliveryProvinceSid)
      } else {
        this.formobj.deliveryProvinceSid = ''
        this.formobj.deliveryCitySid = ''
        this.formobj.deliveryCity = ''
        this.city_list = []
        this.formobj.deliveryCounty = ''
        this.formobj.deliveryCountySid = ''
        this.county_list = []
      }
    },
    getCity(val) {
      getCity({ sid: val }).then((res) => {
        if (res.success) {
          this.city_list = res.data
        }
      })
    },
    cityChange(value) {
      const choose = this.city_list.filter((item) => item.name === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.deliveryCitySid = choose[0].sid
        this.getCounty(this.formobj.deliveryCitySid)
      }
    },
    getCounty(val) {
      getCounty({ sid: val }).then((res) => {
        if (res.success) {
          this.county_list = res.data
        }
      })
    },
    countyChange(value) {
      const choose = this.county_list.filter((item) => item.name === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.deliveryCountySid = choose[0].sid
      }
    },
    showAdd() {
      this.viewTitle = '【新增】商品销售单'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      this.formobj.createByName = window.sessionStorage.getItem('name')
      this.formobj.createBySid = window.sessionStorage.getItem('userSid')
      this.formobj.createOrgSid = window.sessionStorage.getItem('orgSid')
      this.formobj.useOrgSid = window.sessionStorage.getItem('orgSid')
      var nowDate = new Date()
      var date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        day: nowDate.getDate()
      }
      this.formobj.createTime = date.year + '-' + (date.month >= 10 ? date.month : '0' + date.month) + '-' + (date.day >= 10 ? date.day : '0' + date.day)
      this.formobj.discountRate = '100'
    },
    showEdit(row) {
      this.viewTitle = '【编辑】商品销售单'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      req.fetchBySid(row.sid).then((res) => {
        if (res.success) {
          this.formobj = res.data
        }
      })
    },
    warehouseChange(value) {
      const choose = this.warehouse_list.filter((item) => item.warehouseSid === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.warehouseName = choose[0].warehouseName
      } else {
        this.formobj.warehouseName = ''
      }
    },
    deliveryTypeChange(value) {
      const choose = this.deliveryType_list.filter((item) => item.dictKey === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.deliveryTypeValue = choose[0].dictValue
      } else {
        this.formobj.deliveryTypeValue = ''
      }
    },
    billPriceTypeChange(value) {
      const choose = this.billPriceType_list.filter((item) => item.dictKey === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.billPriceTypeValue = choose[0].dictValue
      } else {
        this.formobj.billPriceTypeValue = ''
      }
    },
    bankAccountChange(value) {
      const choose = this.bankAccount_list.filter((item) => item.dictKey === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.bankAccount = choose[0].dictValue
        this.formobj.accounts = []
      } else {
        this.formobj.bankAccount = ''
        this.formobj.accounts = []
      }
    },
    // 选择客户
    chooseCustomer() {
      this.customerVisible = true
      this.resetCustomer()
    },
    customerMethod(index) {
      var pagestart = (this.customerQuery.current - 1) * this.customerQuery.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    selectCustomer() {
      this.customerQuery.current = 1
      this.customerList()
    },
    customerList() {
      this.customerLoading = true
      this.customerQuery.params.createOrgSid = window.sessionStorage.getItem('orgSid')
      chooseCustomerList(this.customerQuery).then((response) => {
        this.customerLoading = false
        if (response.success) {
          this.customerData = response.data.records
          this.customerQuery.total = response.data.total
        } else {
          this.customerData = []
          this.customerQuery.total = 0
        }
      })
    },
    resetCustomer() {
      this.customerQuery = {
        current: 1,
        size: 5,
        total: 0,
        params: {
          createOrgSid: '',
          mobile: '',
          name: '',
          customerNo: ''
        }
      }
      this.customerList()
    },
    customerConfirm(row) {
      this.customerVisible = false
      this.formobj.customerName = row.name
      this.formobj.customerSid = row.sid
    },
    // 选择商品
    chooseCommodity() {
      this.commodityVisible = true
      this.resetCommodity()
    },
    commodityMethod(index) {
      var pagestart = (this.commodityQuery.current - 1) * this.commodityQuery.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    selectCommodity() {
      this.commodityQuery.current = 1
      this.commodityList()
    },
    commodityList() {
      this.commodityLoading = true
      this.commodityQuery.params.createOrgSid = window.sessionStorage.getItem('orgSid')
      req.chooseProducts(this.commodityQuery).then((response) => {
        this.commodityLoading = false
        if (response.success) {
          this.commodityData = response.data.records
          this.commodityQuery.total = response.data.total
        } else {
          this.commodityData = []
          this.commodityQuery.total = 0
        }
      })
    },
    resetCommodity() {
      this.commodityQuery = {
        current: 1,
        size: 5,
        total: 0,
        params: {
          goodsName: '',
          goodsSkuCode: '',
          goodsSkuOwnSpec: '',
          createOrgSid: ''
        }
      }
      this.commodityList()
    },
    // 信息条数 获取点击时当前的sid
    handleSelectionChange(row) {
      this.dataList = row
    },
    commodityConfirm() {
      if (this.dataList.length > 0) {
        this.commodityVisible = false
        this.dataList.forEach((e) => {
          this.formobj.goodsList.push({
            goodSpuSid: e.goodSpuSid,
            goodsSpuName: e.goodsSpuName,
            goodsSkuSid: e.goodsSkuSid,
            goodsSkuTitle: e.goodsSkuTitle,
            goodsSkuCode: e.goodsSkuCode,
            goodsSkuOwnSpec: e.goodsSkuOwnSpec,
            weight: e.weight,
            volume: e.volume,
            unit: e.unit,
            auxiliaryUnit: e.auxiliaryUnit,
            price: e.price,
            count: '1',
            discountRtate: '100',
            discountPrice: e.price,
            dueAmount: e.price,
            cost: '',
            discountAmount: '0',
            amount: e.price,
            inventoryCount: '',
            remarks: '',
            batchNumber: '',
            taxRate: '',
            taxAmount: '',
            taxTotalAmount: '',
            unTaxPrice: '',
            pic: e.pic
          })
        })
      } else {
        this.$message({ showClose: true, type: 'error', message: '请至少选择一条记录进行操作' })
      }
    },
    commodityDelete(index) {
      this.formobj.goodsList.splice(index, 1)
    },
    // 合计
    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 === 'dueAmount') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
          this.totalReceivables = sums[index] += ''
        } else 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 === 'cost') {
          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 === 'discountAmount') {
          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
    },
    // 修改折扣率时
    discountRateInput() {
      if (this.formobj.goodsList.length > 0) {
        // 重新计算底部的优惠金额 = 总应收合计 * (1 - 折扣率)
        this.formobj.discountAmount = Math.round((parseFloat(this.totalReceivables !== '' ? this.totalReceivables : '0') * (parseFloat(1) - parseFloat(this.formobj.discountRate !== '' ? this.formobj.discountRate : '0') / 100)) * 100) / 100
        // 需计算商品列表中各商品的分摊优惠、惠后金额
        this.formobj.goodsList.forEach((e) => {
          // 分摊优惠 = 底部优惠金额  * 对应的应收 / 总应收合计
          e.discountAmount = Math.round((parseFloat(this.formobj.discountAmount) * parseFloat(e.dueAmount !== '' ? e.dueAmount : '0') / parseFloat(this.totalReceivables !== '' ? this.totalReceivables : '0')) * 100) / 100
          // 惠后金额 = 对应的应收 - 对应的分摊优惠
          e.amount = Math.round((parseFloat(e.dueAmount !== '' ? e.dueAmount : '0') - parseFloat(e.discountAmount !== '' ? e.discountAmount : '0')) * 100) / 100
        })
      }
    },
    // 修改优惠金额时
    discountAmountInput() {
      if (this.formobj.goodsList.length > 0) {
        // 重新计算折扣率 = (总应收合计 - 优惠金额) / 总应收合计
        this.formobj.discountRate = Math.round((((parseFloat(this.totalReceivables !== '' ? this.totalReceivables : '0') - parseFloat(this.formobj.discountAmount !== '' ? this.formobj.discountAmount : '0')) / parseFloat(this.totalReceivables !== '' ? this.totalReceivables : '0')) * 100).toFixed(2) * 100) / 100
        // 需计算商品列表中各商品的分摊优惠、惠后金额
        this.formobj.goodsList.forEach((e) => {
          // 分摊优惠 = 底部优惠金额  * 对应的应收 / 总应收合计
          e.discountAmount = Math.round((parseFloat(this.formobj.discountAmount) * parseFloat(e.dueAmount !== '' ? e.dueAmount : '0') / parseFloat(this.totalReceivables !== '' ? this.totalReceivables : '0')) * 100) / 100
          // 惠后金额 = 对应的应收 - 对应的分摊优惠
          e.amount = Math.round((parseFloat(e.dueAmount !== '' ? e.dueAmount : '0') - parseFloat(e.discountAmount !== '' ? e.discountAmount : '0')) * 100) / 100
        })
      }
    },
    // 计算折后单价 = 单价 * 折扣率
    discountPriceInput(row) {
      row.discountPrice = Math.round((parseFloat(row.price !== '' ? row.price : '0') * parseFloat(row.discountRtate !== '' ? row.discountRtate : '0') / 100) * 100) / 100
      this.dueAmountInput(row)
    },
    // 计算应收款， 同时计算惠后金额
    dueAmountInput(row) {
      // 应收款 = 折后单价 * 数量
      row.dueAmount = Math.round((parseFloat(row.discountPrice !== '' ? row.discountPrice : '0') * parseFloat(row.count !== '' ? row.count : '0')) * 100) / 100
      // 惠后金额 = 应收款 - 分摊金额
      row.amount = Math.round((parseFloat(row.dueAmount) - parseFloat(row.discountAmount)) * 100) / 100
    },
    // 计算税额。同时计算未含税价及未含税总额
    taxAmountInput(row) {
      // 计算税额 = (单价 - (单价 / (1 + 税率))) * 数量
      row.taxAmount = Math.round(((parseFloat(row.price) - (parseFloat(row.price) / (parseFloat(1) + parseFloat(row.taxRate !== '' ? row.taxRate : '0') / 100))) * parseFloat(row.count !== '' ? row.count : '0')) * 100) / 100
      // 计算未含税价 = 单价 - 税额
      row.unTaxPrice = Math.round((parseFloat(row.price) - parseFloat(row.taxAmount)) * 100) / 100
      // 计算未含税总额 = 未含税价 * 数量
      row.taxTotalAmount = Math.round((parseFloat(row.unTaxPrice) * parseFloat(row.count !== '' ? row.count : '0')) * 100) / 100
    },
    handleAccount() {
      this.formobj.bankAccount = ''
      this.formobj.bankAccountKey = ''
      this.dialogVisible = true
      const aa = []
      if (this.bankAccount_list.length > 0) {
        this.bankAccount_list.forEach((e) => {
          aa.push({
            bankAccount: e.dictValue,
            bankAccountKey: e.dictKey,
            amount: ''
          })
        })
      }
      this.formobj.accounts = aa
    },
    handleConfirm() {
      this.dialogVisible = false
    },
    handleSave() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.formobj.amount = this.yhhCompute
          this.formobj.dueAmount = this.yhhCompute
          this.formobj.thisDebt = this.bcqkCompute
          if (this.formobj.billTypeValue === '线下订单') {
            this.formobj.billTypeKey = '001'
          } else if (this.formobj.billTypeValue === '预售订单') {
            this.formobj.billTypeKey = '002'
          }
          this.submitdisabled = true
          req.saveOrUpdate(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '保存成功' })
              this.handlePartReset()
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    handleSubmit() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.formobj.amount = this.yhhCompute
          this.formobj.dueAmount = this.yhhCompute
          this.formobj.thisDebt = this.bcqkCompute
          if (this.formobj.billTypeValue === '线下订单') {
            this.formobj.billTypeKey = '001'
          } else if (this.formobj.billTypeValue === '预售订单') {
            this.formobj.billTypeKey = '002'
          }
          this.submitdisabled = true
          req.submit(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '保存成功' })
              this.handlePartReset()
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    handleSubmitAndAdd() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.formobj.amount = this.yhhCompute
          this.formobj.dueAmount = this.yhhCompute
          this.formobj.thisDebt = this.bcqkCompute
          if (this.formobj.billTypeValue === '线下订单') {
            this.formobj.billTypeKey = '001'
          } else if (this.formobj.billTypeValue === '预售订单') {
            this.formobj.billTypeKey = '002'
          }
          this.submitdisabled = true
          req.submit(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '保存成功' })
              this.handlePartReset()
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    handlePartReset() {
      this.formobj.freight = ''
      this.formobj.thisPay = ''
      this.formobj.billPriceTypeKey = ''
      this.formobj.billPriceTypeValue = ''
      this.formobj.bankAccountKey = ''
      this.formobj.bankAccount = ''
      this.formobj.amount = ''
      this.formobj.dueAmount = ''
      this.formobj.thisDebt = ''
      this.formobj.goodsList = []
      this.totalReceivables = ''
      this.commodityData = []
      this.formobj.accounts = []
      this.submitdisabled = false
    },
    // 重置页面参数（点击保存或重置时调用）
    handleReset() {
      this.formobj = {
        sid: '',
        billNo: '',
        shopName: '',
        shopSid: '',
        createBySid: '',
        createByName: '',
        useOrgSid: '',
        createOrgSid: '',
        remarks: '',
        deptSid: '',
        deptName: '',
        createTime: '',
        billTypeKey: '',
        billTypeValue: '',
        warehouseSid: '',
        warehouseName: '',
        deliveryTypeKey: '',
        deliveryTypeValue: '',
        logisticsName: '',
        logisticsNameSid: '',
        salesUserSid: '',
        salesName: '',
        isFirstPay: '',
        billPriceTypeKey: '',
        billPriceTypeValue: '',
        customerSid: '',
        customerName: '',
        shipperName: '',
        shipperSid: '',
        shipperMob: '',
        phone: '',
        deliveryProvinceSid: '',
        deliveryProvince: '',
        deliveryCitySid: '',
        deliveryCity: '',
        deliveryCountySid: '',
        deliveryCounty: '',
        deliveryAddress: '',
        postCode: '',
        isInvoicing: '',
        invoiceTypeKey: '',
        invoiceType: '',
        invoiceTitle: '',
        taxpayerNo: '',
        taxRate: '',
        discountRate: '',
        coupon: '',
        discountAmount: '',
        amount: '',
        dueAmount: '',
        freight: '',
        thisPay: '',
        thisDebt: '',
        totalDebt: '',
        advanceBalance: '',
        bankAccount: '',
        bankAccountKey: '',
        settleAmount: '',
        goodsList: [],
        files: [],
        accounts: []
      }
      this.totalReceivables = ''
      this.commodityData = []
      this.submitdisabled = false
    },
    handleReturn() {
      this.$emit('doback')
    }
  }
}
</script>

<style scoped>
.span-sty {
  width: 130px !important;
}
.addinputInfo {
  margin-left: 120px !important;
}
.titleOne {
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
/deep/ .el-form-item__error {
  margin-left: 120px !important;
}
.formaddcopy02 .el-row .el-col /deep/ .el-form-item .addinputw {
  margin-left: 120px !important;
  width: calc(100% - 115px);
}
.formaddcopy02 .el-row .el-col /deep/ .el-form-item .el-radio-group {
  display: inline;
  line-height: 1px;
  vertical-align: middle;
}
.rowStyle {
  border: 0;
}
.rowStyle .el-col {
  border-right: 0;
  border-bottom: 0;
}
.rowStyle .el-col .span-sty {
  border-right: 0;
}
</style>
