<template>
  <div class="rates-container">
    <div class="title">
      <p>Volume Reward</p>
      <span class="tipInfo">{{ tipInfo }}</span>
      <el-button
        type="danger"
        size="small"
        class="saveBtn"
        :disabled="btnSaveDisabled"
        @click="handleSave"
      >Save</el-button>
      <el-button type="primary" class="addBtn" size="small" @click="handleAdd">New</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      stripe
      class="table"
      :cell-style="cellStyle"
    >
      <el-table-column type="index" width="50" />
      <el-table-column
        prop="Min"
        label="Min"
        min-width="50"
        :formatter="minFormatter"
        show-overflow-tooltip
      />
      <el-table-column
        prop="Max"
        label="Max"
        min-width="50"
        show-overflow-tooltip
        :formatter="maxFormatter"
      />
      <el-table-column
        prop="Price"
        label="Additional Pay ($)"
        show-overflow-tooltip
        min-width="70"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.Price | rounding }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="Action" min-width="200">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="handleEdit(scope.$index,scope.row)">Edit</el-button>
          <el-button size="small" type="text" @click="handleDelete(scope.$index,scope.row)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      style="text-align:right;margin-top:5px;"
      :total="total"
      :page.sync="listQuery.PageIndex"
      :limit.sync="listQuery.PageSize"
      @pagination="getList"
    />

    <el-dialog
      :key="timer"
      :title="title"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      size="small"
    >
      <el-form ref="rewardForm" label-width="150px" :rules="rules" :model="rewardForm" size="small">
        <el-form-item label="Min: " prop="Min">
          <el-input v-model="rewardForm.Min" type="number" />
        </el-form-item>
        <el-form-item label="Max: " prop="Max">
          <el-input v-model="rewardForm.Max" type="number" />
        </el-form-item>
        <el-form-item label="Additional Pay ($): " prop="Price">
          <el-input v-model="rewardForm.Price" type="number" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" size="small" @click="handleSaveForm()">Ok</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import {
  getvolumeRewardPriceList,
  addOrUpdatevolumeRewardPriceList
} from '@/api/financials'
const getListQueryDefault = () => {
  return {
    PageIndex: 1,
    PageSize: 20,
    Asc: false,
    SortField: ''
  }
}
export default {
  name: 'VolumeReward',
  components: { Pagination },
  filters: {
    rounding(value) {
      return value ? Number(value).toFixed(2) : value
    }
  },
  data() {
    return {
      listQuery: getListQueryDefault(),
      list: [],
      listLoading: false,
      total: 0,
      tipInfo: '',
      btnSaveDisabled: true,
      dialogVisible: false,
      title: '',
      timer: '',
      minError: [],
      maxError: [],
      rewardForm: {},
      rules: {
        Price: [{ required: true, message: 'Please specify', trigger: 'blur' }],
        Min: [{ required: true, message: 'Please specify', trigger: 'blur' }],
        Max: [{ required: true, message: 'Please specify', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getvolumeRewardPriceList(this.listQuery)
        .then((res) => {
          this.listLoading = false
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    handleAdd() {
      this.rewardForm = {}
      this.title = 'Add'
      this.timer = new Date().getTime()
      this.dialogVisible = true
    },
    handleEdit(index, row) {
      this.title = 'Edit'
      this.rewardForm = JSON.parse(JSON.stringify(row))
      this.rewardForm.index = index
      this.timer = new Date().getTime()
      this.dialogVisible = true
    },
    handleSaveForm() {
      this.$refs.rewardForm.validate((valid) => {
        if (valid) {
          // 编辑
          if (this.rewardForm.Id) {
            this.list.forEach((item) => {
              if (item.Id === this.rewardForm.Id) {
                item.Min = this.rewardForm.Min
                item.Max = this.rewardForm.Max
                item.Price = this.rewardForm.Price
              }
            })
            // this.list.splice(this.rewardForm.index, 1)
            // this.list.push({
            //   Id:this.rewardForm.Id,
            //   Price: this.rewardForm.Price,
            //   Min: this.rewardForm.Min,
            //   Max: this.rewardForm.Max,
            // });
          } else {
            this.list.push({
              Id: new Date().getTime(),
              Price: this.rewardForm.Price,
              Min: this.rewardForm.Min,
              Max: this.rewardForm.Max
            })
          }

          this.btnSaveDisabled = false
          this.list.sort(this.compare('Min'))

          this.dialogVisible = false
          this.tipInfo = `Please Save`
          this.handelCheckError()
        }
      })
    },
    compare(property) {
      return function(a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    },
    handleDelete(index, row) {
      this.$confirm('Confirm to delete?', {
        type: 'warning',
        distinguishCancelAndClose: true,
        confirmButtonText: 'Yes',
        cancelButtonText: 'No'
      }).then(() => {
        this.list.splice(index, 1)
        this.tipInfo = `Please Save`
        this.btnSaveDisabled = false

        this.list.sort(this.compare('Min'))
        this.handelCheckError()
      })
    },
    handleSave() {
      this.handelCheckError()
      if (this.minError.length > 0 || this.maxError.length > 0) {
        this.tipInfo = 'Validate Error'
        return
      }
      if (this.list.length === 0) {
        this.tipInfo = 'Error: At least one record'
        return
      }
      addOrUpdatevolumeRewardPriceList(this.list)
        .then((res) => {
          if (res.IsSuccess) {
            this.getList()
            this.$message.success('Updated successfully!')
            this.tipInfo = ''
            this.btnSaveDisabled = true
          }
        })
        .catch((err) => {
          this.$message({ message: err, type: 'error' })
        })
    },
    handelCheckError() {
      this.minError = []
      this.maxError = []
      for (var i = 0; i < this.list.length; i++) {
        if (i === 0) {
          if (this.list[0].Min !== 0) {
            this.minError.push({
              index: 0,
              value: '(must be 0)',
              column: 1
            })
          }
        } else {
          if (Number(this.list[i - 1].Max) + 1 !== Number(this.list[i].Min)) {
            this.maxError.push({
              index: i - 1,
              value: '( ' + (this.list[i].Min - 1) + ' ?)',
              column: 2
            })

            this.minError.push({
              index: i,
              value: '( ' + (Number(this.list[i - 1].Max) + 1) + ' ?)',
              column: 1
            })
          }

          if (Number(this.list[i].Min) > Number(this.list[i].Max)) {
            this.maxError.push({
              index: i,
              value: '( must bigger than' + this.list[i].Min + ' )',
              column: 2
            })
          }
        }
      }
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      const minError = this.minError.filter(
        (item) => item.index === rowIndex
      )[0]
      const maxError = this.maxError.filter(
        (item) => item.index === rowIndex
      )[0]
      if (minError) {
        if (minError.column === columnIndex) return 'color:red'
      }
      if (maxError) {
        if (maxError.column === columnIndex) return 'color:red'
      }
      return
    },
    minFormatter(row, column, value, index) {
      var error = this.minError.filter((item) => item.index === index)[0]
      if (error) {
        return value + error.value
      } else return value
    },

    maxFormatter(row, column, value, index) {
      var error = this.maxError.filter((item) => item.index === index)[0]
      if (error) {
        return value + error.value
      } else return value
    }
  }
}
</script>
<style lang="scss" scoped>
.rates-container {
  .title {
    position: relative;
    height: 35px;
    line-height: 35px;
    background: #e4ebf1;
    border-left: 3px solid #0fc8e0;
    padding-left: 5px;
    margin: 10px 0px;
    font-size: 13px;
    p {
      margin: 0;
    }
    .tipInfo {
      position: absolute;
      right: 150px;
      top: 50%;
      height: 30px;
      margin-top: -10px;
      color: red;
    }
    .saveBtn {
      position: absolute;
      right: 60px;
      top: 50%;
      height: 30px;
      margin-top: -15px;
    }
    .addBtn {
      position: absolute;
      right: 0px;
      top: 50%;
      height: 30px;
      margin-top: -15px;
    }
  }
}
</style>
