<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="selectCustomer()">选择客户</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate()">保存</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="settleAccounts()">结算</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="print()">打印</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="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><span class="addinputInfo">{{ formobj.createTime }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>销售人员</div>
              <el-form-item prop="salesName">
                <el-select class="addinputInfo" v-model="formobj.salesName" placeholder="请选择" @change="waitorChange" clearable filterable>
                  <el-option v-for="item in user_list" :key="item.sid" :label="item.name" :value="item.name"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">备注(打印)</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.printRemarks" clearable placeholder="" /></el-form-item>
            </el-col>
            <el-col :span="8">
              <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-collapse v-model="activeNames">
            <el-collapse-item title="客户信息" name="1">
              <el-row style="border-top: 1px solid #e0e3eb">
                <el-col :span="8">
                  <div class="span-sty"><span class="icon">*</span>客户</div>
                  <el-form-item prop="customerName"><span class="addinputInfo">{{ formobj.customerName }}</span></el-form-item>
                </el-col>
                <el-col :span="8">
                  <div class="span-sty">联系电话</div>
                  <el-form-item><span class="addinputInfo">{{ formobj.mobile }}</span></el-form-item>
                </el-col>
                <el-col :span="8">
                  <div class="span-sty">车牌号/车架号</div>
                  <el-form-item><span class="addinputInfo">{{ formobj.vehMark }}/{{ formobj.vinNo }}</span></el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
            <el-collapse-item title="发票信息" name="2">
              <el-row style="border-top: 1px solid #e0e3eb">
                <el-col :span="8">
                  <div class="span-sty">是否开发票</div>
                  <el-form-item>
                    <el-radio-group class="addinputInfo" v-model="formobj.invoiceVo.isInvoicing" @change="isInvoicingChange">
                      <el-radio label="1">是</el-radio>
                      <el-radio label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <div class="span-sty">开票类型</div>
                  <el-form-item>
                    <el-select class="addinputInfo" :disabled="formobj.invoiceVo.isInvoicing != '1'" v-model="formobj.invoiceVo.invoiceType" placeholder="请选择" @change="invoiceTypeChange" clearable filterable>
                      <el-option v-for="item in invoiceType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <div class="span-sty">税率(%)</div>
                  <el-form-item><el-input class="addinputInfo addinputw" @input="taxRateInput" :disabled="formobj.invoiceVo.isInvoicing != '1'" @keyup.native="formobj.invoiceVo.taxRate = getNumber(formobj.invoiceVo.taxRate, 2)" v-model="formobj.invoiceVo.taxRate" clearable placeholder="" /></el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div class="span-sty">开票单位</div>
                  <el-form-item>
                    <el-select class="addinputInfo" :disabled="formobj.invoiceVo.isInvoicing != '1'" v-model="formobj.invoiceVo.invoiceTitleSid" placeholder="请选择" @change="changeCompanyInvoicing" clearable>
                      <el-option v-for="item in companyInvoicing_list" :key="item.companyInvoicingSid" :label="item.companyInvoicingName" :value="item.companyInvoicingSid"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
          <div class="title">商品列表</div>
          <el-table :key="commodityKey" :data="formobj.goodsVos" :index="index" border style="width: 100%">
            <el-table-column fixed width="60" label="序号" type="index" :index="index + 1" align="center" />
            <el-table-column align="center" width="80">
              <template slot="header" slot-scope="scope">
                <i class="add-btn-icon el-icon-plus" style="color: red;font-size:20px" @click="commodityAdd(scope.row)"></i>
              </template>
              <template slot-scope="scope">
                <i class="el-icon-delete" @click="commodityDelete(scope.$index)"></i>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" align="center" width="200">
              <template slot-scope="scope">
                <el-popover placement="right" trigger="click"  width="500">
                  <div>
                    <el-table :data="commodityData" v-loading="commodityLoading" highlight-current-row @current-change="commodityCurrentChange($event, scope.row)">
                      <el-table-column fixed prop="goodsSpuName" label="商品名称" align="center" />
                      <el-table-column prop="goodsSkuCode" label="图号" align="center" />
                      <el-table-column prop="goodsSkuOwnSpec" label="规格" align="center" />
                      <el-table-column prop="unit" label="单位" align="center" />
                    </el-table>
                    <el-pagination :page.sync="commodityQuery.current" :page-size="commodityQuery.size" layout="total, pager" :total="commodityQuery.total" />
                  </div>
                  <el-input slot="reference" v-model="scope.row.goodsSpuName" @input="commodityInput(scope.row.goodsSpuName)" clearable placeholder="商品名称"/>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="goodsSkuCode" label="图号" align="center" width="100" />
            <el-table-column prop="goodsSkuOwnSpec" label="规格" align="center" width="100" />
            <el-table-column prop="unit" label="单位" align="center" width="100" />
            <el-table-column prop="billObjName" label="供应商" align="center" width="150" />
            <el-table-column prop="warehouseName" label="仓库" align="center" width="150" />
            <el-table-column prop="areaName" label="库区" align="center" width="150" />
            <el-table-column prop="warehouseRackCode" label="库位" align="center" width="150" />
            <el-table-column prop="currentCount" label="库存" align="center" width="100" />
            <el-table-column prop="price" label="销售价" align="center" width="150" />
            <el-table-column label="数量" align="center" width="100">
              <template slot-scope="scope">
                <el-input @input="computeYHAndXSJE(scope.row)" v-model="scope.row.count" @keyup.native="scope.row.count = getNumber(scope.row.count, 2)" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column label="折扣" align="center" width="100">
              <template slot-scope="scope">
                <el-input @input="computeYHAndXSJE(scope.row)" v-model="scope.row.discount" @keyup.native="scope.row.discount = getNumber(scope.row.discount, 2)" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column prop="discountAmount" label="优惠" align="center" width="100" />
            <el-table-column prop="amount" label="金额" align="center" width="100" />
            <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>
          <div class="title">附加项目</div>
          <el-table :key="subjoinKey" :data="formobj.aitemVos" :index="index" border style="width: 100%">
            <el-table-column fixed width="60" label="序号" type="index" :index="index + 1" align="center"/>
            <el-table-column align="center" width="80">
              <template slot="header" slot-scope="scope">
                <i class="add-btn-icon el-icon-plus" style="color: red;font-size:20px" @click="subjoinAdd(scope.row)"></i>
              </template>
              <template slot-scope="scope">
                <i class="el-icon-delete" @click="subjoinDelete(scope.$index)"></i>
              </template>
            </el-table-column>
            <el-table-column label="附加项目" align="center" width="200">
              <template slot-scope="scope">
                <el-popover placement="right" width="500" trigger="click">
                  <div>
                    <el-table :data="subjoinData" v-loading="subjoinLoading" highlight-current-row @current-change="subjoinCurrentChange($event, scope.row)">
                      <el-table-column fixed prop="aitemName" label="项目名称" align="center" />
                      <el-table-column prop="aitemCode" label="项目编码" align="center" />
                      <el-table-column prop="price" label="销售金额" align="center" />
                    </el-table>
                    <el-pagination :page.sync="subjoinQuery.current" :page-size="subjoinQuery.size" layout="total, pager" :total="subjoinQuery.total" />
                  </div>
                  <el-input slot="reference" v-model="scope.row.aitemName" @input="subjoinInput(scope.row.aitemName)" clearable placeholder="项目名称、拼音"/>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="销售价" align="center" width="150" />
            <el-table-column label="备注" align="center" min-width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" clearable placeholder="" />
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <el-col :span="24">
              <div class="span-sty" style="border-right: 0px">合计金额：</div>
              <el-form-item><span class="addinputInfo">{{ jeTotal }} = 材料费：{{ clfTotal }} + 附加费：{{ fjfTotal }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="span-sty" style="border-right: 0px">应收金额：</div>
              <el-form-item><span class="addinputInfo">{{ ysjeTotal }} = 合计金额：{{ jeTotal }} - 优惠：{{ yhTotal }}</span></el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!-- 选择客户 -->
    <selectCustomer v-show="viewState == 2" ref="divCus" @backData="backData" @doback="resetState"/>
    <!-- 结算 -->
    <el-dialog :visible.sync="settleVisible" width="70%">
      <el-form ref="formobj" :model="formobj" :rules="rules" class="formaddcopy02">
        <el-row style="border-top: 1px solid #e0e3eb">
          <el-col :span="8">
            <div class="span-sty"><span class="icon">*</span>付款人姓名</div>
            <el-form-item prop="settlementVo.payerName"><el-input class="addinputInfo addinputw" v-model="formobj.settlementVo.payerName" clearable placeholder="" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">付款人编号</div>
            <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.settlementVo.payerNo" clearable placeholder="" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">应收金额</div>
            <el-form-item><span class="addinputInfo">{{ ysjeTotal }}</span></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <div class="span-sty">订金抵扣</div>
            <el-form-item><el-input class="addinputInfo addinputw" @keyup.native="formobj.settlementVo.depositdeductAmount = getNumber(formobj.settlementVo.depositdeductAmount, 2)" v-model="formobj.settlementVo.depositdeductAmount" clearable placeholder="" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty"><span class="icon">*</span>结算方式</div>
            <el-form-item prop="settlementVo.settleValue">
              <el-select class="addinputInfo" v-model="formobj.settlementVo.settleValue" placeholder="请选择" @change="settleChange" clearable filterable>
                <el-option v-for="item in settle_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty"><span class="icon">*</span>结算金额</div>
            <el-form-item prop="settlementVo.settleAmount"><el-input class="addinputInfo addinputw" @keyup.native="formobj.settlementVo.settleAmount = getNumber(formobj.settlementVo.settleAmount, 2)" v-model="formobj.settlementVo.settleAmount" clearable placeholder="" /></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <div class="span-sty">其他结算方式</div>
            <el-form-item>
              <el-select class="addinputInfo" v-model="formobj.settlementVo.otherSettleValue" placeholder="请选择" @change="otherSettleChange" clearable filterable>
                <el-option v-for="item in otherSettle_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
              </el-select>
            </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.settlementVo.otherSettleAmount = getNumber(formobj.settlementVo.otherSettleAmount, 2)" v-model="formobj.settlementVo.otherSettleAmount" clearable placeholder="" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">欠款金额</div>
            <el-form-item><span class="addinputInfo">{{ qkjeTotal }}</span></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="span-sty"><span class="icon">*</span>结算时间</div>
            <el-form-item prop="settlementVo.settleTime"><el-date-picker class="addinputInfo addinputw" v-model="formobj.settlementVo.settleTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期" /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align:center;margin-top: 20px;">
        <el-button type="primary" size="mini" @click="confirm">确 定</el-button>
        <el-button type="info " size="mini" @click="settleVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import req from '@/api/operation/salesticket'
import additionitem from '@/api/basicinformation/additionitem'
import { selAllByOrgSidPath, selSubjectInfo, typeValues, listPageSales, getOrgSidByPath, getInvoicingList } from '@/api/Common/dictcommons'
import selectCustomer from '@/components/publicPage/selectCustomer'
import {getStorage} from "@/utils/auth";

export default {
  name: 'SalesTicketAdd',
  components: {
    selectCustomer
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      submitdisabled: false,
      user_list: [], // 销售人员
      subject_list: [], // 科目
      settleVisible: false, // 结算弹框
      invoiceType_list: [], // 发票类型
      companyInvoicing_list: [], // 开票单位
      settle_list: [], // 结算方式
      otherSettle_list: [], // 其他结算方式
      activeNames: '1',
      index: 0,
      // commodity商品
      commodityKey: 1,
      commodityLoading: false,
      commodityQuery: {
        current: 1,
        size: 2,
        total: 0,
        params: {
          goodsName: '',
          useOrgSid: ''
        }
      },
      commodityData: [],
      // subjoin附加项目
      subjoinKey: 2,
      subjoinLoading: false,
      subjoinQuery: {
        current: 1,
        size: 2,
        total: 0,
        params: {
          aitemName: '',
          orgPath: ''
        }
      },
      subjoinData: [],
      formobj: {
        sid: '',
        createOrgSid: '',
        createOrgName: '',
        useOrgSid: '',
        useOrgName: '',
        createTime: '',
        createByName: '',
        createBySid: '',
        customerName: '',
        customerSid: '',
        deptName: '',
        deptSid: '',
        mobile: '',
        vehMark: '',
        vinNo: '',
        billNo: '',
        subjectSid: '',
        subject: '',
        salesUserSid: '',
        salesName: '',
        shotRemarks: '',
        printRemarks: '',
        discountAmount: '',
        coupon: '',
        scoreDeduct: '',
        customerOrg: '',
        receivableAmount: '',
        goodsAmount: '',
        addAmount: '',
        invoiceVo: {
          isInvoicing: '',
          invoiceType: '',
          invoiceTypeKey: '',
          taxpayerNo: '',
          invoiceCode: '',
          taxRate: '',
          invoiceTitleSid: '',
          invoiceTitle: ''
        },
        aitemVos: [],
        goodsVos: [],
        settlementVo: {
          payerNo: '',
          payerName: '',
          receivableAmount: '',
          depositdeductAmount: '',
          settleKey: '',
          settleValue: '',
          settleAmount: '',
          otherSettleKey: '',
          otherSettleValue: '',
          otherSettleAmount: '',
          debts: '',
          settleTime: ''
        }
      },
      rules: {
        salesName: [{ required: true, message: '服务顾问不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    // 计算材料费 = 商品列表中所有销售价乘以数量的值之和
    clfTotal() {
      let clf = '0'
      if (this.formobj.goodsVos.length > 0) {
        this.formobj.goodsVos.forEach((e) => {
          if (e.goodsSpuName !== '') {
            clf = Math.round((parseFloat(clf) + (parseFloat(e.price !== '' ? e.price : '0') * parseFloat(e.count !== '' ? e.count : '0'))) * 100) / 100
          }
        })
      }
      return clf
    },
    // 计算附加费 == 附加项目列表中所有销售价之和
    fjfTotal() {
      let fjf = '0'
      if (this.formobj.aitemVos.length > 0) {
        this.formobj.aitemVos.forEach((e) => {
          if (e.aitemName !== '') {
            fjf = Math.round((parseFloat(fjf) + parseFloat(e.price !== '' ? e.price : '0')) * 100) / 100
          }
        })
      }
      return fjf
    },
    // 计算合计金额 = 材料费 + 附加费
    jeTotal() {
      let je = '0'
      je = Math.round((parseFloat(je) + parseFloat(this.clfTotal) + parseFloat(this.fjfTotal)) * 100) / 100
      return je
    },
    // 计算优惠 = 商品列表中所有优惠之和、
    yhTotal() {
      let yh = '0'
      if (this.formobj.goodsVos.length > 0) {
        this.formobj.goodsVos.forEach((e) => {
          yh = Math.round((parseFloat(yh) + parseFloat(e.discountAmount !== '' ? e.discountAmount : '0')) * 100) / 100
        })
      }
      return yh
    },
    // 计算应收金额 = 合计金额 - 优惠
    ysjeTotal() {
      let ysje = '0'
      ysje = Math.round((parseFloat(ysje) + parseFloat(this.jeTotal) - parseFloat(this.yhTotal)) * 100) / 100
      return ysje
    },
    // 结算页面中计算欠款金额 = 应付金额 - 订金抵扣 - 结算金额 - 其他结算金额
    qkjeTotal() {
      let qkje = '0'
      qkje = Math.round((parseFloat(this.ysjeTotal) - parseFloat(this.formobj.settlementVo.depositdeductAmount !== '' ? this.formobj.settlementVo.depositdeductAmount : '0') - parseFloat(this.formobj.settlementVo.settleAmount !== '' ? this.formobj.settlementVo.settleAmount : '0') - parseFloat(this.formobj.settlementVo.otherSettleAmount !== '' ? this.formobj.settlementVo.otherSettleAmount : '0')) * 100) / 100
      return qkje
    }
  },
  methods: {
    init() {
      typeValues({ type: 'billingType' }).then((res) => {
        if (res.success) {
          this.invoiceType_list = res.data
        }
      })
      getInvoicingList({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.companyInvoicing_list = res.data
        }
      })
      typeValues({ type: 'settle' }).then((res) => {
        if (res.success) {
          this.settle_list = res.data
        }
      })
      typeValues({ type: 'otherSettle' }).then((res) => {
        if (res.success) {
          this.otherSettle_list = res.data
        }
      })
      selSubjectInfo({ useOrgSid: window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1) }).then((resp) => {
        if (resp.success) {
          this.subject_list = resp.data
        }
      })
      selAllByOrgSidPath({ orgSidPath: window.sessionStorage.getItem('defaultOrgPath') }).then((resp) => {
        if (resp.success) {
          this.user_list = resp.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
    },
    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.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)
      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.invoiceVo.isInvoicing = '0'
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.formobj.createOrgSid = res.data
          this.formobj.useOrgSid = res.data
        }
      })
    },
    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
        }
      })
    },
    selectCustomer() {
      this.viewState = 2
      this.$refs['divCus'].showData(this.formobj.deptSid, '')
    },
    backData(value) {
      this.viewState = 1
      value = JSON.parse(JSON.stringify(value))
      this.formobj.customerName = value.customerName
      this.formobj.customerSid = value.sid
      this.formobj.mobile = value.mobile
      this.formobj.vehMark = value.vehMark
      this.formobj.vinNo = value.vinNo
    },
    waitorChange(value) {
      const choose = this.user_list.filter((item) => item.name === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.salesUserSid = choose[0].sid
      } else {
        this.formobj.salesUserSid = ''
      }
    },
    isInvoicingChange() {
      if (this.formobj.invoiceVo.isInvoicing !== '1') {
        this.formobj.invoiceVo.invoiceTitle = ''
        this.formobj.invoiceVo.invoiceTitleSid = ''
        this.formobj.invoiceVo.invoiceType = ''
        this.formobj.invoiceVo.invoiceTypeKey = ''
        this.formobj.invoiceVo.taxRate = ''
      }
      this.taxRateInput()
    },
    invoiceTypeChange(value) {
      const choose = this.invoiceType_list.filter((item) => item.dictValue === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.invoiceVo.invoiceTypeKey = choose[0].dictKey
      } else {
        this.formobj.invoiceVo.invoiceTypeKey = ''
      }
    },
    taxRateInput() {
      if (this.formobj.goodsVos.length > 0) {
        this.formobj.aitemVos.forEach((k) => {
          if (this.formobj.invoiceVo.isInvoicing === '1') {
            if (k.isTaxRate === '0') {
              // 商品进货价含税则销售价 = 原销售价
              k.price = k.goodsDetailsPrice
            } else {
              // 商品进货价不含税则销售价 = 原销售价 + 原销售价 * (1 + 税率)
              k.price = Math.round((parseFloat(k.goodsDetailsPrice) + parseFloat(k.goodsDetailsPrice) * (parseFloat(1) + parseFloat(this.formobj.invoiceVo.taxRate !== '' ? this.formobj.invoiceVo.taxRate : '0') / 100)) * 100) / 100
            }
            this.computeYHAndXSJE(k)
          } else {
            // 销售价 = 原销售价
            k.price = k.goodsDetailsPrice
          }
        })
      }
      if (this.formobj.aitemVos.length > 0) {
        this.formobj.aitemVos.forEach((e) => {
          if (this.formobj.invoiceVo.isInvoicing === '1') {
             // 销售价 = 原销售价 + 原销售价 * (1 + 税率)
            e.price = Math.round((parseFloat(e.aitemPrice) + parseFloat(e.aitemPrice) * (parseFloat(1) + parseFloat(this.formobj.invoiceVo.taxRate !== '' ? this.formobj.invoiceVo.taxRate : '0') / 100)) * 100) / 100
          } else {
            // 销售价 = 原销售价
            e.price = e.aitemPrice
          }
        })
      }
    },
    changeCompanyInvoicing(value) {
      const choose = this.companyInvoicing_list.filter((item) => item.companyInvoicingSid === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.invoiceVo.invoiceTitle = choose[0].companyInvoicingName
      } else {
        this.formobj.invoiceVo.invoiceTitle = ''
      }
    },
    commodityAdd() {
      this.formobj.goodsVos.push({
        goodSpuSid: '',
        goodsSkuSid: '',
        goodsSpuName: '', // 商品名称
        goodsSkuCode: '', // 商品编码(图号)
        goodsSkuOwnSpec: '', // 规格型号
        goodsSkuTitle: '', // 商品名称
        unit: '', // 计量单位
        warehouseName: '', // 仓库名称
        warehouseSid: '',
        areaName: '', // 库区
        areaSid: '',
        warehouseRackCode: '', // 库位编号
        warehouseRackSid: '',
        billObjName: '', // 供应商
        billObjSid: '',
        manufacturerName: '', // 厂家
        manufacturerSid: '',
        count: '', // 出/退库数量
        goodsDetailsPrice: '', // 原销售单价
        isTaxRate: '', // 是否含税
        inventorySid: '', // 库存sid
        price: '', // 销售价
        discount: '', // 折扣(0-10，0免费，10不打折)
        discountAmount: '', // 优惠金额 (=销售价*(1-折扣*0.1) )
        amount: '', // 金额(销售价-优惠金额)
        remarks: '',
        currentCount: '', // 库存数量
        supplierName: '', // 厂家
        goodsID: '' // 商品ID
      })
    },
    commodityInput(value) {
      this.commodityQuery.params.useOrgSid = this.formobj.deptSid
      this.commodityQuery.params.goodsName = value
      this.commodityLoading = true
      listPageSales(this.commodityQuery).then((response) => {
        if (response.success) {
          this.commodityLoading = false
          this.commodityData = response.data.records
          this.commodityQuery.total = response.data.total
        } else {
          this.commodityLoading = false
          this.commodityData = []
          this.commodityQuery.total = 0
        }
      })
    },
    commodityCurrentChange(value, row) {
      row.goodSpuSid = value.goodSpuSid
      row.goodsSkuSid = value.goodsSkuSid
      row.goodsSpuName = value.goodsSpuName
      row.goodsSkuCode = value.goodsSkuCode
      row.goodsSkuTitle = value.goodsSpuName
      row.goodsSkuOwnSpec = value.goodsSkuOwnSpec
      row.unit = value.unit
      row.warehouseName = value.warehouseName
      row.warehouseSid = value.warehouseSid
      row.areaName = value.areaName
      row.areaSid = value.areaSid
      row.warehouseRackCode = value.warehouseRackCode
      row.warehouseRackSid = value.warehouseRackSid
      row.billObjName = value.billObjName
      row.billObjSid = value.billObjSid
      row.manufacturerName = value.manufacturerName
      row.manufacturerSid = value.manufacturerSid
      row.count = value.count
      row.goodsDetailsPrice = value.price
      row.isTaxRate = value.isTaxRate
      row.inventorySid = value.inventorySid
      if (this.formobj.invoiceVo.isInvoicing === '1') {
        if (row.isTaxRate === '0') {
          // 商品进货价含税则销售价 = 原销售价
          row.price = row.goodsDetailsPrice
        } else {
          // 商品进货价不含税则销售价 = 原销售价 + 原销售价 * (1 + 税率)
          row.price = Math.round((parseFloat(row.goodsDetailsPrice) + parseFloat(row.goodsDetailsPrice) * (parseFloat(1) + parseFloat(this.formobj.invoiceVo.taxRate !== '' ? this.formobj.invoiceVo.taxRate : '0') / 100)) * 100) / 100
        }
      } else {
        // 销售价 = 原销售价
        row.price = row.goodsDetailsPrice
      }
      row.discount = ''
      row.discountAmount = ''
      row.amount = ''
      row.remarks = ''
      row.currentCount = value.currentCount
      row.supplierName = value.supplierName
      row.goodsID = value.goodsID
      document.body.click()
    },
    commodityDelete(index) {
      this.formobj.goodsVos.splice(index, 1)
    },
    // 计算优惠、销售金额 -- 维修项目列表
    computeYHAndXSJE(row) {
      // 计算优惠(销售价 * 数量 * (1 - (折扣 * 0.1)))
      row.discountAmount = Math.round((parseFloat(row.price === '' ? '0' : row.price) * parseFloat(row.count !== '' ? row.count : '0') * Math.round((parseFloat(1) - parseFloat(row.discount === '' ? '0' : row.discount) * parseFloat(0.1)) * 100) / 100) * 100) / 100
      // 计算销售金额(销售价 * 数量 - 优惠)
      if (row.price == 0) {
        row.amount = '0'
      } else {
        row.amount = Math.round((parseFloat(row.price === '' ? '0' : row.price) * parseFloat(row.count !== '' ? row.count : '0') - parseFloat(row.discountAmount === '' ? '0' : row.discountAmount)) * 100) / 100
      }
    },
    subjoinAdd() {
      this.formobj.aitemVos.push({
        aitemSid: '',
        aitemName: '', // 附加项目名称
        aitemPrice: '', // 原销售单价
        price: ''
      })
    },
    subjoinInput(value) {
      this.subjoinQuery.params.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      this.subjoinQuery.params.aitemName = value
      this.subjoinLoading = true
      additionitem.listPage(this.subjoinQuery).then((response) => {
        if (response.success) {
          this.subjoinLoading = false
          this.subjoinData = response.data.records
          this.subjoinQuery.total = response.data.total
        } else {
          this.subjoinLoading = false
          this.subjoinData = []
          this.subjoinQuery.total = 0
        }
      })
    },
    subjoinDelete(index) {
      this.formobj.aitemVos.splice(index, 1)
    },
    subjoinCurrentChange(value, row) {
      row.aitemSid = value.sid
      row.aitemName = value.aitemName
      row.aitemPrice = value.price
      if (this.formobj.invoiceVo.isInvoicing === '1') {
        // 销售价 = 原销售价 + 原销售价 * (1 + 税率)
        row.price = Math.round((parseFloat(row.aitemPrice) + parseFloat(row.aitemPrice) * (parseFloat(1) + parseFloat(this.formobj.invoiceVo.taxRate !== '' ? this.formobj.invoiceVo.taxRate : '0') / 100)) * 100) / 100
      } else {
        // 销售价 = 原销售价
        row.price = row.aitemPrice
      }
      document.body.click()
    },
    saveOrUpdate() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          if (this.formobj.customerName === '') {
            this.$message({ showClose: true, type: 'error', message: '客户信息不能为空' })
            return
          }
          if (this.formobj.goodsVos.length === 0) {
            this.$message({ showClose: true, type: 'error', message: '商品列表不能为空' })
            return
          }
          this.formobj.receivableAmount = this.ysjeTotal
          this.formobj.discountAmount = this.yhTotal
          this.formobj.goodsAmount = this.clfTotal // 材料费
          this.formobj.addAmount = this.fjfTotal // 附加费
          this.submitdisabled = true
          req.saveOrUpdate(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
          })
        }
      })
    },
    settleAccounts() {
      this.settleVisible = true
    },
    settleChange(value) {
      const choose = this.settle_list.filter((item) => item.dictValue === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.settlementVo.settleKey = choose[0].dictKey
      } else {
        this.formobj.settlementVo.settleKey = ''
      }
    },
    otherSettleChange(value) {
      const choose = this.otherSettle_list.filter((item) => item.dictValue === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.settlementVo.otherSettleKey = choose[0].dictKey
      } else {
        this.formobj.settlementVo.otherSettleKey = ''
      }
    },
    confirm() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          if (this.formobj.customerName === '') {
            this.$message({ showClose: true, type: 'error', message: '客户信息不能为空' })
            return
          }
          if (this.formobj.goodsVos.length === 0) {
            this.$message({ showClose: true, type: 'error', message: '商品列表不能为空' })
            return
          }
          this.formobj.receivableAmount = this.ysjeTotal
          this.formobj.discountAmount = this.yhTotal
          this.formobj.goodsAmount = this.clfTotal // 材料费
          this.formobj.addAmount = this.fjfTotal // 附加费
          this.submitdisabled = true
          req.settle(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
          })
        }
      })
    },
    print() {
      if (this.formobj.sid !== '') {
        req.printSmsBill({ sid: this.formobj.sid, userSid: this.formobj.createBySid, createOrgSid: this.formobj.createOrgSid, useOrgSid: this.formobj.deptSid }).then((res) => {
          if (res.success) {
            var xhr = new XMLHttpRequest()
            xhr.open('GET', process.env.VUE_APP_BASE_API + '/base/file/download?filePath=' + res.data + '&outFileName=' + '销售单', true)
            xhr.setRequestHeader('token', getStorage())
            xhr.responseType = 'blob'
            xhr.onload = function(e) {
              // 如果请求执行成功
              var blob = this.response
              var filename = '销售单.pdf'
              var a = document.createElement('a')
              // blob.type="application/octet-stream";
              // 创键临时url对象
              var url = URL.createObjectURL(blob)
              a.href = url
              a.download = filename
              a.click()
              // 释放之前创建的URL对象
              window.URL.revokeObjectURL(url)
            }
            // 发送请求
            xhr.send()
          }
        })
      } else {
        this.$message({ showClose: true, type: 'error', message: '请保存相关信息后在进行打印' })
      }
    },
    resetState() {
      this.viewState = 1
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {
        sid: '',
        createOrgSid: '',
        createOrgName: '',
        useOrgSid: '',
        useOrgName: '',
        createTime: '',
        createByName: '',
        createBySid: '',
        customerName: '',
        customerSid: '',
        deptName: '',
        deptSid: '',
        mobile: '',
        vehMark: '',
        vinNo: '',
        billNo: '',
        subjectSid: '',
        subject: '',
        salesUserSid: '',
        salesName: '',
        shotRemarks: '',
        printRemarks: '',
        discountAmount: '',
        coupon: '',
        scoreDeduct: '',
        customerOrg: '',
        receivableAmount: '',
        goodsAmount: '',
        addAmount: '',
        invoiceVo: {
          isInvoicing: '',
          invoiceType: '',
          invoiceTypeKey: '',
          taxpayerNo: '',
          invoiceCode: '',
          taxRate: '',
          invoiceTitleSid: '',
          invoiceTitle: ''
        },
        aitemVos: [],
        goodsVos: [],
        settlementVo: {
          payerNo: '',
          payerName: '',
          receivableAmount: '',
          depositdeductAmount: '',
          settleKey: '',
          settleValue: '',
          settleAmount: '',
          otherSettleKey: '',
          otherSettleValue: '',
          otherSettleAmount: '',
          debts: '',
          settleTime: ''
        }
      }
      this.commodityData = []
      this.subjoinData = []
      this.settleVisible = false
      this.submitdisabled = false
      this.$emit('doback')
    }
  }
}
</script>

<style scoped>
.span-sty {
  width: 130px !important;
}
.addinputInfo {
  margin-left: 120px !important;
}
/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;
}
</style>
