<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="dialogStatus === 'add' ? saveAdd() : saveEdit()">保存
          </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="wlInfo"><span>排产申请</span></div>
        <el-form ref="form_obj" :model="formobj" :rules="rules" label-position="top">
          <el-row class="lineone">
            <el-col :span="3" class="el-form-item-right">
              <el-form-item label="申请编号:"></el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item>
                <el-input v-model="formobj.applicationCode" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="3" class="el-form-item-right">
              <el-form-item label="申请人:"></el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item>
                <el-input v-model="formobj.createByName" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="3" class="el-form-item-right">
              <el-form-item label="申请日期:"></el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item>
                <el-input v-model="formobj.applicationDate" readonly/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="linetwo">
            <el-col :span="3" class="el-form-item-right">
              <el-form-item label="排产类型:"></el-form-item>
            </el-col>
            <el-col :span="21">
              <el-form-item>
                <el-select v-model="formobj.schedulingType" placeholder="请选择" clearable>
                  <el-option v-for="item in schedulingType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="linethree">
            <el-col :span="3" class="el-form-item-right">
              <el-form-item label="备注:"></el-form-item>
            </el-col>
            <el-col :span="21">
              <el-form-item>
                <el-input v-model="formobj.remarks" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="tableStyle">
          <div style="margin-left: 5px;font-weight: bold">排产车型列表</div>
          <div style="margin-left: 15px">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="addCommodity()">添加</el-button>
          </div>
        </div>
        <el-table :key="tableKey" :data="formobj.busVehicleApplyDetailDtoList" :index="index" show-summary :summary-method="getSummaries" border style="width: 100%">
          <el-table-column fixed width="80px" label="序号" type="index" :index="index + 1" align="center"/>
          <el-table-column fixed prop="name" label="操作" width="80px" align="center" header-align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="dataDelete(scope.$index, formobj.busVehicleApplyDetailDtoList[scope.$index])">删除
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="车型" align="left" header-align="center" width="250">
            <template slot-scope="scope" prop="vehicleName">
              <span>{{ scope.row.vehicleName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="常用配置" align="left" header-align="center">
            <template slot-scope="scope" prop="configName">
              <span>{{ scope.row.configName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排产数量" header-align="center" width="130">
            <template slot-scope="scope" prop="quantity">
              <el-input v-model="scope.row.quantity" placeholder="" class="addinputw" clearable/>
            </template>
          </el-table-column>
          <el-table-column prop="useDeposit" label="使用订金" header-align="center" width="150">
            <template slot-scope="scope" prop="useDeposit">
              <el-input v-model="scope.row.useDeposit" placeholder="" class="addinputw" clearable/>
            </template>
          </el-table-column>
          <el-table-column prop="applyForDeposit" label="申请订金" header-align="center" width="150">
            <template slot-scope="scope" prop="applyForDeposit">
              <el-input v-model="scope.row.applyForDeposit" placeholder="" class="addinputw" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="销售指导价" header-align="center" width="150">
            <template slot-scope="scope" prop="saleGuPrice">
              <el-input v-model="scope.row.saleGuPrice" placeholder="" class="addinputw" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="备注" header-align="center" width="200">
            <template slot-scope="scope" prop="remarks">
              <el-input v-model="scope.row.remarks" placeholder="" class="addinputw" clearable/>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <div class="tableStyle">
            <div style="margin-left: 5px;font-weight: bold">订金使用情况</div>
          </div>
          <el-form ref="formobj" :model="formobj" label-width="130px" label-position="top" class="formadd">
            <el-row>
              <el-col :span="4" class="el-form-item-right">
                <el-form-item label="当前订金金额"></el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item>
                  <el-input v-model="formobj.currentAmount" placeholder="" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="4" class="el-form-item-right">
                <el-form-item label="本次需使用金额"></el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item>
                  {{ useMoney }}
                </el-form-item>
              </el-col>
              <el-col :span="4" class="el-form-item-right">
                <el-form-item label="本次申请金额"></el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item>
                  {{ applyMoney }}
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </div>
    <!--End 添加修改部分-->
    <!--选择车型和常用配置-->
    <configuration v-show="viewState == 2" ref="divconfiguration" @backData="backData" @doback="closePage"/>
  </div>
</template>

<script>
import req from '@/api/supplychain/busvehicleapply'
import configuration from './chexingbyconfiguration'
export default {
  name: 'cheliangpaichanAdd',
  components: {
    configuration
  },
  data() {
    return {
      viewTitle: '',
      dialogStatus: '',
      viewState: 1,
      index: 0,
      tableKey: 0,
      // 下拉框
      schedulingType_list: [], // 排产订金使用
      list1: [],
      useMoney: '', // 本次需使用金额
      applyMoney: '', // 本次申请金额
      // 表单数据
      formobj: {
        sid: '', // 一条数据的sid
        createBySid: window.sessionStorage.getItem('userSid'), // 用户人sid
        createByName: window.sessionStorage.getItem('name'), // 制单人
        applicationCode: '', // 申请编号
        applicationDate: '', // 申请日期
        schedulingType: '', // 排产类型
        remarks: '', // 备注
        currentAmount: '', // 当前订金金额
        busVehicleApplyDetailDtoList: []
      },
      rules: {},
      submitdisabled: false
    }
  },
  created() {
    this.getSchedulingType()
  },
  // computed: {
  //   sumUseDeposit() {
  //     console.log(88888)
  //     return this.formobj.busVehicleApplyDetailDtoList.map(row => row.useDeposit).reduce((acc,cur) => (parseFloat(cur) + acc),0)
  //   }
  // },
  methods: {
    // 下拉框-排产类型
    getSchedulingType() {
      req.pullDown({ type: 'schedulingType' }).then((res) => {
        if (res.code == '200') {
          this.schedulingType_list = res.data
          console.log('下拉框请求111', res.data)
        }
      })
    },
    // 明细表添加一行数据
    addCommodity() {
      this.viewState = 2
      this.$refs['divconfiguration'].showData(this.list1)
    },
    // 明细表删除一行数据
    dataDelete(index, row) {
      this.formobj.busVehicleApplyDetailDtoList.splice(index, 1)
      this.list1.splice(index, 1)
    },
    showAdd() {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.dialogStatus = 'add'
      this.viewTitle = '【新增】排产申请'
    },
    showEdit(sid, row) {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.dialogStatus = 'edit'
      this.viewTitle = '【编辑】排产申请'
      console.log('编辑回显', sid)
      req.fetchBySid(sid).then((resp) => {
        const data = resp.data
        this.formobj.applicationCode = data.applicationCode
        this.formobj.applicationDate = data.applicationDate
        this.formobj.schedulingType = data.schedulingType
        this.formobj.remarks = data.remarks
        this.formobj.currentAmount = data.currentAmount
        this.formobj.sid = sid
        this.formobj.busVehicleApplyDetailDtoList = data.busVehicleApplyDetailVoList
        this.list1 = data.busVehicleApplyDetailVoList
      }).catch((e) => {
        this.formobj = row
      })
    },
    // 车型常用配置列表--新增确定返回的数据
    backData(value) {
      this.viewState = 1
      // this.formobj.busVehicleApplyDetailDtoList = []
      if (this.formobj.busVehicleApplyDetailDtoList.length > 0) {
        for (var i = 0; i < value.length; i++) {
          for (var u = 0; u < this.formobj.busVehicleApplyDetailDtoList.length; u++) {
            if (value[i].modelName == this.formobj.busVehicleApplyDetailDtoList[u].vehicleName && value[i].configName == this.formobj.busVehicleApplyDetailDtoList[u].configName) {
              value.splice(value[i], 1)
            }
          }
        }
      }
      if (value.length > 0) {
        value.forEach((e) => {
          this.formobj.busVehicleApplyDetailDtoList.push({
            quantity: '',
            applySid: '',
            configSid: e.configurationItemsSid,
            configName: e.configName,
            useDeposit: '',
            applyForDeposit: '',
            remarks: '',
            saleGuPrice: '',
            vehicleName: e.modelName,
            vehicleSid: e.modelSid
          })
        })
        this.list1 = this.formobj.busVehicleApplyDetailDtoList
      }
    },
    saveAdd() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.saveAdd(this.formobj).then((resp) => {
            this.submitdisabled = false
            if (resp.code == '200') {
              this.$message({
                showClose: true,
                type: 'success',
                message: resp.msg
              })
              this.handleReturn('true')
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        } else {
          return false
        }
      })
    },
    saveEdit() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.saveEdit(this.formobj).then((resp) => {
              this.submitdisabled = false
              this.$message({
                showClose: true,
                type: 'success',
                message: resp.msg
              })
              this.handleReturn('true')
            }).catch(() => {
              this.submitdisabled = false
            })
        } else {
          return false
        }
      })
    },
    submitVehicleApply() {
      req.submitVehicleApply(this.formobj).then((res) => {
        if (res.code == '200') {
          this.$message({
            showClose: true,
            type: 'success',
            message: '提交成功'
          })
          this.handleReturn('true')
        } else {
          this.$message({
            showClose: true,
            type: 'error',
            message: '提交失败'
          })
        }
      })
    },
    // 返回（===既判断又赋值）
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj.schedulingType = '' // 排产类型
      this.formobj.remarks = '' // 备注
      this.formobj.currentAmount = ''
      this.formobj.applicationCode = ''
      this.formobj.applicationDate = ''
      this.formobj.busVehicleApplyDetailDtoList = []
      this.list1 = []
      this.$refs['form_obj'].resetFields()
      this.$refs['divconfiguration'].getList()
      this.$emit('doback')
    },
    // 合计
    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 === 'useDeposit') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
          this.useMoney = sums[index] += ''
        } else if (column.property === 'applyForDeposit') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
          this.applyMoney = 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
    },
    closePage() {
      this.viewState = 1
    }
  }
}
</script>

<style scoped>
.wlInfo {
  text-align: center;
  font-size: 28px;
  line-height: 90px;
}
.lineone {
  border-bottom: 2px solid #e0e3eb;
}
.lineone .el-form-item {
  margin-bottom: -10px;
}
.lineone >>> .el-input__inner {
  border: 0;
}
.linetwo {
  margin-top: 10px;
}
.linetwo .el-form-item {
  margin-bottom: 0px !important;
}
.linethree .el-form-item {
  margin-bottom: 0px !important;
}
.tableStyle {
  background-color: #FFFFFF;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border: 1px solid #dfe4ed;
  height: 40px;
}
.el-form-item-right {
  /* padding: 0 10px 0 0; */
  text-align: right;
}
.formadd{
  padding: 0px !important;
}
.icon {
  color: #e84026;
  margin-right: 4px;
}
</style>

