<template>
  <div class="app-container">
    <div v-show="viewState== 1">
      <!--标题按钮部分开始-->
      <div class="tab-header webtop">
        <!--标题-->
        <div>{{ viewTitle }}</div>
        <!--start 添加修改按钮-->
        <div>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="save()">保存
          </el-button>
          <el-button type="primary" size="small" @click="submitVehicleApply()">提交
          </el-button>
          <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
        </div>
      </div>
      <!--标题按钮部分结束-->
      <!--Start 新增修改部分-->
      <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="4">
              <el-form-item><span>{{ formobj.useOrgName }}</span></el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span>申请人</span>
            </el-col>
            <el-col :span="4">
              <el-form-item><span>{{ formobj.applicationName }}</span></el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span>申请日期</span>
            </el-col>
            <el-col :span="4">
              <el-form-item><span>{{ formobj.createTime }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="tleftb">
              <span>买断原因</span>
            </el-col>
            <el-col :span="12">
              <el-form-item><el-input v-model="formobj.reason" type="textarea" :autosize="{ minRows: 1, maxRows: 10}" resize="none" clearable placeholder="" class="addinputw"></el-input></el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span>是否需要付款</span>
            </el-col>
            <el-col :span="4">
              <el-form-item>
                <el-radio v-model="formobj.isPay" label="1">是</el-radio>
                <el-radio v-model="formobj.isPay" 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="addCommodity()">选择车辆</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="dataDelete(scope.$index)">删除
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="车架号" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.vinNo }}</span>
              </template>
            </el-table-column>
            <el-table-column label="车型" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.modelName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="版本" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.vehicleVersionValue }}</span>
              </template>
            </el-table-column>
            <el-table-column label="燃料" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.fuelTypeValue }}</span>
              </template>
            </el-table-column>
            <el-table-column label="变速箱" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.gearboxTypeValue }}</span>
              </template>
            </el-table-column>
            <el-table-column label="排放标准" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.emissionStandardValue }}</span>
              </template>
            </el-table-column>
            <el-table-column label="厂家入库日期" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.inboundDate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库龄(天)" align="center" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.dayNum }}</span>
              </template>
            </el-table-column>
            <el-table-column label="内部编码" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.insideCode }}<span>({{ scope.row.vehicleNum }})</span></span>
              </template>
            </el-table-column>
            <el-table-column label="厂家结算价" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.inboundPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="actualMoney" label="买断金额" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.actualMoney" placeholder="" clearable @keyup.native="UpNumber($event, scope.row)" @keydown.native="UpNumber($event, scope.row)"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <div v-show="formobj.isPay == '1'">
            <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="paymentKey" :data="formobj.detailsPayList" :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.payRemark" placeholder="" clearable></el-input>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
    </div>
    <!--End 添加修改部分-->
    <!--选择车型和常用配置-->
    <vehicle v-show="viewState == 2" ref="divVehicle" @backData="backData" @doback="closePage"/>
  </div>
</template>

<script>
import req from '@/api/weishoumaiduan/unsold'
import vehicle from './vehicle.vue'
import { getPathSidByUserSid, fetchBySid, typeValues } from '@/api/cheliang/dictcommons'

export default {
  name: 'weishoumaiduanAdd',
  components: {
    vehicle
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      index: 0,
      tableKey: 0,
      paymentKey: 1,
      payment_list: [],
      actualPay_list: [],
      // 表单数据
      formobj: {
        sid: '', // 一条数据的sid
        applicationName: '',
        isPay: '',
        payAccountAll: '',
        useOrgName: '',
        useOrgSid: '',
        money: '',
        createTime: '',
        reason: '',
        userSid: '',
        instanceId: '', // 流程实例ID
        taskId: '', // 任务ID
        detailsList: [],
        detailsPayList: []
      },
      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
    },
    init() {
      typeValues({ type: 'paymentType' }).then((res) => {
        if (res.success) {
          this.payment_list = res.data
        }
      })
      getPathSidByUserSid({ userSid: window.sessionStorage.getItem('userSid') }).then((resp) => {
        if (resp.success) {
          this.formobj.useOrgSid = resp.data
          fetchBySid(resp.data).then((res) => {
            if (res.success) {
              this.formobj.useOrgName = res.data.name
            }
          })
          req.actualList().then((respsone) => {
            if (respsone.success) {
              this.actualPay_list = respsone.data
            }
          })
        }
      })
    },
    UpNumber(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.actualMoney = e.target.value
    },
    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
    },
    // 明细表添加一行数据
    addCommodity() {
      this.viewState = 2
      this.$refs['divVehicle'].showData(this.formobj.detailsList)
    },
    // 明细表删除一行数据
    dataDelete(index) {
      this.formobj.detailsList.splice(index, 1)
    },
    handleAdd() {
      this.formobj.detailsPayList.push({
        actualPay: '',
        bank: '',
        payAccount: '',
        payRemark: '',
        paymentType: '',
        paymentTypeKey: '',
        receivingAccount: ''
      })
    },
    handleDelete(index) {
      this.formobj.detailsPayList.splice(index, 1)
    },
    showAdd() {
      this.newDate()
      this.init()
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.formobj.applicationName = window.sessionStorage.getItem('name')
      this.formobj.userSid = window.sessionStorage.getItem('userSid')
      this.viewTitle = '【新增】车辆未售买断申请'
    },
    showEdit(row) {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.viewTitle = '【编辑】车辆未售买断申请'
      console.log('编辑回显', row.sid)
      req.fetchBySid(row.sid).then((resp) => {
        this.formobj = resp.data
        this.formobj.instanceId = resp.data.procInstId
      }).catch((e) => {
        this.formobj = row
      })
    },
    // 车型常用配置列表--新增确定返回的数据
    backData(value) {
      this.viewState = 1
      if (value.length > 0) {
        value.forEach((e) => {
          this.formobj.detailsList.push({
            inboundDate: e.priceDate,
            inboundPrice: e.priced,
            modelName: e.vehicleAlias,
            vinNo: e.vinNo,
            insideCode: e.insideCode,
            vehicleNum: e.vehicleNum,
            dayNum: e.dayNum,
            vehicleVersionValue: e.vehicleVersionValue,
            fuelTypeValue: e.fuelTypeValue,
            gearboxTypeValue: e.gearboxTypeValue,
            emissionStandardValue: e.emissionStandardValue,
            actualMoney: e.priced
          })
        })
      }
    },
    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
    },
    save() {
      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.isPay == '1' && this.formobj.payAccountAll !== this.formobj.money) {
        this.$message({ showClose:true, type: 'error', message: '因买断金额合计与付款金额合计不一致，提交失败' })
        return
      }
      req.submitVehicleApply(this.formobj).then((res) => {
        if (res.success) {
          this.$message({
            showClose: true,
            type: 'success',
            message: '提交成功'
          })
          this.handleReturn('true')
        } else {
          this.$message({
            showClose: true,
            type: 'error',
            message: '提交失败'
          })
        }
      })
    },
    // 合计
    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 === 'actualMoney') {
          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 = {
        sid: '', // 一条数据的sid
        applicationName: '',
        isPay: '',
        payAccountAll: '',
        useOrgName: '',
        useOrgSid: '',
        money: '',
        createTime: '',
        reason: '',
        userSid: '',
        instanceId: '', // 流程实例ID
        taskId: '', // 任务ID
        detailsList: [],
        detailsPayList: []
      }
      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>

