<template>
  <div class="card card-secondary">
    <div class="card-header">{{locales['Products'] || "Products"}} </div>
    <div class="card-body bg-light-gray">
      <div class="row">
        <div class="col-md-12">
          <div class="card">
            <div class="card-body">
              <!-- Toggle Button -->
              <div class="row">
                <div class="col-md-12">
                  <label class="cl-switch cl-switch-green ios">
                    <span class="label">{{locales['Select Product By Group'] || "Select Products By Group"}} 
                      <!-- {{ count }} -->
                      </span>
                    <input type="checkbox" v-model="groupby" checked>
                    <span class="switcher"></span>
                  </label>
                  <button v-show="selectAllStatus" class="btn btn-danger btn-sm float-right" @click="removeAll">{{locales['Remove All'] || "Remove All"}}</button>
                  <button class="btn btn-success btn-sm mr-2 float-right" @click="selectAll">{{locales['Select All Products'] || "Select All Products"}}</button>
                </div>
              </div>
              <!-- Show if groupby is true -->
              <div class="row" >
                <div class="col-md-6" v-if="groupby">
                  <div class="form-group">
                    <label for=""><span class="text-danger">*</span>{{locales['Select Product Group'] || "Select Product Group"}} </label>
                    <v-selector v-model="selected_product_group" :options="productGroups" label="name" >
                      <template v-slot:option="group">
                        <span :class="group"></span>
                        {{group.name}}
                      </template>
                    </v-selector>
                  </div>
                </div>
                <div class="col-md-6" >
                  <div class="form-group">
                    <label for=""><span class="text-danger">*</span>{{locales['Select Product/s'] || "Select Product/s"}} </label>
                    <vSelect v-model="selected_product_ids" :options="products" label="name" multiple>
                      
                    </vSelect>
                    <button v-if="groupby"  @click="selectAllProducts" class="btn btn-sm btn-primary">{{locales['Select all products of'] || "Select all products of"}} {{selected_product_group.name }}</button>
                  </div>
                </div>
              </div>

              <div v-for="product in selected_product_ids" :key="product.id">
                <SelectedProductComponent 
                  :tax_rates="tax_rates"
                  :product="product" 
                  :page_type="page_type"
                  v-if="page_type  == 'create'"
                  @removeProduct="removeProduct($event)"
                  @total_amount="total_product_amount($event)"
                ></SelectedProductComponent> 
                <SelectedProductComponent 
                  :tax_rates="tax_rates"
                  :product="product" 
                  :page_type="page_type"
                  :new_product="new_product"
                  v-if="page_type  == 'edit'"
                  :selected_products="selected_products"
                  @removeProduct="removeProduct($event)"
                  @total_amount="total_product_amount($event)"
                ></SelectedProductComponent> 
              </div>
            </div>
          </div>
        </div>
        
        <table id="products" class="table">
          <tbody>
            <tr>
              <td></td>
              <td></td>
              <td colspan="2"><label for="" class="float-right pt-2">{{locales['Sub-Total']|| "Sub-Total"}} </label></td>
              <td colspan="1"><label for="priceTotalWithTax"></label><input type="number" name="sub_total" class="form-control form-control-sm" id="priceTotalWithTax" step="0.02" v-model="sub_total" readonly /></td>
            </tr>
            <tr>
              <td></td>
              <td><label for=""  class="float-right pt-2">{{locales['Discount'] || "Discount"}} (%)</label></td>
              <td>

                <label>
                  <select v-model="discount_type_selected" class="form-control form-control-sm">
                    <option v-for="item in discount_type" :key="item.type" :value="item.type">
                      {{item.name}}
                    </option>
                  </select>
                </label>
              </td>
              <td>
                <div class="input-group">
                  <label for="getDiscountTotal"></label><input type="number" v-model="discount_percentage" class="form-control form-control-sm" id="getDiscountTotal" step="0.01" min="0" required/>
                  <span class="input-group-append">
                    <button class="input-group-text btn-sm" type="button" id="inputGroup-sizing-sm">%</button>
                  </span>
                </div>
              
              </td>
              <td>
                <div class="input-group">
                  <label>
                    <input type="number" v-model="discount_value" class="form-control form-control-sm"  step="0.02" readonly/>
                  </label>
                </div>
              </td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td colspan="2"><label for="" class="text-danger float-right pt-2">{{locales['Adjustments'] || "Adjustments"}} </label></td>
              <td>
                <label>
                  <input type="number" v-model="adjustments" class="form-control form-control-sm" step="0.01" required/>
                </label>
                <label class="text-danger" v-if="adjustmentStatus">{{locales['Empty field not allowed.'] || "Empty field not allowed."}}</label>
              </td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td colspan="2"><label for="Total Amount" class="float-right pt-2 "><span class="text-bold">{{locales['Total Amount'] || "Total Amount"}}</span></label></td>
              <td><label>
                <input type="number" v-model="total_amount" class="form-control form-control-sm" step="0.02" placeholder="0" readonly/>
              </label></td>
            </tr>
          </tbody>
        </table>
        
      </div>
    </div>

    <div class="card card-primary">
      <div class="card-body">
        <div v-if="this.comptype == 'Proposal'">
          <div class="row"  v-if="this.page_type  == 'create'">
            <div class="col-md-6 com-sm-12">
              <button class="btn btn-primary btn-block text-bold" :disabled="validated" @click="save">
                {{locales['Save'] || "Save"}} {{locales['Proposal'] || 'Proposal'}}
              </button>
            </div>
            <!-- <div class="col-md-6 com-sm-12">
              <button type="submit" class="btn btn-primary btn-block  text-bold" :disabled="validated" @click="save_email">
                {{locales['Save and Send Email'] || "Save and Send Email"}}
              </button>
            </div> -->
          </div>
          <div class="row"  v-if="this.page_type  == 'edit'">
            <div class="col-md-6 com-sm-12">
              <button class="btn btn-primary btn-block text-bold" :disabled="validated" @click="update">
                {{locales['Update'] || "Update"}} {{locales['Proposal'] || 'Proposal'}}
              </button>
            </div>
            <!-- <div class="col-md-6 com-sm-12">
              <button type="submit" class="btn btn-primary btn-block  text-bold" :disabled="validated" @click="update_email">
                {{locales['Update and Send Email'] || "Update and Send Email"}}
              </button>
            </div> -->

          </div>
        </div>
        <div v-if="this.comptype == 'Invoice'">
          <div class="row"  v-if="this.page_type  == 'create'">
            <div class="col-md-6 com-sm-12">
              <button class="btn btn-primary btn-block text-bold" :disabled="inv_validated" @click="save">
                {{locales['Save'] || "Save"}} {{locales['Invoice'] || 'Invoice'}}
              </button>
            </div>
            <!-- <div class="col-md-6 com-sm-12">
              <button type="submit" class="btn btn-primary btn-block  text-bold" :disabled="inv_validated" @click="save_email">
                {{locales['Save and Send Email'] || "Save and Send Email"}}
              </button>
            </div> -->
          </div>
          <div class="row"  v-if="this.page_type  == 'edit'">
            <div class="col-md-6 com-sm-12">
              <button class="btn btn-primary btn-block text-bold" :disabled="inv_validated" @click="update">
                {{locales['Update'] || "Update"}} {{locales['Invoice'] || 'Invoice'}}
              </button>
            </div>
            <!-- <div class="col-md-6 com-sm-12">
              <button type="submit" class="btn btn-primary btn-block  text-bold" :disabled="inv_validated" @click="update_email">
                {{locales['Update and Send Email'] || "Update and Send Email"}}
              </button>
            </div> -->

          </div>
        </div>

        <div v-if="this.comptype == 'Estimate'">
          <div class="row"  v-if="this.page_type  == 'create'">
            <div class="col-md-6 com-sm-12">
              <button class="btn btn-primary btn-block text-bold" :disabled="estimate_validated" @click="save">
                {{locales['Save'] || "Save"}} {{locales['Estimate'] || 'Estimate'}}
              </button>
            </div>
            <!-- <div class="col-md-6 com-sm-12">
              <button type="submit" class="btn btn-primary btn-block  text-bold" :disabled="estimate_validated" @click="save_email">
                {{locales['Save and Send Email'] || "Save and Send Email"}}
              </button>
            </div> -->
          </div>
          <div class="row"  v-if="this.page_type  == 'edit'">
            <div class="col-md-6 com-sm-12">
              <button class="btn btn-primary btn-block text-bold" :disabled="estimate_validated" @click="update">
                {{locales['Update'] || "Update"}} {{locales['Estimate'] || 'Estimate'}}
              </button>
            </div>
            <!-- <div class="col-md-6 com-sm-12">
              <button type="submit" class="btn btn-primary btn-block  text-bold" :disabled="estimate_validated" @click="update_email">
                {{locales['Update and Send Email'] || "Update and Send Email"}}
              </button>
            </div> -->

          </div>
        </div>

      </div>
    </div>

  </div>  
</template>

<script>
import vSelect from "vue-select";
import { mapGetters } from 'vuex';
import SelectedProductComponent from './SelectedProductComponent';
import Vue from "vue";
export default {
    props: ['comptype'],
    "name":"ProductSelector",
    components: { vSelect, SelectedProductComponent},
    computed:{
      ...mapGetters({
        validated:'validated',
        estimate_validated:'estimate_validated',
        inv_validated:'inv_validated',
        locales: 'locales',
      }),
    },
    data() {
      return {
        groupby: true,
        productGroups:[],
        selected_product_group:{
          id:null,
          name:null
        },
        products:[],
        selected_product_ids:[],
        selectAllStatus:false,
        tax_rates:[],
        sub_total:0,
        discount_type:[
          {'type':'before', name:'Before Tax'},
          {'type':'after', name:'After Tax'},
        ],
        discount_type_selected:'after',
        discount_percentage:0,
        discount_value:0,
        adjustments:0,
        total_amount:0,
        total_tax:0,
        selected_products:[],
        adjustmentStatus: false,
        page_type:"create",
        proposal_id:null,
        invoice_id:null,
        estimate_id:null,
        new_product:false, // make this true, if you are adding a new product by pressing any add button, even if in the product edit page.
      }
    },
    mounted(){
      this.getProductGroups();
      this.getTaxRates();

    },
    created() {
      // check if route is proposal create or proposal edit
      if (this.$route.params.id !== undefined) {
        this.page_type = "edit";
        
        if (this.page_type === "edit") {
          if(this.comptype == 'Proposal'){
            this.proposal_id = this.$route.params.id;
            axios.post('/api/v1/proposal/getEditProposalData  ', {
              'id': this.$route.params.id
            })
            .then((res) => {
              let prop_data = res.data.proposal;
              this.adjustments = (prop_data.adjustments == null) ? 0 : parseFloat(prop_data.adjustments);
              this.discount_percentage = prop_data.discount_percentage;
              this.discount_type_selected = prop_data.discount_type_selected;
              this.discount_value = parseFloat(prop_data.discount_value);
              this.selected_product_ids = res.data.products;
              this.selected_products = JSON.parse(prop_data.selected_products);
              this.sub_total = parseFloat(prop_data.sub_total);
              this.total_tax = parseFloat(prop_data.total_tax);
              this.total_amount = parseFloat(prop_data.total_amount);
              this.selected_products_counter = JSON.parse(prop_data.selected_products).length;
            });
          }else if(this.comptype == 'Invoice'){
            axios.post('/api/v1/invoice/getEditInvoiceData  ', {
              'id': this.$route.params.id
            })
            .then((res) => {
              let prop_data = res.data.invoice;
              this.adjustments = (prop_data.adjustments == null) ? 0 : parseFloat(prop_data.adjustments);
              this.discount_percentage = prop_data.discount_percentage;
              this.discount_type_selected = prop_data.discount_type_selected;
              this.discount_value = parseFloat(prop_data.discount_value);
              this.selected_product_ids = res.data.products;
              this.selected_products = JSON.parse(prop_data.selected_products);
              this.sub_total = parseFloat(prop_data.sub_total);
              this.total_tax = parseFloat(prop_data.total_tax);
              this.total_amount = parseFloat(prop_data.total_amount);
              this.selected_products_counter = JSON.parse(prop_data.selected_products).length;
            });
          }else if(this.comptype == 'Estimate'){
            axios.post('/api/v1/estimate/getEditEstimateData  ', {
              'id': this.$route.params.id
            })
            .then((res) => {
              let prop_data = res.data.estimate;
              this.adjustments = (prop_data.adjustments == null) ? 0 : parseFloat(prop_data.adjustments);
              this.discount_percentage = prop_data.discount_percentage;
              this.discount_type_selected = prop_data.discount_type_selected;
              this.discount_value = parseFloat(prop_data.discount_value);
              this.selected_product_ids = res.data.products;
              this.selected_products = JSON.parse(prop_data.selected_products);
              this.sub_total = parseFloat(prop_data.sub_total);
              this.total_tax = parseFloat(prop_data.total_tax);
              this.total_amount = parseFloat(prop_data.total_amount);
              this.selected_products_counter = JSON.parse(prop_data.selected_products).length;
            });
          }
        }
      }
    },
  methods:{
      async save(){
        if (this.comptype == 'Proposal') {
         axios.post('/api/v1/proposal/store',{
           "proposal_number_prefix": this.$store.state.createProposalStore.proposal_data.proposal_number_prefix,
           "new_proposal_number": this.$store.state.createProposalStore.proposal_data.proposal_number,
           "subject": this.$store.state.createProposalStore.proposal_data.subject,
           "lead_customer_id": this.$store.state.createProposalStore.proposal_data.lead_customer_id.id,
           "relation": this.$store.state.createProposalStore.proposal_data.relation,
           "proposal_date": this.$store.state.createProposalStore.proposal_data.proposal_date,
           "open_till_date":  this.$store.state.createProposalStore.proposal_data.open_till_date,
           "status": this.$store.state.createProposalStore.proposal_data.status,
           "currency_id": this.$store.state.createProposalStore.proposal_data.currency_id.id,
           "assigned_to": this.$store.state.createProposalStore.proposal_data.assigned_to.id,
           "message": this.$store.state.createProposalStore.proposal_data.message,
           "selected_products": this.selected_products,
           "adjustments":this.adjustments,
           "discount_percentage":this.discount_percentage,
           "discount_type_selected":this.discount_type_selected,
           "discount_value":this.discount_value,
           "sub_total":this.sub_total,
           "total_amount":this.total_amount,
           "total_tax":this.total_tax
         })
          .then((res) => {
            if(res.data.code === 200){
              this.$store.commit('RESET_PROPOSAL_STATE');
              this.groupby = true;
              this.selected_product_group = {};
              this.selected_product_ids = []; // This array contains the data from the products table only
              this.selectAllStatus =false;
              this.tax_rates = [];
              this.sub_total = 0;
              this.discount_type_selected = 'after';
              this.discount_percentage = 0;
              this.discount_value = 0;
              this.adjustments = 0;
              this.total_amount = 0;
              this.total_tax = 0;
              this.selected_products = []; // This array contains the calculated products data depending upon tax applied, units, and price
              this.adjustmentStatus= false;
              this.proposal_number_status = false;
              Vue.$toast.success('Proposal added successfully!', {
                position: 'top-right',
                duration: 5000,
                dismissible: true
              });
            }
          });          
        } else if (this.comptype == 'Invoice'){
         axios.post('/api/v1/invoice/store',{
           "invoice_number_prefix": this.$store.state.createInvoiceStore.invoice_data.invoice_number_prefix,
           "invoice_number": this.$store.state.createInvoiceStore.invoice_data.invoice_number,
           "invoice_title": this.$store.state.createInvoiceStore.invoice_data.invoice_title,
           "customer_id": this.$store.state.createInvoiceStore.invoice_data.customer_id.id,
           "invoice_date": this.$store.state.createInvoiceStore.invoice_data.invoice_date,
           "due_date":  this.$store.state.createInvoiceStore.invoice_data.due_date,
           "status": this.$store.state.createInvoiceStore.invoice_data.status,
           "currency_id": this.$store.state.createInvoiceStore.invoice_data.currency_id.id,
           "selected_products": this.selected_products,
           "adjustments":this.adjustments,
           "discount_percentage":this.discount_percentage,
           "discount_type_selected":this.discount_type_selected,
           "discount_value":this.discount_value,
           "sub_total":this.sub_total,
           "total_amount":this.total_amount,
           "total_tax":this.total_tax,
           "amount_due":this.$store.state.createInvoiceStore.invoice_data.amount_due,
           "amount_paid":this.$store.state.createInvoiceStore.invoice_data.amount_paid,
           "customer_notes":this.$store.state.createInvoiceStore.invoice_data.customer_notes,
           "customer_notes":this.$store.state.createInvoiceStore.invoice_data.customer_notes,
           "invoice_owner_id":this.$store.state.createInvoiceStore.invoice_data.invoice_owner_id,
           "selected_products_counter":this.$store.state.createInvoiceStore.invoice_data.selected_products_counter,
           "shipping_charges":this.$store.state.createInvoiceStore.invoice_data.shipping_charges,
           "termsandconditions":this.$store.state.createInvoiceStore.invoice_data.termsandconditions,
         })
          .then((res) => {
            if(res.data.code === 200){
              this.$store.commit('RESET_INVOICE_STATE');
              this.groupby = true;
              this.selected_product_group = {};
              this.selected_product_ids = [];
              this.selectAllStatus =false;
              this.tax_rates = [];
              this.sub_total = 0;
              this.discount_type_selected = 'after';
              this.discount_percentage = 0;
              this.discount_value = 0;
              this.adjustments = 0;
              this.total_amount = 0;
              this.total_tax = 0;
              this.selected_products = [];
              this.adjustmentStatus= false;
              this.proposal_number_status = false;
              Vue.$toast.success(res.data.message, {
                position: 'top-right',
                duration: 5000,
                dismissible: true
              });
            }else{
              Vue.$toast.error(res.data.message, {
                position: 'top-right',
                duration: 10000,
                dismissible: true
              });
            }
          });  
        } else if (this.comptype == 'Estimate'){
         axios.post('/api/v1/estimate/store',{
           "estimate_number_prefix": this.$store.state.createEstimateStore.estimate_data.estimate_number_prefix,
           "estimate_number": this.$store.state.createEstimateStore.estimate_data.estimate_number,
           "estimate_title": this.$store.state.createEstimateStore.estimate_data.estimate_title,
           "estimate_owner_id":this.$store.state.createEstimateStore.estimate_data.estimate_owner_id,
           "estimate_relation": this.$store.state.createEstimateStore.estimate_data.estimate_relation,
           "estimate_lead_customer_id": this.$store.state.createEstimateStore.estimate_data.estimate_lead_customer_id.id,
           "estimate_date": this.$store.state.createEstimateStore.estimate_data.estimate_date,
           "estimate_due_date":  this.$store.state.createEstimateStore.estimate_data.estimate_due_date,
           "estimate_status": this.$store.state.createEstimateStore.estimate_data.estimate_status,
           "estimate_currency_id": this.$store.state.createEstimateStore.estimate_data.estimate_currency_id.id,
           "selected_products": this.selected_products,
           "adjustments":this.adjustments,
           "discount_percentage":this.discount_percentage,
           "discount_type_selected":this.discount_type_selected,
           "discount_value":this.discount_value,
           "sub_total":this.sub_total,
           "total_amount":this.total_amount,
           "total_tax":this.total_tax,
           "estimate_customer_notes":this.$store.state.createEstimateStore.estimate_data.estimate_customer_notes,
           "selected_products_counter":this.$store.state.createEstimateStore.estimate_data.selected_products_counter,
           "estimate_shipping_charges":this.$store.state.createEstimateStore.estimate_data.estimate_shipping_charges,
           "estimate_termsandconditions":this.$store.state.createEstimateStore.estimate_data.estimate_termsandconditions,
         })
          .then((res) => {
            if(res.data.code === 200){
              this.$store.commit('RESET_ESTIMATE_STATE');
              this.groupby = true;
              this.selected_product_group = {};
              this.selected_product_ids = [];
              this.selectAllStatus =false;
              this.tax_rates = [];
              this.sub_total = 0;
              this.discount_type_selected = 'after';
              this.discount_percentage = 0;
              this.discount_value = 0;
              this.adjustments = 0;
              this.total_amount = 0;
              this.total_tax = 0;
              this.selected_products = [];
              this.adjustmentStatus= false;
              this.proposal_number_status = false;
              Vue.$toast.success('Estimate added successfully!', {
                position: 'top-right',
                duration: 5000,
                dismissible: true
              });
            }
          });  
        }
      },
      async save_email(){
        console.log('save and email');
      },

      update(){
        if(this.comptype == 'Proposal'){
         axios.post('/api/v1/proposal/update',{
           "proposal_id":this.$store.state.createProposalStore.proposal_id,
           "proposal_number_prefix": this.$store.state.createProposalStore.proposal_data.proposal_number_prefix,
           "new_proposal_number": this.$store.state.createProposalStore.proposal_data.proposal_number,
           "subject": this.$store.state.createProposalStore.proposal_data.subject,
           "lead_customer_id": this.$store.state.createProposalStore.proposal_data.lead_customer_id.id,
           "relation": this.$store.state.createProposalStore.proposal_data.relation,
           "proposal_date": this.$store.state.createProposalStore.proposal_data.proposal_date,
           "open_till_date":  this.$store.state.createProposalStore.proposal_data.open_till_date,
           "status": this.$store.state.createProposalStore.proposal_data.status,
           "currency_id": this.$store.state.createProposalStore.proposal_data.currency_id.id,
           "assigned_to": this.$store.state.createProposalStore.proposal_data.assigned_to.id,
           "message": this.$store.state.createProposalStore.proposal_data.message,
           "selected_products": this.selected_products,
           "adjustments":this.adjustments,
           "discount_percentage":this.discount_percentage,
           "discount_type_selected":this.discount_type_selected,
           "discount_value":this.discount_value,
           "sub_total":this.sub_total,
           "total_amount":this.total_amount,
           "total_tax":this.total_tax
         })
          .then((res) => {
            if(res.data.code === 200){
              Vue.$toast.success('Proposal updated successfully!', {
                position: 'top-right',
                duration: 5000,
                dismissible: true
              });
            }
          });
        }else if(this.comptype == 'Invoice'){
         axios.post('/api/v1/invoice/update',{
           "invoice_id":this.$store.state.createInvoiceStore.invoice_id,
           "invoice_number_prefix": this.$store.state.createInvoiceStore.invoice_data.invoice_number_prefix,
           "invoice_number": this.$store.state.createInvoiceStore.invoice_data.invoice_number,
           "invoice_title": this.$store.state.createInvoiceStore.invoice_data.invoice_title,
           "customer_id": this.$store.state.createInvoiceStore.invoice_data.customer_id.id,
           "invoice_date": this.$store.state.createInvoiceStore.invoice_data.invoice_date,
           "due_date":  this.$store.state.createInvoiceStore.invoice_data.due_date,
           "status": this.$store.state.createInvoiceStore.invoice_data.status,
           "currency_id": this.$store.state.createInvoiceStore.invoice_data.currency_id.id,
           "invoice_owner_id": this.$store.state.createInvoiceStore.invoice_data.invoice_owner_id,
           "customer_notes": this.$store.state.createInvoiceStore.invoice_data.customer_notes,
           "termsandconditions": this.$store.state.createInvoiceStore.invoice_data.termsandconditions,
           "amount_due": this.$store.state.createInvoiceStore.invoice_data.amount_due,
           "amount_paid": this.$store.state.createInvoiceStore.invoice_data.amount_paid,
           "shipping_charges": this.$store.state.createInvoiceStore.invoice_data.shipping_charges,
           "selected_products": this.selected_products,
           "adjustments":this.adjustments,
           "discount_percentage":this.discount_percentage,
           "discount_type_selected":this.discount_type_selected,
           "discount_value":this.discount_value,
           "sub_total":this.sub_total,
           "total_amount":this.total_amount,
           "total_tax":this.total_tax
         })
          .then((res) => {
            if(res.data.code === 200){
              Vue.$toast.success('Invoice updated successfully!', {
                position: 'top-right',
                duration: 5000,
                dismissible: true
              });
            }
          });
        }else if(this.comptype == 'Estimate'){
         axios.post('/api/v1/estimate/update',{
           "estimate_id":this.$store.state.createEstimateStore.estimate_id,
           "estimate_number_prefix": this.$store.state.createEstimateStore.estimate_data.estimate_number_prefix,
           "estimate_number": this.$store.state.createEstimateStore.estimate_data.estimate_number,
           "estimate_title": this.$store.state.createEstimateStore.estimate_data.estimate_title,
           "estimate_lead_customer_id": this.$store.state.createEstimateStore.estimate_data.estimate_lead_customer_id.id,
           "estimate_date": this.$store.state.createEstimateStore.estimate_data.estimate_date,
           "estimate_due_date":  this.$store.state.createEstimateStore.estimate_data.estimate_due_date,
           "estimate_status": this.$store.state.createEstimateStore.estimate_data.estimate_status,
           "estimate_currency_id": this.$store.state.createEstimateStore.estimate_data.estimate_currency_id.id,
           "estimate_relation": this.$store.state.createEstimateStore.estimate_data.estimate_relation,
           "estimate_owner_id": this.$store.state.createEstimateStore.estimate_data.estimate_owner_id,
           "estimate_customer_notes": this.$store.state.createEstimateStore.estimate_data.estimate_customer_notes,
           "estimate_termsandconditions": this.$store.state.createEstimateStore.estimate_data.estimate_termsandconditions,
           "shipping_charges": this.$store.state.createEstimateStore.estimate_data.estimate_shipping_charges,
           "selected_products": this.selected_products,
           "adjustments":this.adjustments,
           "discount_percentage":this.discount_percentage,
           "discount_type_selected":this.discount_type_selected,
           "discount_value":this.discount_value,
           "sub_total":this.sub_total,
           "total_amount":this.total_amount,
           "total_tax":this.total_tax
         })
          .then((res) => {
            if(res.data.code === 200){
              Vue.$toast.success('Estimate updated successfully!', {
                position: 'top-right',
                duration: 5000,
                dismissible: true
              });
            }else if(res.data.code === 422){
              Vue.$toast.error(res.data.message, {
                position: 'top-right',
                duration: 5000,
                dismissible: true
              });
            }
          })
          .catch((res)=>{
              Vue.$toast.error(res.data.message, {
                position: 'top-right',
                duration: 5000,
                dismissible: true
              });
          })
        }
      },
      async update_email(){
          console.log('update and email');
      },

      selectAllProducts(){
        // Copy all v-select items in your selectedItem array
        this.selected_product_ids = [...this.products]
        this.new_product = true;
      },
      getProductGroups(){
        axios.get('/api/v1/productGroups')
        .then((res) => {
          this.productGroups = res.data.productGroups;
        });
      },

      async getTaxRates(){
        axios.get('/api/v1/tax_rates')
        .then((res) => {
          this.tax_rates = res.data.tax_rates;
        })
      },
      async getProductsByGroupId(){
        axios.post('/api/v1/productsByGroup',{
          product_group_id: this.selected_product_group.id
        })
        .then((res) => {
          this.products = res.data.products;
        });
      },
      async getAllProducts(){
        axios.get('/api/v1/products')
        .then((res) => {
          this.products = res.data.products;
        });
      },
      async selectAll(){
        axios.get('/api/v1/products')
        .then((res) => {
            this.selected_product_ids = res.data.products;
            this.new_product = true;
            this.selectAllStatus = true;
        });
      },
      removeAll(){
        this.selected_product_ids = [];
        this.selectAllStatus = false;
      },
      removeProduct(product){
        this.selected_product_ids = this.selected_product_ids.filter(element => element.id !== product.id)
      },
      total_product_amount(product){
        // Remove the coming product from the selected list
        this.selected_products = this.selected_products.filter(ele => ele.product_id !== product.product_id);
        if(product.output_type !== 'remove'){
          // if output type is not remove, then add again in the list
          this.selected_products.push(product);
        }
        this.calculate_sub_total();
      },
      calculate_sub_total(){
        // Calculate sub_total
        this.sub_total = 0;
        this.selected_products.forEach(ele => {
          this.sub_total = this.sub_total+ele.total_p_amount
        });
        this.calculateTotalAmount();
      },
      calculate_total_tax(){
        // Calculate total tax
        this.total_tax = 0;
        this.selected_products.forEach(ele => {
          this.total_tax = this.total_tax+ele.tax_amount
        });
        this.calculateTotalAmount();
      },
      calc_discount_value(){
        if(this.discount_type_selected === 'after'){
          // If discount needs to be applied before tax 
          this.discount_value = (this.sub_total*this.discount_percentage)/100;
        }else{
          // If discount needs to be applied before tax 
          // newSubAmount is only sub_total without tax
          let newSubAmount = this.sub_total - this.total_tax;
          this.discount_value = (newSubAmount*this.discount_percentage)/100;
        }
        this.discount_value = this.discount_value.toFixed(2);
      },
      calculateTotalAmount(){
        this.total_amount = parseFloat(this.sub_total)-parseFloat(this.discount_value)+parseFloat(this.adjustments);
        this.total_amount= this.total_amount.toFixed(2);
      }
    },
    
    watch:{
      'selected_product_group':function(){
        this.getProductsByGroupId();
      },
      'groupby':function(){
        this.getAllProducts();
      },
      'selected_products':function(newVal){
        this.calculate_sub_total();
        this.calculate_total_tax();
        this.$store.dispatch({
          'type':'update_selected_products',
          'selected_products': newVal
        });
        // this.validated = newVal.length <= 0;
      },
      'discount_percentage':function(){
        this.calc_discount_value();
      },
      'discount_type_selected':function(){
        this.calc_discount_value();
      },
      'sub_total':function(){
        this.calc_discount_value();
      },
      'adjustments':function(newVal){
        this.adjustmentStatus = newVal === '';
        this.calculateTotalAmount();
      },
      'discount_value':function(){
        this.calculateTotalAmount();
      },
      'selected_product_ids':function(){
        this.selected_products = this.selected_products.filter(ele => this.selected_product_ids.some(o2 => ele.product_id === o2.id));
      }
    }
}
</script>
