<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.collectionApply }}回款返利预提申请</span></div>
        <el-form ref="form_obj" :model="formobj" :rules="rules" class="formadd">
          <el-row class="rowStyle">
            <el-col :span="24" class="tleftb colOneStyle">
              <div><span style="font-size: 16px">金额单位：元</span></div>
            </el-col>
          </el-row>
          <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>
          <el-table :key="tableKey" :data="formobj.scmCollectionRebateWiths" :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 label="回款方式" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.collectionTypeValue }}</span>
              </template>
            </el-table-column>
            <el-table-column label="回款金额" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.collectionMoney }}</span>
              </template>
            </el-table-column>
            <el-table-column label="运费" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.freight }}</span>
              </template>
            </el-table-column>
            <el-table-column label="计算标准" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.calculationStandard }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="estimateRebate" label="预计返利" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.estimateRebate }}</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>
          <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" clearable placeholder="" class="addinputw"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!--End 添加修改部分-->
    <huikuanfanliselect v-show="viewState == 2" ref="divSelect" @doback="resetState" @backData="backData"/>
    <huikuanfanliAdd v-show="viewState == 3" ref="divAdd" @backAdd="backAdd" />
  </div>
</template>

<script>
import req from '@/api/manufacturerrebates/collectionrebatewithholding'
import { brandDown } from '@/api/cheliang/dictcommons'
import huikuanfanliselect from './relation/huikuanfanliselect'
import huikuanfanliAdd from './relation/huikuanfanliAdd'

export default {
  name: 'HuiKuanFanLiYuTiEdit',
  components: {
    huikuanfanliselect,
    huikuanfanliAdd
  },
  data() {
    return {
      viewTitle: '',
      index: 0,
      tableKey: 0,
      viewState: 1,
      dialogStatus: '',
      brand_list: [],
      // 表单数据
      formobj: {
        sid: '',
        brandName: '',
        brandSid: '',
        collectionApply: '',
        createOrgName: '',
        createOrgSId: '',
        useOrgName: '',
        useOrgSid: '',
        remarks: '',
        withRebateTotal: '',
        createByName: '',
        createBySid: '',
        instanceId: '', // 流程实例ID
        taskId: '', // 任务ID
        orgPath: '',
        scmCollectionRebateWiths: []
      },
      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: 390 + 'px'
      }
    }, '*')
  },
  methods: {
    init() {
      brandDown({ useOrg: this.formobj.createOrgSid }).then((res) => {
        if (res.success) {
          this.brand_list = res.data
        }
      })
    },
    // 获取日期
    newDate() {
      let date = new Date()
      let year = date.getFullYear() // 年
      let month = date.getMonth() + 1 // 月
      this.formobj.collectionApply = year + '年' + month + '月'
    },
    showInfo(sid) {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.dialogStatus = 'edit'
      this.viewTitle = '【编辑】回款返利预提申请'
      console.log('编辑回显', sid)
      req.fetchBySid(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.scmCollectionRebateWiths, this.formobj.createOrgSid, this.formobj.brandSid)
    },
    // 列表--选择返回数据
    backData(value) {
      this.viewState = 1
      for (var i in value) {
        let cval = value[i]
        if (!this.formobj.scmCollectionRebateWiths || this.formobj.scmCollectionRebateWiths.length === 0) {
          this.formobj.scmCollectionRebateWiths = []
        }
        let v = 0
        for (var j in this.formobj.scmCollectionRebateWiths) {
          if (this.formobj.scmCollectionRebateWiths[j].collectionTypeValue === cval.collectionTypeValue) {
            this.formobj.scmCollectionRebateWiths[j].collectionMoney = parseInt(this.formobj.scmCollectionRebateWiths[j].collectionMoney) + parseInt(cval.collectionMoney)
            this.formobj.scmCollectionRebateWiths[j].freight = parseInt(this.formobj.scmCollectionRebateWiths[j].freight) + parseInt(cval.freight)
            this.formobj.scmCollectionRebateWiths[j].estimateRebate = parseInt(this.formobj.scmCollectionRebateWiths[j].estimateRebate) + parseInt(cval.estimateRebate)
            this.formobj.scmCollectionRebateWiths[j].collectionRebateSids.push(cval.sid)
            v = 1
            break
          }
        }
        if (v === 0) {
          this.formobj.scmCollectionRebateWiths.push({
            collectionTypeKey: cval.collectionTypeKey,
            collectionTypeValue: cval.collectionTypeValue,
            collectionMoney: cval.collectionMoney,
            freight: cval.freight,
            calculationStandard: cval.calculationStandard,
            estimateRebate: cval.estimateRebate,
            brandName: cval.brandName,
            brandSid: cval.brandSid,
            collectionRebateSids: [cval.sid],
            sid: '',
            mainSid: ''
          })
        }
      }
    },
    // 明细--查看
    handleLook(row) {
      this.viewState = 3
      this.$refs['divAdd'].showInfo(row)
    },
    // 明细--查看返回数据
    backAdd(value, collectionTypeValue) {
      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].collectionTypeValue === cval.collectionTypeValue) {
              aa[j].collectionMoney = parseInt(aa[j].collectionMoney) + parseInt(cval.collectionMoney)
              aa[j].freight = parseInt(aa[j].freight) + parseInt(cval.freight)
              aa[j].estimateRebate = parseInt(aa[j].estimateRebate) + parseInt(cval.estimateRebate)
              aa[j].collectionRebateSids.push(cval.sid)
              v = 1
              break
            }
          }
          if (v === 0) {
            aa.push({
              collectionTypeKey: cval.collectionTypeKey,
              collectionTypeValue: cval.collectionTypeValue,
              collectionMoney: cval.collectionMoney,
              freight: cval.freight,
              calculationStandard: cval.calculationStandard,
              estimateRebate: cval.estimateRebate,
              brandName: cval.brandName,
              brandSid: cval.brandSid,
              collectionRebateSids: [cval.sid],
              sid: '',
              mainSid: ''
            })
          }
        }
        for (var k = 0; k < this.formobj.scmCollectionRebateWiths.length; k++) {
          if (this.formobj.scmCollectionRebateWiths[k].collectionTypeValue === collectionTypeValue) {
            this.formobj.scmCollectionRebateWiths[k].collectionTypeKey = aa[0].collectionTypeKey
            this.formobj.scmCollectionRebateWiths[k].collectionTypeValue = aa[0].collectionTypeValue
            this.formobj.scmCollectionRebateWiths[k].collectionMoney = aa[0].collectionMoney
            this.formobj.scmCollectionRebateWiths[k].estimateRebate = aa[0].estimateRebate
            this.formobj.scmCollectionRebateWiths[k].freight = aa[0].freight
            this.formobj.scmCollectionRebateWiths[k].calculationStandard = aa[0].calculationStandard
            this.formobj.scmCollectionRebateWiths[k].brandName = aa[0].brandName
            this.formobj.scmCollectionRebateWiths[k].brandSid = aa[0].brandSid
            this.formobj.scmCollectionRebateWiths[k].vehRebateSids = aa[0].vehRebateSids
            break
          }
        }
      } else if (value.length === 0) {
        for (var l = 0; l < this.formobj.scmCollectionRebateWiths.length; l++) {
          if (this.formobj.scmCollectionRebateWiths[l].collectionTypeValue === collectionTypeValue) {
            this.formobj.scmCollectionRebateWiths.splice(l, 1)
            break
          }
        }
      }
    },
    resetState() {
      this.viewState = 1
    },
    save() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.save(this.formobj).then((resp) => {
            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) => {
            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
        }
      })
    },
    // 合计
    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 === 'estimateRebate') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
          this.formobj.withRebateTotal = 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
    }
  }
}
</script>
<style scoped>
.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>

