<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <div class="tab-header webtop">
        <div>{{ viewTitle }}</div>
        <div>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate()">保存</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="submit()">提交</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.deptName }}</span></el-form-item>
            </el-col>
            <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.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="purchaseTypeValue">
                <div class="addinputInfo" style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center">
                  <el-select v-model="formobj.purchaseTypeValue" placeholder="请选择" @change="purchaseTypeChange" clearable filterable>
                    <el-option v-for="item in procurementType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                  </el-select>
                  <el-select style="margin-left: 5px" v-model="formobj.operateBrandValue" placeholder="选择经营品牌" @change="operateBrandChange" clearable filterable>
                    <el-option v-for="item in operateBrand_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>采购原因</div>
              <el-form-item prop="purchaseReasonValue">
                <el-select class="addinputInfo" v-model="formobj.purchaseReasonValue" placeholder="请选择" @change="purchaseReasonChange" clearable filterable>
                  <el-option v-for="item in procurementReason_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="payTypeValue">
                <el-select class="addinputInfo" v-model="formobj.payTypeValue" placeholder="请选择" @change="payTypeChange" clearable filterable>
                  <el-option v-for="item in paymentMethod_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
              </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="supplierSid">
                <div class="addinputInfo" style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center">
                  <el-select v-model="formobj.supplierSid" placeholder="请选择" @change="supplierChange" clearable filterable>
                    <el-option v-for="item in supplier_list" :key="item.sid" :label="item.supplierName" :value="item.sid"></el-option>
                  </el-select>
                  <el-select style="margin-left: 5px" :disabled="formobj.purchaseTypeValue == '外采'" v-model="formobj.warehouseTypeValue" placeholder="选择仓库类型" @change="warehouseTypeChange" clearable filterable>
                    <el-option v-for="item in warehouseType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>是否开发票</div>
              <el-form-item prop="purchaseBillInvoice.isInvoicing">
                <el-radio-group class="addinputInfo" @change="isInvoicingChange" v-model="formobj.purchaseBillInvoice.isInvoicing">
                  <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 v-show="formobj.purchaseBillInvoice.isInvoicing == '1'">
                <div class="span-sty">发票类型(税率)</div>
                <el-form-item><span class="addinputInfo">{{ formobj.purchaseBillInvoice.billType }}{{ formobj.purchaseBillInvoice.taxRate == '' ? '' : '(' + formobj.purchaseBillInvoice.taxRate + '%)' }}</span></el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row v-show="formobj.payTypeValue == '预付款'">
            <el-col :span="24">
              <div class="span-sty">预付款情况</div>
              <el-form-item><span class="addinputInfo">当前预付款项金额(元)：<el-input style="width: 30%" @keyup.native="formobj.prepaymentAmount = getNumber(formobj.prepaymentAmount, 2)" v-model="formobj.prepaymentAmount" clearable placeholder="" /></span></el-form-item>
            </el-col>
          </el-row>
          <el-row v-show="formobj.payTypeValue == '月结'">
            <el-col :span="24">
              <div class="span-sty">月结欠款情况</div>
              <el-form-item><span class="addinputInfo">累计欠款金额(元)：<el-input style="width: 30%" @keyup.native="formobj.owedAmount = getNumber(formobj.owedAmount, 2)" v-model="formobj.owedAmount" clearable placeholder="" /></span></el-form-item>
            </el-col>
          </el-row>
          <el-row v-show="formobj.purchaseTypeValue == '代理库'">
            <el-col :span="16">
              <div class="span-sty">厂家订单类型</div>
              <el-form-item>
                <el-select class="addinputInfo" v-model="formobj.manufacturersOrderTypeKey" placeholder="请选择" @change="manufacturersOrderTypeChange" clearable filterable>
                  <el-option v-for="item in manufacturersOrderType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">厂家订单号</div>
              <el-form-item><span class="addinputInfo">{{ formobj.manufacturersOrderNumber }}</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" v-model="formobj.remarks" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">采购人</div>
              <el-form-item>
                <span class="addinputInfo" v-if="formobj.purchaseTypeValue == '代理库'">{{ formobj.purchasingAgent }}</span>
                <el-select class="addinputInfo" v-else v-model="formobj.purchasingAgentSid" placeholder="请选择" @change="purchasingAgentChange" clearable filterable>
                  <el-option v-for="item in purchasingAgent_list" :key="item.sid" :label="item.name" :value="item.sid"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">预计到货日期</div>
              <el-form-item><el-date-picker class="addinputInfo" v-model="formobj.deliveryDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期" /></el-form-item>
            </el-col>
          </el-row>
          <div v-if="formobj.payTypeValue == '单笔付款'">
            <div class="title">订金及付款申请</div>
            <el-row>
              <el-col :span="8">
                <div class="span-sty"><span class="icon">*</span>是否先付货款</div>
                <el-form-item prop="purchasePay.isFirstPay">
                  <el-radio-group class="addinputInfo" v-model="formobj.purchasePay.isFirstPay">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="formobj.purchasePay.isFirstPay == '0'">
                <div class="span-sty"><span class="icon">*</span>审批通过后付订金</div>
                <el-form-item prop="purchasePay.deposit">
                  <el-input class="addinputInfo addinputw" @keyup.native="formobj.purchasePay.deposit = getNumber(formobj.purchasePay.deposit, 2)" v-model="formobj.purchasePay.deposit" clearable placeholder=""/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="formobj.purchasePay.isFirstPay == '0'">
                <div class="span-sty">验货后付货款</div>
                <el-form-item><span class="addinputInfo">{{ calculateGoodsMoney }}</span></el-form-item>
              </el-col>
              <el-col :span="16" v-else>
                <div class="span-sty">审批通过后付货款</div>
                <el-form-item><span class="addinputInfo">{{ calculateGoodsMoney }}</span></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.purchasePay.accountName" placeholder="请选择" @change="accountChange" clearable filterable>
                    <el-option v-for="item in account_list" :key="item.bankAccount" :label="item.accountName" :value="item.accountName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <div class="span-sty">开户行</div>
                <el-form-item><span class="addinputInfo">{{ formobj.purchasePay.bankName }}</span></el-form-item>
              </el-col>
              <el-col :span="8">
                <div class="span-sty">银行账号</div>
                <el-form-item><span class="addinputInfo">{{ formobj.purchasePay.bankAccount }}</span></el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="16">
                <div class="span-sty">其他费用名称</div>
                <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.purchasePay.otherAmountName" clearable placeholder=""/></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.purchasePay.otherAmount = getNumber(formobj.purchasePay.otherAmount, 2)" v-model="formobj.purchasePay.otherAmount" clearable placeholder=""/></el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="span-sty">付款备注</div>
                <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.purchasePay.payRemark" 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.purchasePay.filePaths" :limit="50" bucket="map" :upload-data="{ type: '0001' }"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="title titleOne">
            <div>商品列表</div>
            <el-button type="primary" size="mini" class="btntopblueline" @click="selectProducts">选择商品</el-button>
          </div>
          <el-table :key="tableKey" :data="formobj.pmsPurchaseBillDetailList" :index="index" border style="width: 100%">
            <el-table-column fixed width="60" label="序号" type="index" :index="index + 1" align="center"/>
            <el-table-column fixed label="操作" align="center" width="100">
              <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" width="300" />
            <el-table-column prop="goodsSkuCode" label="图号" align="center" width="200" />
            <el-table-column prop="goodsSkuOwnSpec" label="规格" align="center" width="200" />
            <el-table-column prop="unit" label="单位" align="center" width="100" />
            <el-table-column prop="manufacturerName" label="厂家" align="center" width="100" />
            <el-table-column label="采购数量" align="center" width="150">
              <template slot-scope="scope">
                <el-input @input="amountInput(scope.row)" @keyup.native="scope.row.count = getNumber(scope.row.count, 2)" v-model="scope.row.count" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column v-if="formobj.purchaseBillInvoice.isInvoicing == '1'" label="含税单价(元)" align="center" min-width="150">
              <template slot-scope="scope">
                <el-input @input="amountInput(scope.row)" @keyup.native="scope.row.taxPrice = getNumber(scope.row.taxPrice, 2)" v-model="scope.row.taxPrice" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column v-else label="不含税单价(元)" align="center" min-width="150">
              <template slot-scope="scope">
                <el-input @input="amountInput(scope.row)" @keyup.native="scope.row.taxPrice = getNumber(scope.row.taxPrice, 2)" v-model="scope.row.taxPrice" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="采购金额(元)" align="center" width="200" />
          </el-table>
          <el-row>
            <el-col :span="24">
              <div class="span-sty" style="border-right: 0px">数量：</div>
              <el-form-item><span class="addinputInfo">{{ slTotal }}</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">{{ yfTotal }} = 采购金额：{{ cgTotal }} + 运费：<el-input @keyup.native="formobj.freight = getNumber(formobj.freight, 2)" v-model="formobj.freight" style="width: 160px" clearable placeholder="" /> - 优惠：<el-input @keyup.native="formobj.discountAmount = getNumber(formobj.discountAmount, 2)" v-model="formobj.discountAmount" style="width: 160px" clearable placeholder="" /> + 误差调整：<el-input @keyup.native="formobj.errorAmount = getNumber(formobj.errorAmount, 2)" v-model="formobj.errorAmount" style="width: 160px" clearable placeholder="" /></span></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/procurement'
import uploadImg from '@/components/uploadFile/uploadImg'
import { typeValues, getOrgSidByPath, choiceSupplierInfo, selAllByOrgSidPath } from '@/api/Common/dictcommons'
import chooseproducts from './relation/chooseproducts'

export default {
  name: 'ProcurementAdd',
  components: {
    chooseproducts,
    uploadImg
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      submitdisabled: false,
      tableKey: 1,
      index: 0,
      accept: '.jpg,.jpeg,.png',
      procurementType_list: [],
      purchasingAgent_list: [],
      operateBrand_list: [],
      procurementReason_list: [],
      paymentMethod_list: [],
      supplier_list: [],
      warehouseType_list: [],
      manufacturersOrderType_list: [],
      account_list: [],
      formobj: {
        sid: '',
        remarks: '',
        createBySid: '',
        createByName: '',
        createTime: '',
        sourceBillSid: '',
        sourceBillNo: '',
        billNo: '',
        purchaseTypeKey: '',
        purchaseTypeValue: '',
        purchaseReasonKey: '',
        purchaseReasonValue: '',
        purchasingAgent: '',
        purchasingAgentSid: '',
        payTypeKey: '',
        payTypeValue: '',
        errorAmount: '',
        supplierSid: '',
        supplierName: '',
        supplierPhone: '',
        purchaserSid: '',
        purchaserName: '',
        deliveryDate: '',
        freight: '',
        discountAmount: '',
        payableAmount: '',
        prepaymentAmount: '',
        owedAmount: '',
        deptSid: '',
        deptName: '',
        procDefId: '',
        nodeId: '',
        procInstId: '',
        nodeState: '',
        taskId: '',
        finishTime: '',
        orgPath: '',
        useOrgSid: '',
        useOrgName: '',
        createOrgSid: '',
        createOrgName: '',
        operateBrandKey: '',
        operateBrandValue: '',
        warehouseTypeKey: '',
        warehouseTypeValue: '',
        manufacturersOrderTypeValue: '',
        manufacturersOrderTypeKey: '',
        manufacturersOrderNumber: '',
        purchasePay: {
          sid: '',
          billSid: '',
          isFirstPay: '',
          deposit: '',
          goodsMoney: '',
          accountName: '',
          bankName: '',
          bankAccount: '',
          otherAmountName: '',
          otherAmount: '',
          payRemark: '',
          filePaths: []
        },
        purchaseBillInvoice: {
          billSid: '',
          isInvoicing: '',
          billTypeKey: '',
          billType: '',
          taxRate: ''
        },
        pmsPurchaseBillDetailList: []
      },
      rules: {
        purchaseTypeValue: [{ required: true, message: '采购方式不能为空', trigger: 'change' }],
        purchaseReasonValue: [{ required: true, message: '采购原因不能为空', trigger: 'change' }],
        payTypeValue: [{ required: true, message: '付款方式不能为空', trigger: 'change' }],
        supplierSid: [{ required: true, message: '供应商不能为空', trigger: 'change' }],
        'purchaseBillInvoice.isInvoicing': [{ required: true, message: '是否开发票不能为空', trigger: 'change' }],
        'purchasePay.isFirstPay': [{ required: true, message: '是否先付货款不能为空', trigger: 'change' }],
        'purchasePay.deposit': [{ required: true, message: '审批通过后付订金不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 数量
    slTotal() {
      let sl = '0'
      if (this.formobj.pmsPurchaseBillDetailList.length > 0) {
        this.formobj.pmsPurchaseBillDetailList.forEach((e) => {
          if (e.goodsSpuName !== '') {
            sl = Math.round((parseFloat(sl) + parseFloat(e.count !== '' ? e.count : '0')) * 100) / 100
          }
        })
      }
      return sl
    },
    // 采购金额
    cgTotal() {
      let cg = '0'
      if (this.formobj.pmsPurchaseBillDetailList.length > 0) {
        this.formobj.pmsPurchaseBillDetailList.forEach((e) => {
          if (e.goodsSpuName !== '') {
            cg = Math.round((parseFloat(cg) + parseFloat(e.amount !== '' ? e.amount : '0')) * 100) / 100
          }
        })
      }
      return cg
    },
    // 应付金额
    yfTotal() {
      let yf = '0'
      yf = Math.round((parseFloat(yf) + parseFloat(this.cgTotal) + parseFloat(this.formobj.freight !== '' ? this.formobj.freight : '0') - parseFloat(this.formobj.discountAmount !== '' ? this.formobj.discountAmount : '0') + parseFloat(this.formobj.errorAmount !== '' ? this.formobj.errorAmount : '0')) * 100) / 100
      return yf
    },
    // 付货款
    calculateGoodsMoney() {
      let goodsMoney = '0'
      if (this.formobj.payTypeValue === '单笔付款') {
        if (this.formobj.purchasePay.isFirstPay === '1') {
          // 是否先付货款为是，计算审批通过后付货款 = 应付金额
          goodsMoney = this.yfTotal
        } else if (this.formobj.purchasePay.isFirstPay === '0') {
          // 是否先付货款为否，计算验货后付货款 = 应付金额 - 审批通过后付订金
          goodsMoney = parseFloat(this.yfTotal) - parseFloat(this.formobj.purchasePay.deposit !== '' ? this.formobj.purchasePay.deposit : '0')
        }
      }
      return goodsMoney
    }
  },
  methods: {
    init() {
      typeValues({ type: 'procurementType' }).then((res) => {
        if (res.success) {
          this.procurementType_list = res.data
        }
      })
      typeValues({ type: 'operateBrand' }).then((res) => {
        if (res.success) {
          this.operateBrand_list = res.data
        }
      })
      typeValues({ type: 'warehouseType' }).then((res) => {
        if (res.success) {
          this.warehouseType_list = res.data
        }
      })
      typeValues({ type: 'manufacturersOrderType' }).then((res) => {
        if (res.success) {
          this.manufacturersOrderType_list = res.data
        }
      })
      typeValues({ type: 'procurementReason' }).then((res) => {
        if (res.success) {
          this.procurementReason_list = res.data
        }
      })
      typeValues({ type: 'paymentMethod' }).then((res) => {
        if (res.success) {
          this.paymentMethod_list = res.data
        }
      })
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.formobj.createOrgSid = res.data
          this.formobj.useOrgSid = res.data
        }
      })
      choiceSupplierInfo({ deptSid: window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1) }).then((resp) => {
        if (resp.success) {
          this.supplier_list = resp.data
        }
      })
      selAllByOrgSidPath({ orgSidPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.purchasingAgent_list = res.data
        }
      })
    },
    showAdd() {
      this.viewTitle = '【新增】采购单'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      this.formobj.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      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)
    },
    showEdit(row) {
      this.viewTitle = '【编辑】采购单'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      req.fetchDetailsBySid(row.sid).then((res) => {
        if (res.success) {
          this.formobj = res.data
          this.formobj.instanceId = res.data.procInstId
        }
      })
    },
    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
    },
    purchaseTypeChange(value) {
      const choose = this.procurementType_list.filter((item) => item.dictValue === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.purchaseTypeKey = choose[0].dictKey
      } else {
        this.formobj.purchaseTypeKey = ''
      }
      if (this.formobj.purchaseTypeValue === '代理库') {
        // 采购人 = 申请人
        this.formobj.purchasingAgent = this.formobj.createByName
        this.formobj.purchasingAgentSid = this.formobj.createBySid
        this.formobj.warehouseTypeValue = ''
        this.formobj.warehouseTypeKey = ''
      } else if (this.formobj.purchaseTypeValue === '外采') {
        // 仓库类型默认为保外且不能修改
        this.formobj.warehouseTypeValue = '保外'
        this.formobj.warehouseTypeKey = '002'
        this.formobj.purchasingAgent = ''
        this.formobj.purchasingAgentSid = ''
      } else {
        this.formobj.purchasingAgent = ''
        this.formobj.purchasingAgentSid = ''
        this.formobj.warehouseTypeValue = ''
        this.formobj.warehouseTypeKey = ''
      }
    },
    operateBrandChange(value) {
      const choose = this.operateBrand_list.filter((item) => item.dictValue === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.operateBrandKey = choose[0].dictKey
      } else {
        this.formobj.operateBrandKey = ''
      }
    },
    purchaseReasonChange(value) {
      const choose = this.procurementReason_list.filter((item) => item.dictValue === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.purchaseReasonKey = choose[0].dictKey
      } else {
        this.formobj.purchaseReasonKey = ''
      }
    },
    payTypeChange(value) {
      const choose = this.paymentMethod_list.filter((item) => item.dictValue === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.payTypeKey = choose[0].dictKey
      } else {
        this.formobj.payTypeKey = ''
      }
    },
    supplierChange(value) {
      const choose = this.supplier_list.filter((item) => item.sid === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.supplierName = choose[0].supplierName
        this.account_list = choose[0].supplierBankChoices
      } else {
        this.formobj.supplierName = ''
        this.account_list = []
      }
    },
    warehouseTypeChange(value) {
      const choose = this.warehouseType_list.filter((item) => item.dictValue === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.warehouseTypeKey = choose[0].dictKey
      } else {
        this.formobj.warehouseTypeKey = ''
      }
    },
    manufacturersOrderTypeChange(value) {
      const choose = this.manufacturersOrderType_list.filter((item) => item.dictKey === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.manufacturersOrderTypeValue = choose[0].dictValue
      } else {
        this.formobj.manufacturersOrderTypeValue = ''
      }
    },
    purchasingAgentChange(value) {
      const choose = this.purchasingAgent_list.filter((item) => item.sid === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.purchasingAgent = choose[0].name
      } else {
        this.formobj.purchasingAgent = ''
      }
    },
    isInvoicingChange(val) {
      if (val === '1') {
        const choose = this.supplier_list.filter((item) => item.sid === this.formobj.supplierSid)
        if (choose !== null && choose.length > 0) {
          this.formobj.purchaseBillInvoice.billType = choose[0].billingTypeValue
          this.formobj.purchaseBillInvoice.billTypeKey = choose[0].billingTypeKey
          this.formobj.purchaseBillInvoice.taxRate = choose[0].taxRate
        }
      } else {
        this.formobj.purchaseBillInvoice.billType = ''
        this.formobj.purchaseBillInvoice.billTypeKey = ''
        this.formobj.purchaseBillInvoice.taxRate = ''
      }
    },
    accountChange(value) {
      const choose = this.account_list.filter((item) => item.accountName === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.purchasePay.bankAccount = choose[0].bankAccount
        this.formobj.purchasePay.bankName = choose[0].bankName
      } else {
        this.formobj.purchasePay.bankAccount = ''
        this.formobj.purchasePay.bankName = ''
      }
    },
    selectProducts() {
      this.viewState = 2
      const aa = []
      this.$refs['divSp'].showData(aa, this.formobj.createBySid, this.formobj.createOrgSid, this.formobj.deptSid)
    },
    backData(value) {
      this.viewState = 1
      if (value.length > 0) {
        value.forEach((e) => {
          this.formobj.pmsPurchaseBillDetailList.push({
            sid: '',
            billSid: '',
            goodsSpuSid: e.goodsSpuSid,
            goodsSpuName: e.goodsSpuName,
            goodsSkuSid: e.goodsSkuSid,
            goodsSkuTitle: e.goodsSpuName,
            goodsSkuCode: e.goodsSkuCode,
            goodsSkuOwnSpec: e.indexes,
            unit: e.goodsUnitName,
            manufacturerName: e.manufacturerName,
            manufacturerSid: e.manufacturerSid,
            warehouseSid: '',
            warehouseName: '',
            cost: '',
            count: '',
            taxAmount: '',
            taxPrice: '',
            amount: ''
          })
        })
      }
    },
    resetState() {
      this.viewState = 1
    },
    commodityDelete(index) {
      this.formobj.pmsPurchaseBillDetailList.splice(index, 1)
    },
    // 计算采购金额
    amountInput(row) {
      if (row.goodsSpuName !== '') {
        row.amount = Math.round((parseFloat(row.taxPrice !== '' ? row.taxPrice : '0') * parseFloat(row.count !== '' ? row.count : '0')) * 100) / 100
      }
    },
    saveOrUpdate() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          this.formobj.payableAmount = this.yfTotal
          this.formobj.purchasePay.goodsMoney = this.calculateGoodsMoney
          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
          })
        }
      })
    },
    submit() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          if (this.formobj.pmsPurchaseBillDetailList.length === 0) {
            this.$message({ showClose: true, type: 'error', message: '商品列表不能为空' })
            return
          }
          this.submitdisabled = true
          this.formobj.payableAmount = this.yfTotal
          this.formobj.purchasePay.goodsMoney = this.calculateGoodsMoney
          req.submit(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '提交成功' })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {
        sid: '',
        remarks: '',
        createBySid: '',
        createByName: '',
        createTime: '',
        sourceBillSid: '',
        sourceBillNo: '',
        billNo: '',
        purchaseTypeKey: '',
        purchaseTypeValue: '',
        purchaseReasonKey: '',
        purchaseReasonValue: '',
        purchasingAgent: '',
        purchasingAgentSid: '',
        payTypeKey: '',
        payTypeValue: '',
        errorAmount: '',
        supplierSid: '',
        supplierName: '',
        supplierPhone: '',
        purchaserSid: '',
        purchaserName: '',
        deliveryDate: '',
        freight: '',
        discountAmount: '',
        payableAmount: '',
        prepaymentAmount: '',
        owedAmount: '',
        deptSid: '',
        deptName: '',
        procDefId: '',
        nodeId: '',
        procInstId: '',
        nodeState: '',
        taskId: '',
        finishTime: '',
        orgPath: '',
        useOrgSid: '',
        useOrgName: '',
        createOrgSid: '',
        createOrgName: '',
        operateBrandKey: '',
        operateBrandValue: '',
        warehouseTypeKey: '',
        warehouseTypeValue: '',
        manufacturersOrderTypeValue: '',
        manufacturersOrderTypeKey: '',
        manufacturersOrderNumber: '',
        purchasePay: {
          sid: '',
          billSid: '',
          isFirstPay: '',
          deposit: '',
          goodsMoney: '',
          accountName: '',
          bankName: '',
          bankAccount: '',
          otherAmountName: '',
          otherAmount: '',
          payRemark: '',
          filePaths: []
        },
        purchaseBillInvoice: {
          billSid: '',
          isInvoicing: '',
          billTypeKey: '',
          billType: '',
          taxRate: ''
        },
        pmsPurchaseBillDetailList: []
      }
      this.submitdisabled = false
      this.$emit('doback')
    }
  }
}
</script>

<style scoped>
.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);
}
.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 .el-radio-group {
  display: inline;
  line-height: 1px;
  vertical-align: middle;
}
</style>
