<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" :disabled="submitdisabled" @click="submit()">提交
          </el-button>
        </div>
      </div>
      <!--标题按钮部分结束-->
      <!--Start 新增修改部分-->
      <div class="">
        <div class="titwu"><span>{{ formobj.checkApply }}单车返利核对审核申请</span></div>
        <el-form ref="form_obj" :model="formobj" :rules="rules" class="formadd">
          <el-row class="rowStyle">
            <el-col :span="2" class="tleftb colOneStyle">
              <span>品牌:</span>
            </el-col>
            <el-col :span="4" class="colOneStyle">
              <el-form-item>
                <el-select :disabled="dialogStatus === 'edit'" v-model="formobj.brandName" placeholder="请选择" filterable clearable @change="changeBrand">
                  <el-option v-for="item in brand_list" :key="item.sid" :label="item.brandName" :value="item.brandName"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="18" class="tleftb colOneStyle">
              <el-button size="small" type="primary" @click="handleSelect()">添加</el-button>
            </el-col>
          </el-row>
          <div class="title">
            <div>本月各项返利核对情况</div>
          </div>
          <el-table :key="tableKey" :data="formobj.scmWhenVehrebateCheckapplydetailDetails" :index="index" border style="width: 100%">
            <el-table-column fixed width="80px" label="序号" type="index" :index="index + 1" align="center"/>
            <el-table-column label="返利类型" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.rebateTypeValue }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.num }}</span>
              </template>
            </el-table-column>
            <el-table-column label="预提金额" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.withRebate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="上传金额" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.uploadMoney }}</span>
              </template>
            </el-table-column>
            <el-table-column label="待确认金额" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stayDetermineMoney }}</span>
              </template>
            </el-table-column>
            <el-table-column label="调整金额" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.adjustmentMoney }}</span>
              </template>
            </el-table-column>
            <el-table-column label="费用" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.money }}</span>
              </template>
            </el-table-column>
            <el-table-column label="明细" align="center">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="handleLook(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="divStyle">
            <div>预提返利本月核对情况</div>
            <el-button type="primary" size="mini" class="btntopblueline" @click="handleCheck">往月核对情况</el-button>
          </div>
          <el-table :key="lastVehrebateKey" :data="formobj.scmLastVehrebateCheckapplydetailDetails" border style="width: 100%">
            <el-table-column label="预提年月" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.withholdingDate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="预提数量" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.withholdingAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="预提金额" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.withRebate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="上传数量" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.uploadAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="上传金额" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.uploadMoney }}</span>
              </template>
            </el-table-column>
            <el-table-column label="待确认金额" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stayDetermineMoney }}</span>
              </template>
            </el-table-column>
            <el-table-column label="调整金额" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.adjustmentMoney }}</span>
              </template>
            </el-table-column>
            <el-table-column label="费用" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.money }}</span>
              </template>
            </el-table-column>
            <el-table-column label="未上传数量" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.notUploadedAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="未上传金额" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.notUploadedCost }}</span>
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <el-col :span="2" class="tleftb">
              <span>备注</span>
            </el-col>
            <el-col :span="22">
              <el-form-item><el-input v-model="formobj.remarks" placeholder="" class="addinputw" clearable></el-input></el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!--End 添加修改部分-->
    <yiheduidanchefanli v-show="viewState == 2" ref="divSelect" @backData="backData" @doback="resetState"/>
    <bicyclerebatetobecheckedAdd v-show="viewState == 3" ref="divAdd" @backAdd="backAdd" @doback="resetState"/>
    <el-dialog :visible.sync="dialogVisible" width="60%">
      <div class="titwu"><span>往月核对情况</span></div>
      <el-form class="formadd">
        <el-row style="border-top: 1px solid #E0E3EB">
          <el-col :span="3" class="tleftb">
            <span>月促政策</span>
          </el-col>
          <el-col :span="21">
            <el-form-item><span>{{ summation }}</span></el-form-item>
          </el-col>
        </el-row>
        <el-table :key="checkKey" :data="checkList" border width="100%">
          <el-table-column label="计提月份" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.month }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计提" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.month }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上传" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.month }}</span>
            </template>
          </el-table-column>
          <el-table-column label="未上传" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.month }}</span>
            </template>
          </el-table-column>
          <el-table-column label="调整" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.month }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import req from '@/api/bikerebate/bicyclerebatecheck'
import { fetchBySid, brandDown } from '@/api/cheliang/dictcommons'
import yiheduidanchefanli from './relation/yiheduidanchefanli'
import bicyclerebatetobecheckedAdd from './relation/bicyclerebatetobecheckedAdd'

export default {
  name: 'DanCheFanLiHeDuiEdit',
  components: {
    yiheduidanchefanli,
    bicyclerebatetobecheckedAdd
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      index: 0,
      tableKey: 0,
      lastVehrebateKey: 1,
      checkKey: 2,
      dialogVisible: false,
      summation: '',
      checkList: [],
      dialogStatus: '',
      brand_list: [],
      // 表单数据
      formobj: {
        sid: '',
        createByName: '',
        brandName: '',
        brandSid: '',
        checkApply: '',
        createOrgName: '',
        createOrgSid: '',
        useOrgName: '',
        useOrgSid: '',
        remarks: '',
        instanceId: '', // 流程实例ID
        taskId: '', // 任务ID
        orgPath: '',
        scmWhenVehrebateCheckapplydetailDetails: [],
        scmLastVehrebateCheckapplydetailDetails: []
      },
      rules: {},
      submitdisabled: false
    }
  },
  created() {
    console.log('url:' + window.location.href)
    var one = window.location.href.indexOf('&data') + 6
    const data = window.location.href.substr(one) // url解码unescape()已从web中移除,尽量不使用
    const obj = JSON.parse(decodeURIComponent(data))
    this.showInfo(obj.businessSid)
  },
  mounted() {
    window.parent.postMessage({
      cmd: 'returnHeight',
      params: {
        // 告诉父级页面，子页面的弹框高度。
        code: 2,
        data: 450 + 'px'
      }
    }, '*')
  },
  methods: {
    init() {
      fetchBySid(this.formobj.createOrgSid).then((res) => {
        if (res.success) {
          this.formobj.createOrgName = res.data.name
          this.formobj.useOrgName = res.data.name
        }
      })
      brandDown({ useOrg: this.formobj.createOrgSid }).then((res) => {
        if (res.success) {
          this.brand_list = res.data
        }
      })
    },
    showInfo(sid) {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.dialogStatus = 'edit'
      this.viewTitle = '【编辑】单车返利核对审核申请'
      console.log('编辑回显', sid)
      req.fetchDetailsBySid(sid).then((resp) => {
        this.formobj = resp.data
        this.formobj.instanceId = resp.data.procInstId
      }).catch((e) => {
        this.formobj = {}
      })
    },
    changeBrand(value) {
      let bb = null
      this.brand_list.forEach((e) => {
        if (e.brandName === value) {
          bb = {
            name: e.brandName,
            sid: e.sid
          }
        }
      })
      this.formobj.brandSid = bb.sid
    },
    // 明细表添加一行数据
    handleSelect() {
      if (this.formobj.brandName === '' || this.formobj.brandName === null || this.formobj.brandName === undefined) {
        this.$message({ showClose: true, type: 'error', message: '请先选择品牌' })
        return
      }
      this.viewState = 2
      this.$refs['divSelect'].showData(this.formobj.scmWhenVehrebateCheckapplydetailDetails, this.formobj.scmLastVehrebateCheckapplydetailDetails, this.formobj.createOrgSid, this.formobj.brandSid)
    },
    backData(value, val) {
      this.viewState = 1
      if (value.length > 0) {
        for (var i in value) {
          let cval = value[i]
          if (!this.formobj.scmWhenVehrebateCheckapplydetailDetails || this.formobj.scmWhenVehrebateCheckapplydetailDetails.length === 0) {
            this.formobj.scmWhenVehrebateCheckapplydetailDetails = []
          }
          let v = 0
          for (var j in this.formobj.scmWhenVehrebateCheckapplydetailDetails) {
            if (this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].rebateTypeValue === cval.rebateTypeValue) {
              this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].num = parseInt(this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].num) + parseInt(1)
              this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].withRebate = parseInt(this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].withRebate) + parseInt(cval.withRebate)
              this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].uploadMoney = parseInt(this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].uploadMoney) + parseInt(cval.uploadMoney)
              this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].stayDetermineMoney = parseInt(this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].stayDetermineMoney) + parseInt(cval.stayDetermineMoney)
              this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].adjustmentMoney = parseInt(this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].adjustmentMoney) + parseInt(cval.adjustmentMoney)
              this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].money = parseInt(this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].money) + parseInt(cval.money)
              this.formobj.scmWhenVehrebateCheckapplydetailDetails[j].vehRebateSids.push(cval.sid)
              v = 1
              break
            }
          }
          if (v === 0) {
            this.formobj.scmWhenVehrebateCheckapplydetailDetails.push({
              rebateTypeKey: cval.rebateTypeKey,
              rebateTypeValue: cval.rebateTypeValue,
              num: 1,
              withRebate: cval.withRebate,
              brandName: cval.brandName,
              brandSid: cval.brandSid,
              uploadMoney: cval.uploadMoney,
              stayDetermineMoney: cval.stayDetermineMoney,
              adjustmentMoney: cval.adjustmentMoney,
              money: cval.money,
              vehRebateSids: [cval.sid],
              sid: '',
              mainSid: ''
            })
          }
        }
      }
      if (val.length > 0) {
        for (var p in val) {
          let bval = val[p]
          if (!this.formobj.scmLastVehrebateCheckapplydetailDetails || this.formobj.scmLastVehrebateCheckapplydetailDetails.length === 0) {
            this.formobj.scmLastVehrebateCheckapplydetailDetails = []
          }
          let v = 0
          for (var l in this.formobj.scmLastVehrebateCheckapplydetailDetails) {
            if (this.formobj.scmLastVehrebateCheckapplydetailDetails[l].withholdingDate === bval.withholdingDate) {
              this.formobj.scmLastVehrebateCheckapplydetailDetails[l].withholdingAmount = parseInt(this.formobj.scmLastVehrebateCheckapplydetailDetails[l].withholdingAmount) + parseInt(1)
              this.formobj.scmLastVehrebateCheckapplydetailDetails[l].uploadAmount = parseInt(this.formobj.scmLastVehrebateCheckapplydetailDetails[l].uploadAmount) + parseInt(1)
              this.formobj.scmLastVehrebateCheckapplydetailDetails[l].withRebate = parseInt(this.formobj.scmLastVehrebateCheckapplydetailDetails[l].withRebate) + parseInt(bval.withRebate)
              this.formobj.scmLastVehrebateCheckapplydetailDetails[l].uploadMoney = parseInt(this.formobj.scmLastVehrebateCheckapplydetailDetails[l].uploadMoney) + parseInt(bval.uploadMoney)
              this.formobj.scmLastVehrebateCheckapplydetailDetails[l].stayDetermineMoney = parseInt(this.formobj.scmLastVehrebateCheckapplydetailDetails[l].stayDetermineMoney) + parseInt(bval.stayDetermineMoney)
              this.formobj.scmLastVehrebateCheckapplydetailDetails[l].adjustmentMoney = parseInt(this.formobj.scmLastVehrebateCheckapplydetailDetails[l].adjustmentMoney) + parseInt(bval.adjustmentMoney)
              this.formobj.scmLastVehrebateCheckapplydetailDetails[l].money = parseInt(this.formobj.scmLastVehrebateCheckapplydetailDetails[l].money) + parseInt(bval.money)
              this.formobj.scmLastVehrebateCheckapplydetailDetails[l].vehRebateSids.push(bval.sid)
              v = 1
              break
            }
          }
          if (v === 0) {
            this.formobj.scmLastVehrebateCheckapplydetailDetails.push({
              withholdingDate: bval.withholdingDate,
              withholdingAmount: 1,
              uploadAmount: 1,
              withRebate: bval.withRebate,
              uploadMoney: bval.uploadMoney,
              stayDetermineMoney: bval.stayDetermineMoney,
              adjustmentMoney: bval.adjustmentMoney,
              money: bval.money,
              notUploadedAmount: '',
              notUploadedCost: '',
              vehRebateSids: [bval.sid],
              sid: '',
              mainSid: ''
            })
          }
        }
      }
    },
    // 明细表删除一行数据
    dataDelete(index) {
      this.formobj.baseVehinstallModpricedetails.splice(index, 1)
    },
    handleLook(row) {
      this.viewState = 3
      this.$refs['divAdd'].showInfo(row)
    },
    backAdd(value, rebateType) {
      this.viewState = 1
      const aa = []
      if (value.length > 0) {
        for (var i in value) {
          let cval = value[i]
          let v = 0
          for (var j in aa) {
            if (aa[j].rebateTypeValue === cval.rebateTypeValue) {
              aa[j].num = parseInt(aa[j].num) + parseInt(1)
              aa[j].withRebate = parseInt(aa[j].withRebate) + parseInt(cval.withRebate)
              aa[j].uploadMoney = parseInt(aa[j].uploadMoney) + parseInt(cval.uploadMoney)
              aa[j].stayDetermineMoney = parseInt(aa[j].stayDetermineMoney) + parseInt(cval.stayDetermineMoney)
              aa[j].adjustmentMoney = parseInt(aa[j].adjustmentMoney) + parseInt(cval.adjustmentMoney)
              aa[j].money = parseInt(aa[j].money) + parseInt(cval.money)
              aa[j].vehRebateSids.push(cval.sid)
              v = 1
              break
            }
          }
          if (v === 0) {
            aa.push({
              rebateTypeKey: cval.rebateTypeKey,
              rebateTypeValue: cval.rebateTypeValue,
              num: 1,
              withRebate: cval.withRebate,
              brandName: cval.brandName,
              brandSid: cval.brandSid,
              uploadMoney: cval.uploadMoney,
              stayDetermineMoney: cval.stayDetermineMoney,
              adjustmentMoney: cval.adjustmentMoney,
              money: cval.money,
              vehRebateSids: [cval.sid],
              sid: '',
              mainSid: ''
            })
          }
        }
        for (var k = 0; k < this.formobj.scmWhenVehrebateCheckapplydetailDetails.length; k++) {
          if (this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].rebateTypeValue === rebateType) {
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].rebateTypeKey = aa[0].rebateTypeKey
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].rebateTypeValue = aa[0].rebateTypeValue
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].num = aa[0].num
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].withRebate = aa[0].withRebate
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].brandName = aa[0].brandName
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].brandSid = aa[0].brandSid
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].uploadMoney = aa[0].uploadMoney
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].stayDetermineMoney = aa[0].stayDetermineMoney
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].adjustmentMoney = aa[0].adjustmentMoney
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].money = aa[0].money
            this.formobj.scmWhenVehrebateCheckapplydetailDetails[k].vehRebateSids = aa[0].vehRebateSids
            break
          }
        }
      } else if (value.length === 0) {
        for (var l = 0; l < this.formobj.scmWhenVehrebateCheckapplydetailDetails.length; l++) {
          if (this.formobj.scmWhenVehrebateCheckapplydetailDetails[l].rebateTypeValue === rebateType) {
            this.formobj.scmWhenVehrebateCheckapplydetailDetails.splice(l, 1)
            break
          }
        }
      }
    },
    resetState() {
      this.viewState = 1
    },
    handleCheck() {
      this.dialogVisible = true
    },
    save() {
      console.log(this.formobj)
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.save(this.formobj).then((resp) => {
            this.submitdisabled = false
            if (resp.success) {
              this.$message({
                showClose: true,
                type: 'success',
                message: resp.msg
              })
              // 子页面向父级页面传递值(关闭弹框)
              window.parent.postMessage({
                cmd: 'returnHeight',
                params: {
                  // 操作成功，告诉父级页面关闭弹框
                  code: 1
                }
              }, '*')
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        } else {
          return false
        }
      })
    },
    submit() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.submitVehicleApply(this.formobj).then((resp) => {
            this.submitdisabled = false
            if (resp.success) {
              this.$message({
                showClose: true,
                type: 'success',
                message: resp.msg
              })
              // 子页面向父级页面传递值(关闭弹框)
              window.parent.postMessage({
                cmd: 'returnHeight',
                params: {
                  // 操作成功，告诉父级页面关闭弹框
                  code: 1
                }
              }, '*')
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style scoped>
.divStyle {
  padding: 7px;
  font-weight: bold;
  font-size: 16px;
  background-color: #0294d7;
  color: #ffffff;
  text-align: left;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.titwu {
  font-size: 28px;
  text-align: center;
  padding: 30px 0 20px 0;
}
.rowStyle {
  border-left: 0px;
}
.colOneStyle {
  border-right: 0px !important;
  border-bottom: 0px !important;
}
</style>

