<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="formadd">
          <el-row style="border-top: 1px solid #e0e3eb">
            <el-col :span="4" class="tleftb">
              <span>申请日期</span>
            </el-col>
            <el-col :span="8">
              <el-form-item><span>{{ formobj.createTime }}</span></el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span>申请人</span>
            </el-col>
            <el-col :span="8">
              <el-form-item><span>{{ formobj.name }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="tleftb">
              <span>款项类别</span>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-select 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="4" class="tleftb">
              <span>款项名称</span>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-select v-model="formobj.costTitleValue" clearable filterable @change="changeCostTitle" placeholder="请选择">
                  <el-option v-for="item in costTitle_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="4" class="tleftb">
              <span>业务编号</span>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-input v-model="formobj.busSid" class="addinputw" placeholder="" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
            </el-col>
            <el-col :span="8">
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="tleftb">
              <span>付款单位名称</span>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-select v-model="formobj.payCompany" filterable placeholder="请选择" @change="changePayCompany" clearable>
                  <el-option v-for="item in payCompany_list" :key="item.sid" :label="item.name" :value="item.name"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span>收款单位名称</span>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-select v-model="formobj.receiveCompany" filterable placeholder="请选择" @change="changeReceiveCompany" clearable>
                  <el-option v-for="item in receiveCompany_list" :key="item.sid" :label="item.manufacturerName" :value="item.manufacturerName"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="tleftb">
              <span>付款备注</span>
            </el-col>
            <el-col :span="20">
              <el-form-item>
                <el-input v-model="formobj.remarks" placeholder="更多配置" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="tleftb">
              <span>品牌</span>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-select 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="4" class="tleftb">
              <span><span class="icon">*</span>是否涉及车辆</span>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-radio v-model="formobj.isVeh" label="1">是</el-radio>
                <el-radio v-model="formobj.isVeh" label="0">否</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="title">
            <div>付款明细</div>
            <div>
              <el-button type="primary" size="mini" icon="el-icon-plus" class="btntopblueline" @click="handleAdd()">添加</el-button>
            </div>
          </div>
          <el-table :key="tableKey" :data="formobj.detailsList" :index="index" border style="width: 100%" show-summary :summary-method="getSummaries">
            <el-table-column fixed width="80px" label="序号" type="index" :index="index + 1" align="center"/>
            <el-table-column fixed prop="name" label="操作" width="100px" align="center" header-align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index)">删除
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="付款方式" align="center">
              <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">
              <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.bankAccount" :label="item.actualPay" :value="item.actualPay"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="开户行" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.bank }}</span>
              </template>
            </el-table-column>
            <el-table-column label="收款银行账号" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.receivingAccount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="payAccount" label="付款金额(元)" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.payAccount" placeholder="" clearable @keyup.native="UpNumberOne($event, scope.row)" @keydown.native="UpNumberOne($event, scope.row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="付款备注" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" placeholder="" clearable></el-input>
              </template>
            </el-table-column>
          </el-table>
          <div v-show="formobj.isVeh === '1'">
            <div class="title">
              <div>车辆列表</div>
              <div>
                <el-button type="primary" size="mini" icon="el-icon-plus" class="btntopblueline" @click="handleselect()">选择</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="80px" label="序号" type="index" :index="index + 1" align="center"/>
              <el-table-column fixed prop="name" label="操作" width="100px" align="center" header-align="center">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="Delete(scope.$index)">删除
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="车型" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.modelName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="车架号" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.vinNo }}</span>
                </template>
              </el-table-column>
              <el-table-column label="厂家结算价" prop="money" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.money }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
    </div>
    <!--End 添加修改部分-->
    <vehcile v-show="viewState == 2" ref="divVehicle" @backData="backData" @doback="closePage"/>
  </div>
</template>

<script>
import req from '@/api/anruifinmanagement/payment'
import {
  typeValues,
  getOrgSidByPath,
  fetchBySid,
  getGysByOrgSid,
  getListOrg,
  brandDown,
  selectNameByOrg
} from '@/api/jichuxinxi/dictcommons'
import vehcile from './relation/vehcile'
export default {
  name: 'fukuanshenqingAdd',
  components: {
    vehcile
  },
  data() {
    return {
      viewTitle: '',
      tableKey: 0,
      index: 0,
      vehicleKey: 1,
      viewState: 1,
      carBrand_list: [],
      costType_list: [],
      costTitle_list: [],
      payCompany_list: [],
      receiveCompany_list: [],
      payment_list: [],
      actualPay_list: [],
      formobj: {
        busSid: '',
        comment: '',
        costTitleKey: '',
        costTitleValue: '',
        costTypeKey: '',
        costTypeValue: '',
        createBySid: '',
        instanceId: '',
        name: '',
        payCompany: '',
        payCompanySid: '',
        receiveCompany: '',
        receiveCompanySid: '',
        remarks: '',
        sid: '',
        taskId: '',
        isVeh: '',
        carBrandName: '',
        carBrandSid: '',
        orgPath: '',
        detailsList: [],
        vehicleList: []
      },
      rules: {},
      submitdisabled: false
    }
  },
  methods: {
    newDate() {
      let date = new Date()
      let year = date.getFullYear() // 年
      let month = date.getMonth() + 1 // 月
      let day = date.getDate() // 日
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      this.formobj.createTime = year + '-' + month + '-' + day
    },
    UpNumberOne(e, row) {
      e.target.value = e.target.value.replace(/[^\d]/g, '') // 清除“数字”和“.”"-"以外的字符
      e.target.value = e.target.value.replace(/^00/, '0') // 开头不能有两个0
      if (e.target.value.indexOf('.') < 0 && e.target.value !== '' && e.target.value !== '-') {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        console.log(e.target.value)
        e.target.value = parseFloat(e.target.value)
      }
      row.payAccount = e.target.value
    },
    DataDictionary() {
      typeValues({ type: 'payCostType' }).then((res) => {
        if (res.success) {
          this.costType_list = res.data
        }
      })
      typeValues({ type: 'payCostTitle' }).then((res) => {
        if (res.success) {
          this.costTitle_list = res.data
        }
      })
      getListOrg().then((res) => {
        if (res.success) {
          this.payCompany_list = res.data
        }
      })
      typeValues({ type: 'paymentType' }).then((res) => {
        if (res.success) {
          this.payment_list = res.data
        }
      })
    },
    getPathSidByUserSid() {
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((response) => {
        if (response.success) {
          getGysByOrgSid({ orgSid: response.data }).then((resp) => {
            if (resp.success) {
              this.formobj.payCompanySid = response.data
              this.receiveCompany_list = resp.data
            }
          })
          fetchBySid(response.data).then((res) => {
            if (res.success) {
              this.formobj.payCompany = res.data.name
            }
          })
          brandDown({ useOrg: response.data }).then((res) => {
            if (res.success) {
              this.carBrand_list = res.data
            }
          })
        }
      })
    },
    showAdd() {
      this.newDate()
      this.DataDictionary()
      this.getPathSidByUserSid()
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.formobj.createBySid = window.sessionStorage.getItem('userSid')
      this.formobj.name = window.sessionStorage.getItem('name')
      this.formobj.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      this.viewTitle = '【新增】付款申请'
    },
    showEdit(row) {
      this.DataDictionary()
      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
      })
    },
    handleAdd() {
      if (this.formobj.carBrandName === '') {
        this.$message({ showClose: true, type: 'error', message: '请先选择品牌' })
        return
      }
      this.formobj.detailsList.push({
        actualPay: '',
        bank: '',
        payAccount: '',
        remarks: '',
        paymentType: '',
        paymentTypeKey: '',
        receivingAccount: ''
      })
    },
    handleDelete(index) {
      this.formobj.detailsList.splice(index, 1)
    },
    handleselect() {
      this.viewState = 2
      this.$refs['divVehicle'].showData(this.formobj.vehicleList)
    },
    Delete(index) {
      this.formobj.vehicleList.splice(index, 1)
    },
    // 车型常用配置列表--新增确定返回的数据
    backData(value) {
      this.viewState = 1
      if (value.length > 0) {
        value.forEach((e) => {
          this.formobj.vehicleList.push({
            vinNo: e.vinNo,
            vehiSid: e.vehiSid,
            modelName: e.modelName,
            modelSid: e.modelSid,
            money: e.money,
            configSid: e.configSid
          })
        })
      }
    },
    changeCarBrand(value) {
      let bb = null
      this.carBrand_list.forEach((e) => {
        if (e.brandName === value) {
          bb = {
            name: e.brandName,
            sid: e.sid
          }
        }
      })
      this.formobj.carBrandSid = bb.sid
      selectNameByOrg({ carBrandSid: this.formobj.carBrandSid }).then((res) => {
        if (res.success) {
          this.actualPay_list = res.data
        }
      })
    },
    changePaymentType(value, row) {
      let bb = null
      this.payment_list.forEach((e) => {
        if (e.dictValue === value) {
          bb = {
            value: e.dictValue,
            key: e.dictKey
          }
        }
      })
      row.paymentTypeKey = bb.key
    },
    changeActualPay(value, row) {
      let bb = null
      this.actualPay_list.forEach((e) => {
        if (e.actualPay === value) {
          bb = {
            actualPay: e.actualPay,
            bankAccount: e.bankAccount,
            depositBank: e.depositBank
          }
        }
      })
      row.actualPay = bb.actualPay
      row.bank = bb.depositBank
      row.receivingAccount = bb.bankAccount
    },
    changeCostType(value) {
      let bb = null
      this.costType_list.forEach((e) => {
        if (e.dictValue === value) {
          bb = {
            key: e.dictKey,
            value: e.dictValue
          }
        }
      })
      this.formobj.costTypeKey = bb.key
    },
    changeCostTitle(value) {
      let bb = null
      this.costTitle_list.forEach((e) => {
        if (e.dictValue === value) {
          bb = {
            key: e.dictKey,
            value: e.dictValue
          }
        }
      })
      this.formobj.costTitleKey = bb.key
    },
    changePayCompany(value) {
      let bb = null
      this.payCompany_list.forEach((e) => {
        if (e.name === value) {
          bb = {
            name: e.name,
            sid: e.sid
          }
        }
      })
      this.formobj.payCompanySid = bb.sid
    },
    changeReceiveCompany(value) {
      let bb = null
      this.receiveCompany_list.forEach((e) => {
        if (e.manufacturerName === value) {
          bb = {
            manufacturerName: e.manufacturerName,
            sid: e.sid
          }
        }
      })
      this.formobj.receiveCompanySid = bb.sid
    },
    saveOrUpdate() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.saveOrUpdate(this.formobj).then((resp) => {
            this.submitdisabled = false
            if (resp.success) {
              this.$message({
                showClose: true,
                type: 'success',
                message: resp.msg
              })
              this.handleReturn('true')
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        } else {
          return false
        }
      })
    },
    submitVehicleApply() {
      if (this.formobj.isVeh === '') {
        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) => {
            this.submitdisabled = false
            if (resp.success) {
              this.$message({
                showClose: true,
                type: 'success',
                message: resp.msg
              })
              this.handleReturn('true')
            }
          }).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.payAccountAll = 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.money = sums[index] += ''
        } else {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
            this.amount = sums[index] += ''
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {}
      this.$refs['form_obj'].resetFields()
      this.$emit('doback')
    },
    closePage() {
      this.viewState = 1
    }
  }
}
</script>

<style scoped>
.title {
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</style>
