<template>
    <div class="about">
      <TransitionGroup>
        <div class="card mx-auto my-5 shadow" style="min-width: 18rem; max-width: fit-content;overflow: auto;" v-if="showModal">
          <div class="card-body">
            <h5 class="card-title">
               Invoice Template
            </h5>
            <button type="button" class="btn-close position-absolute fs-4" aria-label="Close" style="right: 5px;top: 5px;" @click.prevent="showModal=false"></button>
            <div class="contain">
              <p class="card-text">The Invoice templates help you generate an invoice on the fly easily. you can modify the invoice while generating</p>
              <div class="row" v-for="r,index in Object.keys(headers).filter(item=>!formHidden.includes(item))" :key="index">
                
                <float-select v-if="r=='acc_id'" label="Bank Account" :options="ddHolder.accounts" v-model="rowData[r]" :disabled="disabled.includes(r)" 
                              :ogDataSrc="ddHolder.accounts.find((b)=>{return b.id==rowData[r]})" :subTexts="['bank_branch.bank.name','bank_branch.name','account_no']"
                                                label-class="text-dark fw-bold" option-class="bg-primary-subtle bg-gradient" />

                <float-select v-else-if="r=='payee_id'" label="Payee" :options="ddHolder.pentities" v-model="rowData[r]" :disabled="disabled.includes(r)" 
                              :ogDataSrc="ddHolder.accounts.find((b)=>{return b.id==rowData[r]})" label-class="text-dark fw-bold" option-class="bg-primary-subtle bg-gradient" />

                <multi-form v-else-if="r=='billables'" :options="ddHolder.billabes" formClass="bg-primary-subtle bg-gradient input" wrapClass="col-12 px-1 mb-1" :has-childlabel="true" :child="taxLabels"
                            label-class="text-dark fw-bold" input-class="bg-primary-subtle bg-gradient input"  label="Billables" :suffix="multiCols.suffix" :prefix="multiCols.prefix"
                            title="Select Billables" :selected="rowData[r]? rowData[r] : []" :subTexts="['currency','cost','hsn']" @updateChoices="this.rowData[r]=$event"/>

                <multi-form v-else-if="r=='tax_id'" :options="ddHolder.taxes" formClass="bg-primary-subtle bg-gradient input" wrapClass="col-12 px-1 mb-1"
                            label-class="text-dark fw-bold" input-class="bg-primary-subtle bg-gradient input"  label="Taxes"
                            title="Select Taxes" :selected="rowData[r]? rowData[r] : []" @updateChoices="this.rowData[r]=$event"/>

                <float-select v-else-if="r=='type'" :options="ddHolder.types" v-model="rowData[r]" :disabled="disabled.includes(r)" :ogDataSrc="ddHolder.types.find((b)=>{return b==rowData[r]})"
                                    :label="headers[r]" label-class="text-dark fw-bold" option-class="bg-primary-subtle bg-gradient" listMode="Array" @change="updateType()"/>
                  
                <float-select v-else-if="r=='recurrence'" :options="ddHolder.recurrence" v-model="rowData[r]" :disabled="disabled.includes(r)" :ogDataSrc="ddHolder.recurrence.find((b)=>{return b==rowData[r]})"
                  :label="headers[r]" label-class="text-dark fw-bold" option-class="bg-primary-subtle bg-gradient" listMode="Array" />
                
                  <div v-else-if="r=='terms'" class="col-12 px-1 mb-1">
                    
                    <termsinput title="Terms of Delivery" :terms="rowData[r].delivery" @terms="rowData[r]['delivery']=$event"/>
                    
                    <termsinput title="Terms of Payment" :terms="rowData[r].payment" @terms="rowData[r]['payment']=$event"/>
                </div>
                
                
                
                <float-inp v-else type="text" :label="headers[r]" v-model="rowData[r]" class="col-12 px-1 mb-1" :disabled="disabled.includes(r)"
                label-class="text-dark fw-bold" input-class="bg-primary-subtle bg-gradient input" />
              </div>
            </div>
            <a href="#" v-if="rowData['id']===null || rowData['id']<1" class="btn btn-primary" @click.prevent="postBranch('post')" >Create Invoice Template</a>
            <a href="#" v-else class="btn btn-success" @click.prevent="postBranch('put')" >Update Invoice Tempalte</a>
          </div>
        </div>
        <cdTable :links="links" title="Invoice Templates" table-name="invoice_tempalte" :hidden="hidden" :headers="headers"
         :gen-form="false" v-else @popForm="e=>setRowData(e)" :multiCols="multiCols"></cdTable>
        
      </TransitionGroup>
      
    </div>
  </template>
  <script>
  /* eslint-disable */
  import termsinput from '@/parts/termsinput.vue';
  import floatInp from '@/parts/floatInp.vue';
  import { dropDownLinks } from '@/cd-links';
  import floatSelect from '@/parts/floatSelect.vue';
  import MultiForm from '@/parts/MultiForm.vue';
  import cdTable from '@/components/cddatatables/cdTable.vue';
  import { invoiceTemplateLinks } from '@/cd-links';
  import taxLabels from '@/parts/taxLabels.vue';
  export default{
    components:{
      cdTable, floatInp, floatSelect, MultiForm, termsinput, taxLabels
    },
    data(){
      return {
        links: invoiceTemplateLinks,
        headers:{
            id: "ID",
            name: "Template Name",
            payee_id:"Payee",
            type: "Type",
            tax_id: "taxes",
            billables: "Billables",
            recurrence: "Recurrence",
            acc_id: "Receiver Bank Account",
            'bank_accounts.name': "Receive Acc.",
            'bank_accounts.bank_branch.bank.name': "Receive Bank.",
            'bank_accounts.bank_branch.bank.id': "Receive Bank ID",
            status: "Status",
            biller_id:"Biller",
            terms: "Terms",            
            note: "Note",
          },
          hidden:[
            'creatorId',
            'createdAt',
            'updatedAt',
            'user_id',
            'payee_id',
            'biller_id',
            'acc_id',
            'start_date',
            'end_date',
            'bank_accounts.bank_branch.bank.id',
            'payee_id',
          ],
          formHidden:[
              'creatorId',
              'createdAt',
              'updatedAt',
              'status',
              'user_id',
              'biller_id',
              'bank_accounts.name',
              'bank_accounts.bank_branch.bank.name',
              'bank_accounts.bank_branch.bank.id',
              'start_date',
              'end_date'
            ],
          multiCols:{
                  cols:[
                    'tax_id',
                    'billables',
                    'terms',
                    'taxes'
                  ],
                  subTexts:{
                    tax_id:["perc"],
                    billables:['currency','cost','perc'],
                    terms:['payment','delivery']
                  },
                  suffix:new Map([
                    ["perc","%"],
                    
                  ]),
                  prefix: new Map([
                  ["hsn","HSN#"], 
                  ])
                },
          disabled:['id'],
          showModal:false,
          rowData:{
            id:null,
            name:null,
            type:null,
            tax_id:[],
            billables:[],
            status:null,
            recurrence:null,
            acc_id:null,
            note:null,
            terms: [
              {payment:[],delivery:[]}
            ] 
          } ,
          ddHolder:{
            accounts:[],
            pentities:[],
            taxes:[],
            types:['One-Off','Recurring'],
            recurrence:['None','Daily','Weekly','Monthly','Yearly'],
          },
          preFetch:false,
          
      }
    },
    methods:{
      updateType(){
        if(this.rowData['type']=='One-Off') {
          this.rowData['recurrence']='None';
          this.disabled.push('recurrence');
        }
        else {
          this.rowData['recurrence']=null;
          this.disabled.splice(this.disabled.indexOf('recurrence'),1);
        }
      },
      async postBranch(mode){
        
        this.loading=true;
        this.rowData.status=true;
        typeof this.rowData.payee_id=='object'? this.rowData.payee_id = this.rowData.payee_id.id : null;
        typeof this.rowData.acc_id=='object'? this.rowData.acc_id = this.rowData.acc_id.id : null;
        /* typeof this.rowData.bank_id=='object'? this.rowData.bank_id = this.rowData.bank_id.id : null;
        typeof this.rowData.branch_id=='object'? this.rowData.branch_id = this.rowData.branch_id.id : null; */
        this.rowData['biller_id']=this.$store.getters.getEntity;
        await this.$store.getters.getAxios(this.links[mode],{method:mode,data:this.rowData})
            .then(resp=>{

              if(resp.data.isLoggedIn){
                this.$store.commit('addAlert', {
                                      title: resp.data.title,
                                      message: resp.data.msg,
                                      type: resp.data.success? 'info' : 'danger'
                                  });
                resp.data.success? this.showModal=false : this.showModal=true;                            
                }
              else this.$store.dispatch('loggedOut');
            })
            // eslint-disable-next-line
            .catch(err=>{
                

            })
      },
      setRowData(e){
        console.log(e);
        this.rowData={...this.rowData,...e.rowData};
        if(this.rowData['billables']==null || this.rowData['billables']==undefined){
          this.rowData['billables']=[];
        }
        if(this.rowData['tax_id']==null || this.rowData['tax_id']==undefined){
          this.rowData['tax_id']=[];
        }
        if(this.rowData.terms==null || this.rowData['terms']==undefined){
          this.rowData['terms']={payment:[],delivery:[]};
        }
        this.showModal=true;
      },
      async getDropDownData(table,listName,filter) {
                    this.loading=true;
                    await this.$store.getters.getAxios.post(dropDownLinks[table],{ent_id:this.$store.getters.getEntity,filter:filter})
                        .then(resp=>{
                            if(!resp.data.isLoggedIn){
                                this.$store.dispatch('loggedOut');
                            }
                            else this.ddHolder[listName] =  resp.data.data;
                        })
                        // eslint-disable-next-line
                        .catch(err=>{
                            this.$store.commit('addAlert', {
                                title: "Error Getting DropDown Data for "+listName,
                                message: "Try after some time",
                                type: 'danger'
                            });
        
                        })
      }
    },
    async mounted(){
        await this.getDropDownData('accounts','accounts',0);
        await this.getDropDownData('pentities','pentities',0);
        await this.getDropDownData('taxes','taxes',0);
        await this.getDropDownData('billables','billabes',0);
        /* this.getDropDownData('branches','branches'); */
    }
  }
  </script>
  