<template>
  <div class="set-merchant-page">
    <Card>
      <div class="save-content">
        <!-- <InputNumber :max="10" :min="1" :value="value1" placeholder="0"  @on-blur="handleDateChange"></InputNumber> -->
        <Button type="primary" @click="handleAdd" style="margin-right:10px">+ 新 增</Button>
        <Button type="primary" @click="handleSave">+ 保 存</Button>
        
      </div>
      <tables
        ref="tables"
        editable
        v-model="tableData"
        :columns="columns"
        :loading="loading"
      />
    </Card>
  </div>
</template>
<script>
// import { MerchantLevelObj } from '@/enums'
import Tables from '_c/tables'
// import { Row } from 'iview'
export default {
  components: {
    Tables
  },
  data () {
    let vm = this
    return {
      value1:null,
      loading: false,
      tableData: [],
      itemData: {
        copyrightPriceToplimit: null,
        derivativesAmountToplimit: null,
        derivativesPriceToplimit: null,
        inviteRegisterCommissionRate: null,
        levelName: "",
        levelNo: null,
        merchantShareRate: null,
        platformCommissionRate: null,
        promoteDistributeCommissionRate: null,
        totalEffectiveTurnover: null
      },
      columns: [
        { title: '等级序号', key: 'levelNo', minWidth: 100, align: 'center' },
        { title: '等级名称',
          key: 'levelName',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Input', {
                props: {
                  value: params.row.levelName,
                  clearable: true,
                  readonly: params.row.isReadonly,
                  placeholder: '名称最多可以输入五个字',
                  maxlength: 5
                },
                on: {
                  input: (val) => {
                    // params.row.levelName = val
                    vm.tableData[params.index].levelName = val
                  }
                }
              })
            ])
          }
        },
        { title: '累积有效成交金额（￥）',
          key: 'totalEffectiveTurnover',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('InputNumber', {
                props: {
                  value: params.row.totalEffectiveTurnover,
                  clearable: true,
                  readonly: params.row.isReadonly,
                  placeholder: '0',
                  min: 1
                },
                on: {
                  input: (val) => {
                    // params.row.totalEffectiveTurnover = val
                    vm.tableData[params.index].totalEffectiveTurnover = val
                  }
                }
              })
            ])
          }
        },
        { title: '版权价格上限（￥）',
          key: 'copyrightPriceToplimit',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('InputNumber', {
                props: {
                  value: params.row.copyrightPriceToplimit,
                  clearable: true,
                  readonly: params.row.isReadonly,
                  placeholder: '0',
                  min: 1
                },
                on: {
                  input: (val) => {
                    // params.row.copyrightPriceToplimit = val
                    vm.tableData[params.index].copyrightPriceToplimit = val
                  }
                }
              })
            ])
          }
        },
        { title: '衍生品价格上限（￥）',
          key: 'derivativesPriceToplimit',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('InputNumber', {
                props: {
                  value: params.row.derivativesPriceToplimit,
                  clearable: true,
                  readonly: params.row.isReadonly,
                  placeholder: '0',
                  min: 1
                },
                on: {
                  input: (val) => {
                    // params.row.derivativesPriceToplimit = val
                    vm.tableData[params.index].derivativesPriceToplimit = val
                  }
                }
              })
            ])
          }
        },
        { title: '衍生品数量上限（个）',
          key: 'derivativesAmountToplimit',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('InputNumber', {
                props: {
                  value: params.row.derivativesAmountToplimit,
                  clearable: true,
                  readonly: params.row.isReadonly,
                  placeholder: '0',
                  min: 1
                },
                on: {
                  input: (val) => {
                    // params.row.derivativesAmountToplimit = val
                    vm.tableData[params.index].derivativesAmountToplimit = val
                  }
                }
              })
            ])
          }
        },
        { title: '商家分成比例（%）',
          key: 'merchantShareRate',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('InputNumber', {
                props: {
                  value: params.row.merchantShareRate,
                  clearable: true,
                  readonly: params.row.isReadonly,
                  max: 100,
                  placeholder: '0',
                  min: 1
                },
                on: {
                  input: (val) => {
                    let value = val || 0
                    if (value>100) {
                      this.$Notice.warning({ title: '商家分成比例不能超过100%' })
                      params.row.merchantShareRate = null
                      vm.tableData[params.index] = params.row
                    } else {
                      // params.row.merchantShareRate = value
                      vm.tableData[params.index].merchantShareRate = value
                    }
                  }
                }
              })
            ])
          }
        },
        { title: '邀请注册佣金比例（%）',
          key: 'inviteRegisterCommissionRate',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('InputNumber', {
                props: {
                  value: params.row.inviteRegisterCommissionRate,
                  clearable: true,
                  readonly: params.row.isReadonly,
                  max: 100,
                  placeholder: '0',
                  min: 1
                },
                on: {
                  input: (val) => {
                    let value = val || 0
                    let flag = true
                    let {merchantShareRate, promoteDistributeCommissionRate} = params.row
                    if (!params.row.merchantShareRate) {
                      this.$Notice.warning({ title: '请输入注册佣金比例' })
                      flag = false
                    } else {
                      if ((100 - merchantShareRate - (promoteDistributeCommissionRate || 0) - value <= 0)) {
                        this.$Notice.warning({ title: '邀请注册佣金比例+推广分销佣金比例+平台佣金比例应该+商家分成比例=100%' })
                        flag = false
                      }
                    }  
                    if (!flag) {
                      params.row.inviteRegisterCommissionRate = null
                      vm.tableData[params.index] = params.row
                    } else {
                      // params.row.platformCommissionRate = 100 - merchantShareRate - (promoteDistributeCommissionRate || 0) - value
                      // params.row.inviteRegisterCommissionRate = value
                      vm.tableData[params.index].platformCommissionRate = 100 - merchantShareRate - (promoteDistributeCommissionRate || 0) - value
                      vm.tableData[params.index].inviteRegisterCommissionRate = value
                    }
                  }
                }
              })
            ])
          }
        },
        { title: '推广分销佣金比例（%）',
          key: 'promoteDistributeCommissionRate',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('InputNumber', {
                props: {
                  value: params.row.promoteDistributeCommissionRate,
                  clearable: true,
                  readonly: params.row.isReadonly,
                  max: 100,
                  placeholder: '0',
                  min: 1
                },
                on: {
                  input: (val) => {
                    let value = val || 0
                    let flag = true
                    let {merchantShareRate, inviteRegisterCommissionRate} = params.row
                    if (!params.row.merchantShareRate) {
                      this.$Notice.warning({ title: '请输入商家分成比例' })
                      flag = false
                    } else {
                      if ((100 - merchantShareRate - (inviteRegisterCommissionRate || 0) - value <= 0)) {
                        this.$Notice.warning({ title: '邀请注册佣金比例+推广分销佣金比例+平台佣金比例应该+商家分成比例=100%' })
                        flag = false
                      }
                    }  
                    if (!flag) {
                      params.row.promoteDistributeCommissionRate = null
                      vm.tableData[params.index] = params.row
                    } else {
                      // params.row.platformCommissionRate = 100 - merchantShareRate - (inviteRegisterCommissionRate || 0) - value
                      // params.row.promoteDistributeCommissionRate = value
                      vm.tableData[params.index].platformCommissionRate = 100 - merchantShareRate - (inviteRegisterCommissionRate || 0) - value
                      vm.tableData[params.index].promoteDistributeCommissionRate = value
                    }
                  }
                }
              })
            ])
          }
        },
        { title: '平台佣金比例（%）',
          key: 'platformCommissionRate',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('InputNumber', {
                props: {
                  value: params.row.platformCommissionRate,
                  clearable: true,
                  readonly: true,
                  max: 100,
                  placeholder: '--'
                },
                on: {
                  input: (val) => {
                    params.row.platformCommissionRate = val
                    vm.tableData[params.index].platformCommissionRate = val
                  }
                }
              })
            ])
          }
        },
        { title: '操作',
          key: 'index',
          align: 'center',
          fixed: 'right',
          minWidth: 150,
          render: (h, params) => {
            const editBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleEdit(params)
                },
                style: {
                  marginRight: '5px'
                }
              },
              '编 辑'
            )
            const finishBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleFinish(params)
                },
                style: {
                  marginRight: '5px'
                }
              },
              '完 成'
            )
            const deleteBtn = h(
              'Button',
              {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: this.handleDelete(params)
                },
                style: {
                  marginRight: '5px'
                }
              },
              '删 除'
            )

            return h('div', [params.row.isReadonly ? editBtn : finishBtn, deleteBtn])
          }
        }
      ]
    }
  },
  methods: {
    requestData () {
      this.loading = true
      this.api({
        apiName: 'getMerchantSettinglist',
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          let list = res.data
          for (let item of list) {
            item.isReadonly = true
          }
          this.tableData = list
        }
      })
    },
    checkForm () {
      let errMsg = ''
      console.log(this.tableData)
      for (let row of this.tableData) {
        if (!row.levelName) {
          errMsg = '请输入等级名称！'
          break
        }
        if (!row.totalEffectiveTurnover) {
          errMsg = '请输入累积有效成交金额！'
          break
        }
        if (!row.copyrightPriceToplimit) {
          errMsg = '请输入累积有效成交金额！'
          break
        }
        if (!row.derivativesPriceToplimit) {
          errMsg = '请输入衍生品价格上限！'
          break
        }
        if (!row.derivativesAmountToplimit) {
          errMsg = '请输入衍生品数量上限！'
          break
        }
        if (!row.merchantShareRate) {
          errMsg = '请输入商家分成比例！'
          break
        }
        if (!row.inviteRegisterCommissionRate) {
          errMsg = '请输入邀请注册佣金比例！'
          break
        }
        if (!row.promoteDistributeCommissionRate) {
          errMsg = '请输入推广分销佣金比例！'
          break
        }
      }
      return { errMsg }
    },
    handleSave () {
      // let flag = false
      // flag = this.tableData.some(x => {
      //   return !x.isReadonly
      // })
      // if (flag) {
      //   return this.$Notice.warning({ title: '请点击完成！' })
      // }
      let { errMsg } = this.checkForm()
      if (errMsg) {
        return this.$Notice.warning({ title: errMsg })
      }
      let tableData = this.tableData
      this.api({
        apiName: 'saveMerchantSettings',
        postdata: tableData,
        success: (res) => {
          this.requestData()
          this.$Notice.success({ title: `保存成功！` })
        }
      })
    },
    handleEdit (params) {
      return () => {
        params.row.isReadonly = false
        this.$set(this.tableData, params.index, params.row)
      }
    },
    handleDelete (params) {
      return () => {
        this.tableData.splice(params.index, 1)
      }
    },
    handleFinish (params) {
      return () => {
        params.row.isReadonly = true
        this.$set(this.tableData, params.index, params.row)
      }
    },
    handleAdd () {
      if (this.tableData.length>12) {
        return this.$Notice.warning({ title: '最多添加12条！' })
      }
      let obj = Object.assign({}, this.itemData)
      obj.levelNo = this.tableData.length + 1
      this.tableData.push(obj)
    }
  },
  created () {
    this.requestData()
  }
}
</script>
<style scoped lang="less">
.save-content {
  padding-bottom: 10px;
  text-align: right;
}
</style>
