<template>
  <div>
    <el-table
      :data="tableData"
      class="discount-table"
      header-row-class-name="customer-row"
      row-class-name="customer-row"
      v-loading="loading">
      <el-table-column
        label="Charge Type:"
        min-width="120px">
        <template slot-scope="{row}">
          <el-select
            v-model="row.chargeType"
            class="add-text"
            placeholder="">
            <el-option
              v-for="item in typeOptions"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="Eligible Sites:"
        min-width="120px"
        align="center">
        <template slot-scope="{row}">
          <span
            class="link-detail underline bold"
            @click="showAssignment(row)">{{row.discountSiteLable}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="Discount(%):"
        min-width="100px">
        <template slot-scope="{row}">
          <el-input
            v-model="row.discount"
            class="add-text"
            min="0"
            max="100"
            type="number"
            maxlength="5"/>
        </template>
      </el-table-column>
      <el-table-column
        label=""
        width="100px">
        <template slot-scope="{row, $index}">
          <div class="flexc">
            <img
              class="list-item-icon"
              @click="subtItem(row, $index)"
              src="../../assets/form-list-sub.png"/>
            <img
              v-if="tableData.length - 1 === $index"
              class="list-item-icon"
              @click="addItem"
              src="../../assets/form-list-add.png"/>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <AssignmentSite
      :countryCode="countryCode"
      :groupPk="group"
      :visible="assignment.visible"
      :item="assignment.item"
      @hide="hideAssignment"/>
  </div>
</template>

<script>
import api from '@/http/api/group';
import AssignmentSite from './AssignmentSite.vue';
export default {
  name: "DiscountAssignment",
  props: {
    data: {
      type: Array,
      default: () => []
    },
    group: {
      type: String | Number,
      default: ""
    },
    countryCode: String
  },
  data() {
    return {
      loading: false,
      typeOptions: [],
      tableData: [],
      assignment: {
        visible: false,
        item: {}
      }
    };
  },
  components: {
    AssignmentSite
  },
  mounted() {
    this.getTypeOptions();
  },
  watch: {
    group: {
      handler(pk, old) {
        if (pk) {
          this.init();
        }
      }
    },
    data: {
      deep: true,
      handler(n, o) {
        this.$nextTick(() => {
          if (this.group) {
            this.init();
            console.log("监听变化");
          }
        });
      }
    }
  },
  methods: {
    init() {
      this.tableData = this.data;
      if (this.tableData) {
        if (this.tableData.length == 0) {
          this.addItem();
        }
      } else {
        this.tableData = [];
        this.addItem();
      }
    },
    onChange() {
      this.$emit("change")
    },
    getTypeOptions() {
      api.getChargeTypes().then(res => {
        if (res.data) {
          this.typeOptions = res.data
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    validDiscount() {
      let pattern = /^\d*(\.)?\d{1,2}$/
      if (pattern.test(value)) {
        const lang = Number(value);
        if (lang < 0 || lang > 100) {
          return "Discount must to be between 0 and 100";
        } else {
          return "";
        }
      } else {
        return "Please enter the correct discount";
      }
    },
    showAssignment(row) {
      this.assignment.item = row;
      this.assignment.visible = true;
    },
    hideAssignment() {
      this.assignment.item = {};
      this.assignment.visible = false;
      this.onChange();
    },
    addItem() {
      this.loading = true;
      api.addDiscountItem({
        groupPk: this.group
      }).then(res => {
        this.loading = false;
        if (res.data) {
          this.tableData.push(res.data)
        }
      }).catch(err => {
        this.loading = false;
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    subtItem(item, index) {
      this.$confirm('Confirm delete?', 'Delete', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }).then(() => {
        this.deleteDiscount(item.userGroupDiscountId, index)
      })
    },
    deleteDiscount(id, index) {
      if (id) {
        this.loading = true;
        api.deleteDiscountItem(id).then(res => {
          this.loading = false;
          this.tableData.splice(index, 1);
        }).catch(err => {
          this.loading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        })
      } else {
        this.tableData.splice(index, 1);
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .discount-table {
    max-width: 500px;
    padding-bottom: 10px;
  }
  .discount-table:before {
    height: 0;
  }
  .add-text {
    width: 100%;
  }
  ::v-deep .customer-row {
    th,td {
      background: #fff;
      border-bottom: none;
    }
    .time-picker {
      width: 100%;
    }
  }
  .list-item-icon {
    height: 30px;
    cursor: pointer;
    font-size: 26px;
    font-weight: 500;
  }
  .list-item-icon + .list-item-icon {
    margin-left: 15px;
  }
</style>