<template>
  <div class="card-container">
    <el-form
      ref="detailForm"
      :model="form"
      label-position="right"
      label-width="180px"
      style="width: 100%;"
      v-loading="loading"
      :rules="rules">
      <div class="flexr">
        <div class="flex1 card-content">
          <div class="section-title">Account details</div>
          <el-form-item
            label="Entity Name:">
            <el-input
              class="add-text"
              v-model="form.entityName"
              maxlength="100"/>
          </el-form-item>
          <el-form-item
            label="Entity Business Reg No.:">
            <el-input
              class="add-text"
              v-model="form.entityBusinessRegNo"
              maxlength="50"/>
          </el-form-item>
          <el-form-item
            label="Country:">
            <el-select
              v-model="form.entityCountryCode"
              class="add-text">
              <el-option
                v-for="item in options.country"
                :key="item.name"
                :label="item.name"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="Account Type:">
            <el-select
              v-model="form.entityType"
              class="add-text">
              <el-option
                v-for="item in options.accountType"
                :key="item"
                :label="item"
                :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="Entity POC Name:">
            <el-input
              class="add-text"
              v-model="form.entityContactName"
              maxlength="50"/>
          </el-form-item>
          <el-form-item
            label="POC Email:">
            <el-input
              class="add-text"
              v-model="form.entityContactEmail"
              maxlength="80"/>
          </el-form-item>
          <el-form-item
            label="POC Contact No.:">
            <div class="add-text flexc">
              <el-select
                style="min-width: 75px; max-width: 80px;"
                v-model="form.entityCallingCode">
                <el-option
                  v-for="item in options.callingCode"
                  :key="item.callingCode"
                  :label="'+' + item.callingCode"
                  :value="item.callingCode"/>
              </el-select>
              <el-input
                v-model="form.entityContactNumber"
                style="flex: 1; margin-left: 10px;"
                placeholder=""
                maxlength="20"/>
            </div>
          </el-form-item>
          <el-form-item
            label="Effective Date:">
            <!-- <el-date-picker
              v-model="form.entitySigningDate"
              class="add-text"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"/> -->
            <el-date-picker
              v-model="form.effectiveDateRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              start-placeholder="Start Date"
              end-placeholder="End Date"
              clearable
              class="add-text"/>
          </el-form-item>
          <el-form-item
            label="Billing Date:">
            <div class="add-text flex">
              <el-select
                style="min-width: 65px; max-width: 80px;"
                v-model="form.entitySettlementDate"
                placeholder="D/M">
                <el-option
                  v-for="item in options.dates"
                  :key="item"
                  :label="item"
                  :value="item"/>
              </el-select>
              <div class="flex1 flexc" style="padding-left: 10px;">
                <span style="font-size: 14px; font-weight: bold; white-space: nowrap;">Of every subsequent month</span>
              </div>
            </div>
          </el-form-item>
          <el-form-item
            label="Billing Type:">
            <el-select
              v-model="form.entityBillingType"
              class="add-text">
              <el-option
                v-for="item in options.billingType"
                :key="item"
                :label="item"
                :value="item" />
            </el-select>
          </el-form-item>
        </div>
        <div class="flex1 card-content">
          <div class="section-title">Billing calculation details ({{currencyData[form.entityCountryCode]}})</div>
          <el-table
            :data="form.tabulations"
            class="tabu-table no-border"
            header-row-class-name="customer-row"
            row-class-name="customer-row">
            <el-table-column
              label="Tabulation Model"
              min-width="180">
              <template slot-scope="{row}">
                <div class="row-text">{{row.tabulationModel}} Fee Model</div>
              </template>
            </el-table-column>
            <el-table-column
              label="Rates"
              min-width="260">
              <template slot-scope="{row}">
                <div class="flexc" v-if="row.tabulationModel == 'Revenue'">
                  <el-input
                    v-model="row.tabulationPercent"
                    class="input-text"
                    placeholder=""
                    maxlength="5"/>
                  <span class="row-text">% Per Total Charges</span>
                </div>
                <div class="flexc" v-if="row.tabulationModel == 'Concession'">
                  <el-input
                    v-model="row.tabulationFixed"
                    class="input-text"
                    placeholder=""
                    maxlength="10"/>
                  <span class="row-text">{{currencyData[form.entityCountryCode]}} Per kWh</span>
                </div>
                <div class="flexc" v-if="row.tabulationModel == 'Commission'">
                  <el-input
                    v-model="row.tabulationPercent"
                    class="input-text"
                    placeholder=""
                    maxlength="5"/>
                  <span class="row-text">% Per Total Charges</span>
                </div>
                <div class="flexc" v-if="row.tabulationModel == 'Commission'" style="margin-top: 5px;">
                  <el-input
                    v-model="row.tabulationFixed"
                    class="input-text"
                    placeholder=""
                    maxlength="10"/>
                  <span class="row-text">{{currencyData[form.entityCountryCode]}} Per Transaction</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="Enable"
              width="80">
              <template slot-scope="{row, $index}">
                <el-switch
                  v-model="row.enable"
                  :disabled="isModelEnable($index)"/>
              </template>
            </el-table-column>
          </el-table>
          <el-table
            :data="form.items"
            class="items-table no-border"
            header-row-class-name="customer-row"
            row-class-name="customer-row">
            <el-table-column
              label="Item Name:"
              min-width="160">
              <template slot-scope="{row}">
                <el-input
                  v-model="row.itemName"
                  style="width: 100%;"
                  maxlength="50"/>
              </template>
            </el-table-column>
            <el-table-column
              label="Price:"
              min-width="100">
              <template slot-scope="{row}">
                <el-input
                  v-model="row.itemPrice"
                  style="width: 100%;"
                  maxlength="10"
                  type="number"/>
              </template>
            </el-table-column>
            <el-table-column
              label="Type:"
              min-width="120">
              <template slot-scope="{row}">
                <el-select
                  style="width: 100%;"
                  v-model="row.itemType">
                  <el-option
                    v-for="item in options.itemType"
                    :key="item"
                    :label="item"
                    :value="item"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label=""
              min-width="90">
              <template slot-scope="{row, $index}">
                <div class="flexc">
                  <img
                    class="list-item-icon"
                    @click="subtAdditionalItem($index)"
                    src="../../assets/form-list-sub.png"/>
                  <img
                    v-if="$index === form.items.length - 1"
                    class="list-item-icon"
                    @click="addAdditionalItem"
                    src="../../assets/form-list-add.png"/>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="card-content flexcr">
        <div class="buttons">
          <el-button
            type="primary"
            class="cancel-button"
            @click="onClickCancel">
            CANCEL
          </el-button>
          <el-button
            class="confirm-button"
            type="primary"
            @click="onClickSave">
            SAVE
          </el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import site from '@/http/api/site'
import settings from '../../settings.js'
import financial from '@/http/api/financial';
import {getCountryList} from '../../utils/index.js'
export default {
  data() {
    return {
      loading: false,
      form: {
        entityId: "",
        entityName: "",
        entityBusinessRegNo: "",
        entityCountryCode: settings.defaultCountry,
        entityCallingCode: settings.defaultCalling,
        entityType: "",
        entityBillingType: "",
        entityContactName: "",
        entityContactEmail: "",
        entityContactNumber: "",
        entitySigningDate: "",
        effectiveDateRange: [],
        entitySettlementDate: "",
        items: [],
        tabulations: []
      },
      rules: {},
      options: {
        dates: [],
        country: [],
        itemType: [],
        accountType: [],
        billingType: [],
        callingCode: []
      },
      currencyData: {
        SG: "S$"
      },
      isEdit: false
    }
  },
  created() {
    this.loading = true;
    this.getCountryList();
    this.getItemTypeOptions();
    this.getAccountTypeOptions();
    this.getBilingTypeOptions();
    this.getBillingDateOptions();
    if (this.$route.params.id) {
      this.isEdit = true;
      this.getBillingEntityInfo()
    } else {
      this.addAdditionalItem();
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    }
  },
  methods: {
    getBillingDateOptions() {
      this.options.dates = [];
      for (let i = 1; i < 31; i++) {
        this.options.dates.push(i);
      }
      this.form.tabulations = [{
        enable: false,
        tabulationFixed: "",
        tabulationModel: "Revenue",
        tabulationPercent: ""
      }, {
        enable: false,
        tabulationFixed: "",
        tabulationModel: "Concession",
        tabulationPercent: ""
      }, {
        enable: false,
        tabulationFixed: "",
        tabulationModel: "Commission",
        tabulationPercent: ""
      }]
    },
    getCountryList() {
      getCountryList(list => {
        this.options.callingCode = list
      })
      site.getCountryList().then(res => {
        if (res.data) {
          this.options.country = res.data
          const sign = {}
          res.data.forEach(item => {
            sign[item.value] = item.currencySymbol
          })
          this.currencyData = sign;
        }
      })
    },
    getAccountTypeOptions() {
      financial.getBillingAccountTypes().then(res => {
        if (res.data) {
          this.options.accountType = res.data
        } else {
          this.options.accountType = []
        }
      }).catch(err => {
        this.$message({
          message: error,
          type: 'error'
        })
        this.options.accountType = []
      })
    },
    getBilingTypeOptions() {
      financial.getBillingTypeOptions().then(res => {
        if (res.data) {
          this.options.billingType = res.data
        } else {
          this.options.billingType = []
        }
      }).catch(err => {
        this.$message({
          message: error,
          type: 'error'
        })
        this.options.billingType = []
      })
    },
    getItemTypeOptions() {
      financial.getAdditionalItemTypes().then(res => {
        if (res.data) {
          this.options.itemType = res.data
        }
      }).catch(err => {
        this.$message({
          message: error,
          type: 'error'
        })
      })
    },
    getBillingEntityInfo() {
      financial.viewBillingAccount(this.$route.params.id).then(res => {
        if (res.data) {
          this.form = res.data
          if (!this.form.items || this.form.items.length == 0) {
            this.addAdditionalItem();
          }
        }
      }).catch(err => {
        this.$message({
          message: error,
          type: 'error'
        })
      }).finally(() => {
        this.loading = false;
      })
    },
    isModelEnable(index) {
      for (let i = 0; i < this.form.tabulations.length; i++) {
        let type = this.form.tabulations[i];
        if (type.enable) {
          if (index == i) {
            return false;
          } else {
            return true;
          }
        } else {
          continue;
        }
      }
      return false;
    },
    addAdditionalItem() {
      if (!this.form.items) {
        this.form.items = []
      }
      this.form.items.push({
        itemName: "",
        itemPrice: "",
        itemType: ""
      })
    },
    subtAdditionalItem(index) {
      const item = this.form.items[index];
      if (item.itemId) {
        this.$confirm('Are you sure you want to delete this item?', 'Delete', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }).then(() => {
          this.deleteAddtionalItem(item, index);
        })
      } else {
        this.form.items.splice(index, 1)
        if (this.form.items.length == 0) {
          this.addAdditionalItem()
        }
      }
    },
    deleteAddtionalItem(item, index) {
      financial.deleteAdditionalItem(item.itemId).then(res => {
        this.$message({
          type: 'success',
          message: "Delete success",
        })
        this.form.items.splice(index, 1)
        if (this.form.items.length == 0) {
          this.addAdditionalItem()
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      })
    },
    onClickCancel() {
      this.$nextTick(() => {
        this.$router.replace({
          path: "/financial-management/billing-account-mgmt"
        })
      })
    },
    onClickSave() {
      this.$refs['detailForm'].validate(result => {
        if (result) {
          this.loading = true;
          this.form.items = this.form.items.filter(item => (item.itemName && item.itemPrice && item.itemType));
          if (this.isEdit) {
            this.onUpdateBiling();
          } else {
            this.onCreateBiling();
          }
        }
      })
    },
    onCreateBiling() {
      financial.addBillingAccount(this.form).then(res => {
        this.$message({
          message: "Add successfully",
          type: 'success',
          duration: 3000,
        })
        this.onClickCancel();
      }).catch((error) => {
        this.$message({
          message: error,
          type: "error",
          duration: 5000,
        })
      }).finally(() => {
        this.loading = false;
      })
    },
    onUpdateBiling() {
      financial.updateBillingAccount(this.form).then(res => {
        this.$message({
          message: "Update successfully",
          type: 'success',
          duration: 3000,
        })
        this.onClickCancel();
      }).catch((error) => {
        this.$message({
          message: error,
          type: "error",
          duration: 5000,
        })
      }).finally(() => {
        this.loading = false;
      })
    }
  }
}
</script>

<style scoped="scoped" lang='scss'>
  @import '../../styles/variables.scss';
  
  .card-container {
    width: 100%;
    padding: 20px 40px;
    min-height: $mainAppMinHeight;
    background-color: #F0F5FC;
  }
  .card-content {
    margin: 0 8px 16px;
    padding: 15px 50px;
    border-radius: 6px;
    background-color: white;
  }
  .section-title {
    color: #333;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 15px;
    user-select: none;
    line-height: 24px;
    font-weight: bold;
    font-family: sans-serif;
    text-transform: uppercase;
  }
  .add-text {
    width: 100%;
    min-width: 150px;
    max-width: 300px;
  }
  .add-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  .hr {
    height: 2px;
    margin: 10px -40px;
    background-color: #F0F5FC;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  @media screen and (max-width: 500px) {
    .card-container {
      padding: 0px;
    }
    .card-content {
      padding: 15px 40px;
    }
  }
  .tabu-table {
    width: 100%;
    max-width: 520px;
    padding-bottom: 10px;
  }
  .items-table {
    width: 100%;
    padding: 10px 0;
    max-width: 520px;
  }
  ::v-deep .customer-row {
    th,td {
      background: #fff;
      border-bottom: none;
    }
    .row-text {
      color: #333;
      font-size: 14px;
    }
    .input-text {
      width: 70px;
      margin-right: 5px;
    }
    .list-item-icon {
      width: 28px;
      height: 28px;
      cursor: pointer;
      margin: 0 8px;
    }
  }
</style>