<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="submitVehicleApply()">提交</el-button>
          <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
        </div>
      </div>
      <div class="listconadd">
        <div class="titwu"><span>付款申请</span></div>
        <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.name }}</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="6">
              <div class="span-sty"><span class="icon">*</span>品牌</div>
              <el-form-item prop="carBrandName">
                <el-select class="addinputInfo" v-model="formobj.carBrandName" filterable placeholder="请选择" @change="changeCarBrand" clearable>
                  <el-option v-for="item in carBrand_list" :key="item.sid" :label="item.brandName" :value="item.brandName"/>
                </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.costRangeValue" clearable filterable @change="changeCostRange" placeholder="请选择">
                  <el-option v-for="item in costRange_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></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.costTypeValue" clearable filterable @change="changeCostType" placeholder="请选择">
                  <el-option v-for="item in costType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty"><span class="icon">*</span>是否涉及车辆</div>
              <el-form-item prop="isVeh">
                <el-radio-group :disabled="formobj.costTypeKey !== '001' && formobj.costTypeKey !== ''" class="addinputInfo" v-model="formobj.isVeh" @change="isVehChange">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <div class="span-sty"><span class="icon">*</span>付款单位</div>
              <el-form-item prop="payCompany">
                <el-select class="addinputInfo" v-model="formobj.payCompany" filterable placeholder="请选择" @change="changePayCompany" clearable>
                  <el-option v-for="item in payCompany_list" :key="item.companyInvoicingSid" :label="item.companyInvoicingName" :value="item.companyInvoicingName"/>
                </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.remarks" placeholder="" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div v-if="formobj.isVeh == '0'">
                <div class="span-sty"><span class="icon">*</span>是否事业部运营经理审批</div>
                <el-form-item prop="isLeaderSp">
                  <el-radio-group class="addinputInfo" v-model="formobj.isLeaderSp">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="6">
              <div v-if="formobj.isVeh == '0' && formobj.isLeaderSp == '1'">
                <div class="span-sty"><span class="icon">*</span>是否事业部总经理审批</div>
                <el-form-item prop="isManageSp">
                  <el-radio-group class="addinputInfo" v-model="formobj.isManageSp">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <div v-if="formobj.costTypeValue === '融资付款'">
            <div class="title titleOne">
              <div>融资平仓付款明细</div>
              <el-button type="primary" size="mini" icon="el-icon-plus" class="btntopblueline" @click="handleSelect()">选择</el-button>
            </div>
            <el-table :key="eveKey" :data="formobj.eveList" :index="index" border style="width: 100%">
              <el-table-column fixed width="80" label="序号" type="index" :index="index + 1" align="center"/>
              <el-table-column fixed label="操作" width="100" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="deleteEve(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="costTitleValue" label="款项名称" align="center" width="200" />
              <el-table-column prop="openDate" label="融资付款开通日期" align="center" width="160" />
              <el-table-column prop="period" label="期数" align="center" width="100" />
              <el-table-column label="付款方式" align="center" width="200">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.payWayValue" placeholder="请选择" filterable @change="changePayWay($event, scope.row)">
                    <el-option v-for="item in payment_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="receiveCompany" label="收款单位名称" align="center" width="140" />
              <el-table-column prop="bank" label="开户行" align="center" width="130" />
              <el-table-column prop="receivingAccount" label="收款银行账号" align="center" width="140" />
              <el-table-column prop="exePayPrice" label="付款金额(元)" align="center" width="140" />
              <el-table-column prop="remarks" label="付款备注" align="center" min-width="200" />
            </el-table>
          </div>
          <div v-else>
            <div class="title titleOne">
              <div>付款明细</div>
              <el-button type="primary" size="mini" icon="el-icon-plus" class="btntopblueline" @click="handleAdd()">添加</el-button>
            </div>
            <el-table :key="tableKey" :data="formobj.detailsList" :index="index" border style="width: 100%" show-summary :summary-method="getSummaries">
              <el-table-column fixed width="80" label="序号" type="index" :index="index + 1" align="center"/>
              <el-table-column fixed label="操作" width="180" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
                  <el-button size="mini" type="primary" @click="handleAddPayment(scope.row, scope.$index)">新增关联付款</el-button>
                </template>
              </el-table-column>
              <el-table-column label="款项名称" align="center" width="200">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.costTitleValue" clearable filterable @change="changeCostTitle($event, scope.row)" placeholder="请选择">
                    <el-option v-for="item in costTitle_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="付款方式" align="center" width="200">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.paymentType" placeholder="请选择" filterable @change="changePaymentType($event, scope.row)">
                    <el-option v-for="item in payment_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="厂家回款通路" align="center" width="200">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.actualPay" placeholder="请选择" filterable @change="changeActualPay($event, scope.row)">
                    <el-option v-for="item in actualPay_list" :key="item.actualPaySid" :label="item.actualPay" :value="item.actualPay"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="receiveCompany" label="收款单位" align="center" width="150" />
              <el-table-column prop="bank" label="开户行" align="center" width="140" />
              <el-table-column prop="receivingAccount" label="收款银行账号" align="center" width="160" />
              <el-table-column prop="payAccount" label="付款金额(元)" align="center" width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.payAccount" placeholder="" clearable @keyup.native="scope.row.payAccount = getNumber(scope.row.payAccount, 2)" @keydown.native="scope.row.payAccount = getNumber(scope.row.payAccount, 2)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="付款备注" align="center" min-width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remarks" placeholder="" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column label="关联付款详情" align="center" width="120">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" v-show="scope.row.finPaymentapplyDetailsBelowList.length > 0" @click="handleLookPayment(scope.row, scope.$index)">查看</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="payAccountTotal" label="关联付款金额" align="center" width="140"/>
            </el-table>
          </div>

          <div v-show="formobj.costTypeKey == '001' && formobj.isVeh == '1'"><!-- 款项类别为主车厂家采购且是否涉及车辆为是时显示 -->
            <div class="title titleOne">
              <div>车辆列表</div>
              <div style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center;">
                <div style="margin-right: 10px">
                  <span><span class="icon">*</span>是否已销售：</span>
                  <el-radio-group v-model="formobj.isSales" @change="clearByCar('isSales', $event)">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </div>
                <div style="margin-right: 10px">
                  <span><span class="icon">*</span>款项是否已交清：</span>
                  <el-radio-group v-model="formobj.isSettle" @change="clearByCar('isSettle', $event)">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </div>
                <el-button type="primary" size="mini" icon="el-icon-plus" class="btntopblueline" @click="toSelect()">选择</el-button>
              </div>
            </div>
            <el-table :key="vehicleKey" :data="formobj.vehicleList" :index="index" border style="width: 100%" show-summary :summary-method="getSummaries">
              <el-table-column fixed width="80" label="序号" type="index" :index="index + 1" align="center" />
              <el-table-column fixed label="操作" width="100" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="toDelete(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="modelName" label="车型" align="center" min-width="180" />
              <el-table-column prop="vinNo" label="车架号" align="center" width="160" />
              <el-table-column prop="marketSegmentsValue" label="版本" align="center" width="100" />
              <el-table-column prop="carColor" label="颜色" align="center" width="100" />
              <el-table-column prop="emissionStandardValue" label="排放" align="center" width="100" />
              <el-table-column prop="tranCaseTypeValue" label="变速箱" align="center" width="110" />
              <el-table-column prop="rearAxleValue" label="后桥" align="center" width="100" />
              <el-table-column prop="libraryAge" label="厂家库龄" align="center" width="120" />
              <el-table-column prop="orgLibraryAge" label="公司库龄" align="center" width="120" />
              <el-table-column label="上装名称" align="center" width="130">
                <template slot-scope="scope">
                  <span class="bluezi" @click="lookTops(scope.row)">{{ scope.row.topName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="insideCode" label="内部编码" align="center" width="120" />
              <el-table-column prop="money" label="车辆入库价" align="center" width="130" />
              <el-table-column label="合同/销售订单编号" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ scope.row.contractNo }}/{{ scope.row.saleBillNo }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="customerName" label="客户名称" align="center" width="120" />
              <el-table-column prop="saleTypeValue" label="销售订单类型" align="center" width="150" />
              <el-table-column prop="settlementStatusValue" label="买断状态" align="center" width="120" />
              <el-table-column label="是否申请买断" align="center" width="140">
                <template slot-scope="scope">
                  <el-radio-group v-if="scope.row.settlementStatusValue != '已买断'" v-model="scope.row.isSettle">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                  <span v-else>{{ scope.row.isSettle }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-show="formobj.costTypeKey == '002'"><!-- 款项类别为挂车采购时显示 -->
            <div class="title titleOne">
              <div>挂车列表</div>
              <el-button type="primary" size="mini" icon="el-icon-plus" class="btntopblueline" @click="trailerSelect()">选择</el-button>
            </div>
            <el-table :key="trailerKey" :data="formobj.trailerList" :index="index" border style="width: 100%" show-summary :summary-method="getSummaries">
              <el-table-column fixed width="80" label="序号" type="index" :index="index + 1" align="center" />
              <el-table-column fixed label="操作" width="100" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="trailerDelete(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="trailerTypeValue" label="挂车名称" align="center" min-width="180" />
              <el-table-column prop="size" label="外观尺寸" align="center" width="160" />
              <el-table-column prop="vinNo" label="车架号" align="center" width="100" />
              <el-table-column prop="color" label="箱体颜色" align="center" width="100" />
              <el-table-column prop="costPrice" label="厂家结算价" align="center" width="130" />
              <el-table-column prop="brandName" label="主车品牌" align="center" width="110" />
              <el-table-column prop="vehModel" label="主车车型" align="center" width="100" />
              <el-table-column prop="zcVinNo" label="主车车架号" align="center" width="120" />
              <el-table-column label="合同/销售订单编号" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ scope.row.contractNo }}/{{ scope.row.saleOrderNo }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="customerName" label="客户名称" align="center" width="120" />
              <el-table-column prop="payType" label="销售类型" align="center" width="150" />
            </el-table>
          </div>
          <div v-show="formobj.costTypeKey == '003'"><!-- 款项类别为上装采购时显示 -->
            <div class="title titleOne">
              <div>上装列表</div>
              <el-button type="primary" size="mini" icon="el-icon-plus" class="btntopblueline" @click="topSelect()">选择</el-button>
            </div>
            <el-table :key="topKey" :data="formobj.topList" :index="index" border style="width: 100%" show-summary :summary-method="getSummaries">
              <el-table-column fixed width="80" label="序号" type="index" :index="index + 1" align="center" />
              <el-table-column fixed label="操作" width="100" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="topDelete(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="installNameValue" label="上装/上装配置名称" align="center" min-width="180" />
              <el-table-column prop="size" label="货箱内部尺寸" align="center" width="160" />
              <el-table-column prop="vinNo" label="车架号" align="center" width="100" />
              <el-table-column prop="color" label="箱体颜色" align="center" width="100" />
              <el-table-column prop="costPrice" label="厂家结算价" align="center" width="130" />
              <el-table-column prop="brandName" label="主车品牌" align="center" width="110" />
              <el-table-column prop="vehModel" label="主车车型" align="center" width="100" />
              <el-table-column label="合同/销售订单编号" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ scope.row.contractNo }}/{{ scope.row.saleOrderNo }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="customerName" label="客户名称" align="center" width="120" />
              <el-table-column prop="payType" label="销售类型" align="center" width="150" />
            </el-table>
          </div>
        </el-form>
      </div>
    </div>
    <!--End 添加修改部分-->
    <!-- 付款明细表新增关联付款信息 -->
    <el-dialog :visible.sync="paymentVisible" width="70%" :show-close="false">
      <el-form class="formaddcopy02">
        <div class="title titleOne">
          <div>关联付款信息列表</div>
          <el-button type="primary" size="mini" class="btntopblueline" v-show="paymentBtn" @click="paymentAdd">新增</el-button>
        </div>
        <el-table :key="paymentKey" :data="paymentInformation.list" :index="index" border style="width: 100%">
          <el-table-column fixed width="80" label="序号" type="index" :index="index + 1" align="center" />
          <el-table-column fixed label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" v-show="paymentBtn" @click="paymentDelete(scope.$index)">删除</el-button>
              <el-button size="mini" type="primary" @click="paymentLook(scope.row)">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="costTitleValue" label="款项名称" align="center" width="120" />
          <el-table-column prop="paymentType" label="付款方式" align="center" width="120" />
          <el-table-column prop="receiveCompany" label="收款单位名称" align="center" width="160" />
          <el-table-column prop="bank" label="开户行" align="center" width="120" />
          <el-table-column prop="receivingAccount" label="银行账号" align="center" width="120" />
          <el-table-column prop="payAccount" label="付款金额" align="center" width="120" />
          <el-table-column prop="remarks" label="付款备注" align="center" min-width="200" />
          <el-table-column prop="isPay" label="后期是否有平仓付款" align="center" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.isPay == '1' ? '是' : '否' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div style="text-align: center;padding-top: 5px">
        <el-button size="small" type="primary" v-show="paymentBtn" @click="paymentSave">保存</el-button>
        <el-button size="small" @click="paymentClose">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 主车车辆列表选择车辆 -->
    <vehcile v-show="viewState == 2" ref="divVehicle" @backData="backData" @doback="resetState" />
    <!-- 挂车列表选择车辆 -->
    <trailerCar v-show="viewState == 6" ref="divTrailer" @backData="backTrailer" @doback="resetState" />
    <!-- 上装列表选择车辆 -->
    <top v-show="viewState == 7" ref="divTop" @backData="backTop" @doback="resetState" />
    <!-- 关联付款信息新增 -->
    <paymentInformationAdd v-show="viewState == 3" ref="divPaymentInformation" @backInformation="backInformation" @doback="resetStateByInformation" />
    <!-- 关联付款信息详情 -->
    <paymentInformationInfo v-show="viewState == 4" ref="divPaymentInformationInfo" @doback="resetStateByInformation" />
    <!-- 查看上装配置信息 -->
    <tops v-show="viewState == 5" ref="divTops" @doback="resetState" />
    <!-- 选择融资平仓付款 -->
    <closingPayment v-show="viewState == 8" ref="divClosingPayment" @backData="backClosingPayment" @doback="resetState" />
  </div>
</template>

<script>
import req from '@/api/anruifinmanagement/payment'
import { typeValues, getOrgSidByPath, getInvoicingList, brandDown, selectNameByOrg, getTypeValueList } from '@/api/jichuxinxi/dictcommons'
import vehcile from './relation/vehcile'
import trailerCar from './relation/trailerCar'
import top from './relation/top'
import paymentInformationAdd from './relation/paymentInformationAdd'
import paymentInformationInfo from './relation/paymentInformationInfo'
import closingPayment from './relation/closingPayment'
import tops from '@/components/publicPage/tops'

export default {
  name: 'PaymentAdd',
  components: {
    vehcile,
    trailerCar,
    top,
    paymentInformationAdd,
    paymentInformationInfo,
    tops,
    closingPayment
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      submitdisabled: false,
      tableKey: 0,
      vehicleKey: 1,
      paymentKey: 2,
      trailerKey: 3,
      topKey: 4,
      eveKey: 5,
      index: 0,
      carBrand_list: [],
      costRange_list: [],
      costType_list: [],
      costTitle_list: [],
      payCompany_list: [],
      payment_list: [],
      actualPay_list: [],
      formobj: {
        billNo: '', // 申请编号
        name: '', // 申请人姓名
        deptSid: '', // 申请部门sid
        deptName: '', // 申请部门名称
        createTime: '', // 申请日期
        costRangeKey: '', // 款项范围Key
        costRangeValue: '', // 款项范围value
        isLeaderSp: '', // 是否事业部运营经理审批，1是0否
        isManageSp: '', // 是否事业部总经理审批， 1是0否
        isSales: '', // 是否已销售
        isSettle: '', // 款项是否已交清
        costTypeKey: '', // 款项类别key
        costTypeValue: '', // 款项类别value
        cost: '', // 金额
        payCompanySid: '', // 付款单位sid
        payCompany: '', // 付款单位名称
        busSid: '', // 关联业务sid
        createOrgSid: '', // 创建组织
        useOrgSid: '', // 使用组织
        procInstId: '', // 流程实例id
        taskId: '', // 任务id
        isVeh: '', // 是否涉及车辆，1是，0否
        paymentTotal: '', // 付款明细合计
        carTotal: '', // 车辆金额合计
        carBrandSid: '', // 品牌sid
        carBrandName: '', // 品牌名称
        orgSidPath: '',
        eveList: [], // 融资平仓付款明细列表
        detailsList: [], // 付款信息列表
        vehicleList: [], // 主车车辆列表
        trailerList: [], // 挂车列表
        topList: [] // 上装列表
      },
      rules: {
        carBrandName: [{ required: true, message: '品牌不能为空', trigger: 'change' }],
        isVeh: [{ required: true, message: '是否涉及车辆不能为空', trigger: 'change' }],
        payCompany: [{ required: true, message: '付款单位不能为空', trigger: 'change' }],
        isLeaderSp: [{ required: true, message: '是否事业部运营经理审批不能为空', trigger: 'change' }],
        isManageSp: [{ required: true, message: '是否事业部总经理审批不能为空', trigger: 'change' }]
      },
      paymentVisible: false, // 付款明细表 -- 新增付款信息弹框
      paymentBtn: false, // 付款明细表 -- 新增付款信息弹框 -- 页面按钮是否显示隐藏
      paymentInformation: { // 关联付款信息列表
        index: '',
        list: []
      }
    }
  },
  methods: {
    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
    },
    init() {
      typeValues({ type: 'paymentScope' }).then((res) => {
        if (res.success) {
          this.costRange_list = res.data
        }
      })
      typeValues({ type: 'paymentCategory' }).then((res) => {
        if (res.success) {
          this.costType_list = res.data
        }
      })
      getTypeValueList({ type: 'payCostType', groupNum: '001' }).then((res) => {
        if (res.success) {
          this.costTitle_list = res.data
        }
      })
      getInvoicingList({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.payCompany_list = res.data
        }
      })
      typeValues({ type: 'paymentType' }).then((res) => {
        if (res.success) {
          this.payment_list = res.data
        }
      })
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((response) => {
        if (response.success) {
          this.formobj.createOrgSid = response.data
          this.formobj.useOrgSid = response.data
          brandDown({ useOrg: response.data }).then((res) => {
            if (res.success) {
              this.carBrand_list = res.data
            }
          })
        }
      })
    },
    showAdd() {
      this.init()
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.viewTitle = '【新增】付款申请'
      this.formobj.createBySid = window.sessionStorage.getItem('userSid')
      this.formobj.name = window.sessionStorage.getItem('name')
      this.formobj.deptName = window.sessionStorage.getItem('defaultOrgPathName').substring(window.sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1)
      this.formobj.deptSid = window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1)
      this.formobj.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      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.init()
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.viewTitle = '【编辑】付款申请'
      req.fetchBySid(row.sid).then((resp) => {
        if (resp.success) {
          this.formobj = resp.data
          this.formobj.instanceId = resp.data.procInstId
          selectNameByOrg({ carBrandSid: this.formobj.carBrandSid }).then((res) => {
            if (res.success) {
              this.actualPay_list = res.data
            }
          })
        }
      }).catch((e) => {
        this.formobj = row
      })
    },
    changeCarBrand(value) {
      const choose = this.carBrand_list.filter((item) => item.brandName === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.carBrandSid = choose[0].sid
        selectNameByOrg({ carBrandSid: this.formobj.carBrandSid }).then((res) => {
          if (res.success) {
            this.actualPay_list = res.data
          }
        })
      } else {
        this.formobj.carBrandSid = ''
        this.actualPay_list = []
      }
    },
    changeCostRange(value) {
      const choose = this.costRange_list.filter((item) => item.dictValue === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.costRangeKey = choose[0].dictKey
      } else {
        this.formobj.costRangeKey = ''
      }
    },
    changeCostType(value) {
      const choose = this.costType_list.filter((item) => item.dictValue === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.costTypeKey = choose[0].dictKey
        if (this.formobj.costTypeKey !== '001') {
          this.formobj.isVeh = '0'
        }
      } else {
        this.formobj.costTypeKey = ''
        this.formobj.isVeh = ''
      }
    },
    isVehChange(val) {
      if (val === '1') {
        this.formobj.isLeaderSp = ''
        this.formobj.isManageSp = ''
      } else if (val === '0') {
        this.formobj.isSales = ''
        this.formobj.isSettle = ''
        this.formobj.vehicleList = []
        this.formobj.isLeaderSp = '1'
        this.formobj.isManageSp = ''
      }
    },
    changePayCompany(value) {
      const choose = this.payCompany_list.filter((item) => item.companyInvoicingName === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.payCompanySid = choose[0].companyInvoicingSid
      } else {
        this.formobj.payCompanySid = ''
      }
    },
    handleSelect() {
      this.viewState = 8
      this.$refs['divClosingPayment'].showData(this.formobj.eveList, this.formobj.useOrgSid)
    },
    deleteEve(index) {
      this.formobj.eveList.splice(index, 1)
    },
    backClosingPayment(value) {
      this.viewState = 1
      value = JSON.parse(JSON.stringify(value))
      console.log(value, 77)
      value.forEach((e) => {
        this.formobj.eveList.push({
          sid: '', // sid
          applySid: '', // 付款申请sid
          costTitleValue: e.costTitleValue, // 平仓款名称
          openDate: e.openDate, // 融资付款开通日期
          period: e.period, // 期数
          payWayKey: '', // 付款方式Key
          payWayValue: '', // 付款方式Value
          receiveCompany: e.receiveCompany, // 收款单位名称
          receivingAccount: e.receivingAccount, // 收款银行账号
          bank: e.bank, // 开户行
          exePayPrice: e.exePayPrice, // 平仓付款金额
          remarks: e.remarks
        })
      })
    },
    changePayWay(value, row) {
      const choose = this.payment_list.filter((item) => item.dictValue === value)
      if (choose.length > 0 && choose !== null) {
        row.payWayKey = choose[0].dictKey
      } else {
        row.payWayKey = ''
      }
    },
    handleAdd() {
      if (this.formobj.carBrandName === '') {
        this.$message({ showClose: true, type: 'error', message: '请先选择品牌' })
        return
      }
      this.formobj.detailsList.push({
        costTitleKey: '',
        costTitleValue: '',
        paymentType: '',
        paymentTypeKey: '',
        actualPay: '',
        receiveCompany: '',
        receiveCompanySid: '',
        bank: '',
        receivingAccount: '',
        payAccount: '',
        remarks: '',
        isPay: '',
        payAccountTotal: '',
        finPaymentapplyDetailsBelowList: []
      })
    },
    handleDelete(index) {
      this.formobj.detailsList.splice(index, 1)
    },
    changeCostTitle(value, row) {
      const choose = this.costTitle_list.filter((item) => item.dictValue === value)
      if (choose.length > 0 && choose !== null) {
        row.costTitleKey = choose[0].dictKey
      } else {
        row.costTitleKey = ''
      }
    },
    changePaymentType(value, row) {
      const choose = this.payment_list.filter((item) => item.dictValue === value)
      if (choose.length > 0 && choose !== null) {
        row.paymentTypeKey = choose[0].dictKey
      } else {
        row.paymentTypeKey = ''
      }
    },
    changeActualPay(value, row) {
      const choose = this.actualPay_list.filter((item) => item.actualPay === value)
      if (choose.length > 0 && choose !== null) {
        row.actualPay = choose[0].actualPay
        row.receiveCompany = choose[0].accountName
        row.bank = choose[0].depositBank
        row.receivingAccount = choose[0].bankAccount
      } else {
        row.actualPay = ''
        row.bank = ''
        row.receivingAccount = ''
      }
    },
    handleAddPayment(row, index) {
      if (row.paymentType === '') {
        this.$message({ showClose: true, type: 'error', message: '付款方式不能为空' })
        return
      }
      this.paymentVisible = true
      this.paymentBtn = true
      this.paymentInformation.index = index
      this.paymentInformation.list = JSON.parse(JSON.stringify(row.finPaymentapplyDetailsBelowList))
    },
    handleLookPayment(row, index) {
      this.paymentVisible = true
      this.paymentBtn = false
      this.paymentInformation.inde = index
      this.paymentInformation.list = JSON.parse(JSON.stringify(row.finPaymentapplyDetailsBelowList))
    },
    paymentAdd() {
      this.paymentVisible = false
      this.viewState = 3
      this.$refs['divPaymentInformation'].showAdd(this.formobj.useOrgSid)
    },
    backInformation(value) {
      this.viewState = 1
      this.paymentVisible = true
      value = JSON.parse(JSON.stringify(value))
      this.paymentInformation.list.push({
        sid: '', // sid
        costTitleKey: value.costTitleKey, // 款项名称，数据字典
        costTitleValue: value.costTitleValue, // 款项名称
        paymentTypeKey: value.paymentTypeKey, // 付款方式key
        paymentType: value.paymentType, // 付款方式value
        receiveCompany: value.receiveCompany, // 收款单位名称
        receiveCompanySid: value.receiveCompanySid, // 收款单位sid
        bank: value.bank, // 开户行
        bankShortName: value.bankShortName, // 银行简称
        receivingAccount: value.receivingAccount, // 收款银行账号
        payAccount: value.payAccount, // 付款金额
        detailSid: '', // 付款申请明细sid
        isPay: value.isPay, // 后期是否有平仓付款
        remarks: value.remarks, // 付款备注
        finPaymentapplyDetailsBelowEveList: value.finPaymentapplyDetailsBelowEveList
      })
    },
    resetStateByInformation() {
      this.viewState = 1
      this.paymentVisible = true
    },
    paymentDelete(index) {
      this.paymentInformation.list.splice(index, 1)
    },
    paymentLook(row) {
      this.paymentVisible = false
      this.viewState = 4
      this.$refs['divPaymentInformationInfo'].showInfo(row)
    },
    paymentSave() {
      if (this.formobj.detailsList.length > 0) {
        this.formobj.detailsList[this.paymentInformation.index].finPaymentapplyDetailsBelowList = this.paymentInformation.list
        this.formobj.detailsList.forEach((e) => {
          e.payAccountTotal = ''
          if (e.finPaymentapplyDetailsBelowList.length > 0) {
            e.finPaymentapplyDetailsBelowList.forEach((k) => {
              e.payAccountTotal = Math.round((parseFloat(e.payAccountTotal !== '' ? e.payAccountTotal : 0) + parseFloat(k.payAccount !== '' ? k.payAccount : 0)) * 100) / 100
            })
          }
        })
      }
      this.paymentClose()
    },
    paymentClose() {
      this.paymentVisible = false
      this.paymentBtn = false
      this.paymentInformation = {
        index: '',
        list: []
      }
    },
    clearByCar(val, event) {
      if (val === 'isSettle' && event === '1') {
        this.formobj.isLeaderSp = '0'
        this.formobj.isManageSp = '0'
      } else if (val === 'isSettle' && event === '0') {
        this.formobj.isLeaderSp = '1'
        this.formobj.isManageSp = '1'
      }
      this.formobj.vehicleList = []
    },
    toSelect() {
      if (this.formobj.isSettle !== '' && this.formobj.isSales !== '') {
        this.viewState = 2
        this.$refs['divVehicle'].showData(this.formobj.vehicleList, this.formobj.useOrgSid, this.formobj.isSales, this.formobj.isSettle)
      } else {
        this.$message({ showClose: true, type: 'error', message: '是否已销售和款项是否已交清，请选择是或否' })
      }
    },
    toDelete(index) {
      this.formobj.vehicleList.splice(index, 1)
    },
    // 选择车辆--确定返回的数据
    backData(value) {
      this.viewState = 1
      value = JSON.parse(JSON.stringify(value))
      if (value.length > 0) {
        value.forEach((e) => {
          this.formobj.vehicleList.push({
            applySid: '',
            modelName: e.vehicleAlias,
            modelSid: e.modelSid,
            vinNo: e.vinNo,
            vehiSid: e.sid,
            money: e.money,
            configSid: e.configSid,
            marketSegmentsValue: e.marketSegmentsValue,
            carColor: e.carColor,
            emissionStandardValue: e.emissionStandardValue,
            tranCaseTypeValue: e.tranCaseTypeValue,
            rearAxleValue: e.rearAxleValue,
            libraryAge: e.libraryAge,
            orgLibraryAge: e.orgLibraryAge,
            topName: e.topName,
            topSid: e.topSid,
            insideCode: e.insideCode,
            contractNo: e.contractNo,
            saleBillNo: e.saleBillNo,
            customerName: e.customerName,
            saleTypeValue: e.saleTypeValue,
            settlementStatusValue: e.settlementStatusValue,
            isSettle: e.settlementStatusValue === '已买断' ? '——' : ''
          })
        })
      }
    },
    lookTops(row) {
      this.viewState = 5
      this.$refs['divTops'].showInfo({ sid: row.topSid })
    },
    trailerSelect() {
      this.viewState = 6
      this.$refs['divTrailer'].showData(this.formobj.trailerList, this.formobj.useOrgSid)
    },
    trailerDelete(index) {
      this.formobj.trailerList.splice(index, 1)
    },
    backTrailer(value) {
      this.viewState = 1
      value = JSON.parse(JSON.stringify(value))
      if (value.length > 0) {
        value.forEach((e) => {
          this.formobj.trailerList.push({
            trailerTypeValue: e.trailerTypeValue, // 挂车名称
            size: e.size, // 外观尺寸
            vinNo: e.vinNo, // 挂车车架号
            trailerSid: e.trailerSid, // 挂车sid
            color: e.color, // 箱体颜色
            costPrice: e.costPrice, // 厂家结算价
            brandName: e.brandName, // 品牌名称
            vehModel: e.vehModel, // 车型别名
            zcVinNo: e.zcVinNo, // 主车车架号
            contractNo: e.contractNo, // 合同编号
            saleOrderNo: e.saleOrderNo, // 销售订单号
            customerName: e.customerName, // 客户名称
            payType: e.payType // 销售类型
          })
        })
      }
    },
    topSelect() {
      this.viewState = 7
      this.$refs['divTop'].showData(this.formobj.topList, this.formobj.useOrgSid)
    },
    topDelete(index) {
      this.formobj.topList.splice(index, 1)
    },
    backTop(value) {
      this.viewState = 1
      value = JSON.parse(JSON.stringify(value))
      if (value.length > 0) {
        value.forEach((e) => {
          this.formobj.topList.push({
            installNameValue: e.installNameValue, // 上装名称
            topSid: e.topSid, // 上装sid
            size: e.size, // 外观尺寸
            vinNo: e.vinNo, // 车架号
            vehiSid: e.vehiSid, // 车辆sid
            color: e.color, // 箱体颜色
            costPrice: e.costPrice, // 厂家结算价
            brandName: e.brandName, // 品牌名称
            vehModel: e.vehModel, // 车型别名
            contractNo: e.contractNo, // 合同编号
            saleOrderNo: e.saleOrderNo, // 销售订单号
            customerName: e.customerName, // 客户名称
            payType: e.payType // 销售类型
          })
        })
      }
    },
    saveOrUpdate() {
      if (this.formobj.costTypeKey === '001' && this.formobj.isVeh === '1') {
        if (this.formobj.vehicleList.length === 0) {
          this.$message({ showClose: true, type: 'error', message: '车辆列表不能为空' })
          return
        } else {
          for (var i = 0; i < this.formobj.vehicleList.length; i++) {
            if (this.formobj.vehicleList[i].isSettle === '') {
              this.$message({ showClose: true, type: 'error', message: '车辆列表中是否申请买断不能为空' })
              return
            }
          }
        }
      }
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.saveOrUpdate(this.formobj).then((resp) => {
            if (resp.success) {
              this.$message({ showClose: true, type: 'success', message: resp.msg })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        } else {
          return false
        }
      })
    },
    submitVehicleApply() {
      if (this.formobj.costTypeKey === '001' && this.formobj.isVeh === '1') {
        if (this.formobj.vehicleList.length === 0) {
          this.$message({ showClose: true, type: 'error', message: '车辆列表不能为空' })
          return
        } else {
          for (var i = 0; i < this.formobj.vehicleList.length; i++) {
            if (this.formobj.vehicleList[i].isSettle === '') {
              this.$message({ showClose: true, type: 'error', message: '车辆列表中是否申请买断不能为空' })
              return
            }
          }
        }
      }
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.submitVehicleApply(this.formobj, this.formobj.sid).then((resp) => {
            if (resp.success) {
              this.$message({ showClose: true, type: 'success', message: resp.msg })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        } else {
          return false
        }
      })
    },
    // 合计
    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 === 'payAccount') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
          this.formobj.paymentTotal = sums[index] += ''
        } else if (column.property === 'money') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
          this.formobj.carTotal = sums[index] += ''
        } else if (column.property === 'costPrice') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
        }
      })
      return sums
    },
    resetState() {
      this.viewState = 1
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {
        billNo: '', // 申请编号
        name: '', // 申请人姓名
        deptSid: '', // 申请部门sid
        deptName: '', // 申请部门名称
        createTime: '', // 申请日期
        costRangeKey: '', // 款项范围Key
        costRangeValue: '', // 款项范围value
        isLeaderSp: '', // 是否事业部运营经理审批，1是0否
        isManageSp: '', // 是否事业部总经理审批， 1是0否
        isSales: '', // 是否已销售
        isSettle: '', // 款项是否已交清
        costTypeKey: '', // 款项类别key
        costTypeValue: '', // 款项类别value
        cost: '', // 金额
        payCompanySid: '', // 付款单位sid
        payCompany: '', // 付款单位名称
        busSid: '', // 关联业务sid
        createOrgSid: '', // 创建组织
        useOrgSid: '', // 使用组织
        procInstId: '', // 流程实例id
        taskId: '', // 任务id
        isVeh: '', // 是否涉及车辆，1是，0否
        paymentTotal: '', // 付款明细合计
        carTotal: '', // 车辆金额合计
        carBrandSid: '', // 品牌sid
        carBrandName: '', // 品牌名称
        orgSidPath: '',
        eveList: [], // 融资平仓付款明细列表
        detailsList: [], // 付款信息列表
        vehicleList: [], // 主车车辆列表
        trailerList: [], // 挂车列表
        topList: [] // 上装列表
      }
      this.submitdisabled = false
      this.$refs['form_obj'].resetFields()
      this.$emit('doback')
    }
  }
}
</script>

<style scoped>
.span-sty {
  width: 170px !important;
}
.addinputInfo {
  margin-left: 160px !important;
}
.formaddcopy02 .el-row .el-col /deep/ .el-form-item .addinputw {
  margin-left: 160px !important;
  width: calc(100% - 155px);
}
/deep/ .el-form-item__error {
  margin-left: 160px !important;
}
.formaddcopy02 .el-row .el-col /deep/ .el-form-item .el-radio-group {
  display: inline;
  line-height: 1px;
  vertical-align: middle;
}
.titleOne {
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
/* 覆盖element-ui的单选按钮样式 */
/deep/.titleOne .el-radio__input.is-checked .el-radio__inner {
  border-color: #409EFF; /* 未选中状态下的边框颜色 */
  background-color: #409EFF; /* 选中后的背景色 */
}
/* 如果需要改变选中后对勾的颜色 */
/deep/.titleOne .el-radio__input.is-checked .el-radio__inner:after {
  background-color: #000000; /* 对勾的颜色 */
}
/deep/.titleOne .el-radio__input.is-checked+.el-radio__label {
  color: #000000; /* 选中后的字体颜色 */
}
</style>
