<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>
          <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
        </div>
      </div>
      <!--标题按钮部分结束-->
      <!--Start 新增修改部分-->
      <div class="listconadd">
        <div class="titwu"><span>{{ formobj.withApply }}单车返利预提申请</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.scmVehRebateWiths" :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.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 prop="withRebate" 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">
                <el-button type="primary" size="mini" @click="handleLook(scope.row)">查看</el-button>
              </template>
            </el-table-column>
<!--            <el-table-column label="备注" align="center">-->
<!--              <template slot-scope="scope">-->
<!--                <el-input v-model="scope.row.remarks" clearable placeholder="" class="addinputw"></el-input>-->
<!--              </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 添加修改部分-->
    <danchefanliselect v-show="viewState == 2" ref="divSelect" @doback="resetState" @backData="backData"/>
    <danchefanliAdd v-show="viewState == 3" ref="divAdd" @backAdd="backAdd" />
  </div>
</template>

<script>
import req from '@/api/bikerebate/bicyclerebatewithholding'
import { brandDown, fetchBySid } from '@/api/cheliang/dictcommons'
import danchefanliselect from './relation/danchefanliselect'
import danchefanliAdd from './relation/danchefanliAdd'

export default {
  name: 'bicyclerebatewithholdingAdd',
  components: {
    danchefanliselect,
    danchefanliAdd
  },
  data() {
    return {
      viewTitle: '',
      index: 0,
      tableKey: 0,
      viewState: 1,
      dialogStatus: '',
      brand_list: [],
      // 表单数据
      formobj: {
        sid: '',
        withApply: '',
        createOrgName: '',
        createOrgSid: '',
        useOrgName: '',
        useOrgSid: '',
        remarks: '',
        withRebateTotal: '',
        createByName: '',
        createBySid: '',
        instanceId: '', // 流程实例ID
        taskId: '', // 任务ID
        scmVehRebateWiths: []
      },
      rules: {},
      submitdisabled: false
    }
  },
  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
        }
      })
    },
    // 获取日期
    newDate() {
      let date = new Date()
      let year = date.getFullYear() // 年
      let month = date.getMonth() + 1 // 月
      this.formobj.withApply = year + '年' + month + '月'
    },
    showAdd(createOrgSid) {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
        this.init()
        this.newDate()
      })
      this.dialogStatus = 'add'
      this.formobj.createBySid = window.sessionStorage.getItem('userSid')
      this.formobj.createOrgSid = createOrgSid
      this.formobj.useOrgSid = createOrgSid
      this.formobj.createByName = window.sessionStorage.getItem('name')
      this.viewTitle = '【新增】预提申请'
    },
    showEdit(row) {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.dialogStatus = 'edit'
      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
      })
    },
    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.scmVehRebateWiths, this.formobj.createOrgSid, this.formobj.brandSid)
    },
    // 列表--选择返回数据
    backData(value) {
      this.viewState = 1
      for (var i in value) {
        let cval = value[i]
        if (!this.formobj.scmVehRebateWiths || this.formobj.scmVehRebateWiths.length === 0) {
          this.formobj.scmVehRebateWiths = []
        }
        let v = 0
        for (var j in this.formobj.scmVehRebateWiths) {
          if (this.formobj.scmVehRebateWiths[j].rebateTypeValue === cval.rebateTypeValue) {
            this.formobj.scmVehRebateWiths[j].num = parseInt(this.formobj.scmVehRebateWiths[j].num) + parseInt(1)
            this.formobj.scmVehRebateWiths[j].withRebate = parseInt(this.formobj.scmVehRebateWiths[j].withRebate) + parseInt(cval.withRebate)
            this.formobj.scmVehRebateWiths[j].vehRebateSids.push(cval.sid)
            v = 1
            break
          }
        }
        if (v === 0) {
          this.formobj.scmVehRebateWiths.push({
            rebateTypeKey: cval.rebateTypeKey,
            rebateTypeValue: cval.rebateTypeValue,
            num: 1,
            withRebate: cval.withRebate,
            brandName: cval.brandName,
            brandSid: cval.brandSid,
            vehRebateSids: [cval.sid],
            // remarks: '',
            sid: '',
            mainSid: ''
          })
        }
      }
    },
    // 明细--查看
    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].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,
              vehRebateSids: [cval.sid],
              // remarks: '',
              sid: '',
              mainSid: ''
            })
          }
        }
        for (var k = 0; k < this.formobj.scmVehRebateWiths.length; k++) {
          if (this.formobj.scmVehRebateWiths[k].rebateTypeValue === rebateType) {
            this.formobj.scmVehRebateWiths[k].rebateTypeKey = aa[0].rebateTypeKey
            this.formobj.scmVehRebateWiths[k].rebateTypeValue = aa[0].rebateTypeValue
            this.formobj.scmVehRebateWiths[k].num = aa[0].num
            this.formobj.scmVehRebateWiths[k].withRebate = aa[0].withRebate
            this.formobj.scmVehRebateWiths[k].brandName = aa[0].brandName
            this.formobj.scmVehRebateWiths[k].brandSid = aa[0].brandSid
            this.formobj.scmVehRebateWiths[k].vehRebateSids = aa[0].vehRebateSids
            break
          }
        }
      } else if (value.length === 0) {
        for (var l = 0; l < this.formobj.scmVehRebateWiths.length; l++) {
          if (this.formobj.scmVehRebateWiths[l].rebateTypeValue === rebateType) {
            this.formobj.scmVehRebateWiths.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) => {
            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
        }
      })
    },
    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
              })
              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 === 'withRebate') {
          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
    },
    // 返回（===既判断）
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      // 表单数据
      this.formobj = {
        sid: '',
        withApply: '',
        createOrgName: '',
        createOrgSid: '',
        useOrgName: '',
        useOrgSid: '',
        remarks: '',
        withRebateTotal: '',
        createByName: '',
        createBySid: '',
        instanceId: '', // 流程实例ID
        taskId: '', // 任务ID
        scmVehRebateWiths: []
      }
      this.$refs['form_obj'].resetFields()
      this.$emit('doback')
    }
  }
}
</script>
<style scoped>
.rowStyle {
  border-left: 0px;
}
.colOneStyle {
  border-right: 0px !important;
  border-bottom: 0px !important;
}
</style>

