(async function () {

    Vue.prototype.$accounts = window.ctp.accounts;


    Vue.prototype.$types = window.ctp.types;

    Vue.component('job-card-items', {
        props: ['items'],
        methods: {
            removeItem: function (index) {

            }
        },
        template: `
<!--                <item-rows  v-for="(item,index) in items"-->
<!--                            v-bind:key="index"-->
<!--                            v-bind:index="index"-->
<!--                            v-bind:item="item"-->
<!--                            v-on:remove-item="removeItem">            -->
<!--                </item-rows>-->
        `,


    });


    Vue.component('job-card-item', {
        props: ['index', 'item', 'items'],
        methods: {
            removeItem: function (e) {
                if (confirm('Do want to delete Item?')) {
                    if (this.items[this.index].id === 0) {
                        this.items.splice(this.index, 1);
                    } else {
                        // post request and reload page on success
                        $.ajax({
                            url: '/ctp/rest/job-cards?job-card-item-id=' + this.items[this.index].id,
                            method: 'POST',
                            contentType: 'application/json',
                            dataType: 'json',
                            success: function (data) {
                                location.reload();
                            },
                            error: function (err) {
                                console.log(err)
                                location.reload();
                            }
                        });
                    }
                }
            },
            addPieces: function (e) {
                e.preventDefault();
                this.item.cutPieces.push({
                    'id': 0,
                    'jobCardItemId': 0,
                    'type': '',
                    'quantity': 0
                })
            },
            removePiece: function (index) {
                if (confirm('Do want to delete Item?')) {
                    if (this.item.cutPieces[index].id === 0) {
                        this.item.cutPieces.splice(index, 1);
                    } else {
                        // post request and reload page on success
                        $.ajax({
                            url: '/ctp/rest/cut-pieces?cut-piece-id=' + this.item.cutPieces[index].id,
                            method: 'POST',
                            contentType: 'application/json',
                            dataType: 'json',
                            success: function (data) {
                                location.reload();
                            },
                            error: function (err) {
                                console.log(err)
                                location.reload();
                            }
                        });
                    }
                }
            },
            onItemSelect(itemId, invItem) {
                this.item.itemId = invItem.id;
                this.item.sku = invItem.sku;
            }
        },
        template: `
                <div class="form-row position-relative border-bottom my-4">
                     <input hidden="hidden" v-bind:name="'items[' + index + '].id'" v-bind:value="item.id">
                     <input hidden="hidden" v-bind:name="'items[' + index + '].sku'" v-bind:value="item.sku">
                     <input hidden="hidden" v-bind:name="'items[' + index + '].totalProduction'" v-bind:value="item.totalProduction">
                     <input hidden="hidden" v-bind:name="'items[' + index + '].actualProduction'" v-bind:value="item.actualProduction">
                     <div class="col-sm-3 form-group">
                        <item-search
                                v-bind:id-field-name="'items[' + index + '].itemId'"
                                v-bind:id="item.itemId"
                                v-bind:title="item.title"
                                v-on:item-select="onItemSelect"
                                v-bind:show-label="true"
                                v-bind:requuired="true">                               
                        </item-search>
                     </div>
                      <div class="col-sm-3 form-group">
                            <label>Sku</label>
                            <span class="form-control"  readonly >{{item.sku}}</span> 
                      </div>
                      <div class="col-sm-2 form-group">
                            <label>Expected Quantity</label>
                            <input type="number" class="form-control" v-bind:name="'items[' + index + '].expectedProduction'" v-model="item.expectedProduction" required>
                      </div>
                      <div class="col-sm-1 form-group">
                            <label>Length</label>
                            <input type="text" class="form-control" v-bind:name="'items[' + index + '].length'" v-model="item.length" required>
                      </div>
                      <div class="col-sm-1 form-group">
                            <label>Width</label>
                            <input type="text" class="form-control" v-bind:name="'items[' + index + '].width'" v-model="item.width" required>
                      </div>
                      <div class="col-sm-1 form-group">
                            <label>GSM</label>
                            <input type="text" class="form-control" v-bind:name="'items[' + index + '].gsm'" v-model="item.gsm" required>
                      </div>
                      <div class="col-sm-1 form-group">
                            <label>WT./Ply</label>
                            <input type="text" class="form-control" v-bind:name="'items[' + index + '].wtPly'" v-model="item.wtPly" required>
                      </div>
                      <div class="col-sm-1 form-group">
                            <label>Number of Ply</label>
                            <input type="text" class="form-control" v-bind:name="'items[' + index + '].ply'" v-model="item.ply" required>
                      </div>
                      <div class="col-sm-3 form-group">
                            <label>Cutting Account</label>
                            <select class="form-control"  v-bind:name="'items[' + index + '].accountId'" v-model="item.accountId" required >
                                <option>Please Select</option>
                                <option v-for="(account, index) in $accounts"
                                 v-bind:value="account.id"
                                 v-bind:selected="account.id == item.accountId">{{account.title}}</option>
                            </select>
                      </div>                       
                      <div class="col-sm-1">
                            <label class="d-block">&nbsp;</label>
                            <a href="#" title="Remove" class="btn btn-light text-left" v-on:click="removeItem" >
                                <i class="bi bi-trash"></i>
                            </a>
                      </div>
                      <div class="col-sm-12">
                          <div class="col-sm-4 border bg-white form-group p-3">
                                <h6 class="mb-3">Cut Panels</h6>
                                <cut-piece v-for="(piece, cIndex) in item.cutPieces"
                                    v-bind:index="cIndex"
                                    v-bind:pIndex="index"
                                    v-bind:piece="piece"
                                    v-bind:key="index + '-' + cIndex"
                                    v-on:piece-remove="removePiece">
                                </cut-piece>
                                  <label class="d-block">&nbsp;</label>
                                  <a href="#" title="Add Cut Panels" class="btn btn-light text-left" v-on:click="addPieces" >
                                        <i class="bi-plus-circle-fill"></i>
                                  </a>
                          </div>                                            
                      </div>

                         
                </div>
        `
    });

    Vue.component('cut-piece', {
        props: ['index', 'piece', 'pIndex'],
        methods: {
            removePiece: function (e) {
                e.preventDefault();
                this.$emit('piece-remove', this.index)
            }
        },
        template: `
           <div class="row mt-1">
                <input hidden="hidden" v-bind:name="'items[' + pIndex + '].cutPieces[' + index  +'].id'" v-bind:value="piece.id">
                <input hidden="hidden" v-bind:name="'items[' + pIndex + '].cutPieces[' + index  +'].jobCardItemId'" v-bind:value="piece.jobCardItemId">
                <div class="col-md-5">
                    <select class="form-control" v-bind:name="'items[' + pIndex + '].cutPieces[' + index  +'].type'" v-model="piece.type" required>
                        <option value="">Please Select</option>
                        <option v-for="(type,index) in $types"
                             v-bind:selected="type.title === piece.type"
                            v-bind:value="type.title">{{type.title}}</option>
                    </select>
                </div>
                <div class="col-md-5">
                    <input type="number" class="form-control" v-bind:name="'items[' + pIndex + '].cutPieces[' + index  +'].quantity'" v-model="piece.quantity" required>
                </div>
                 <div class="col-md-1">
                  <span class="bi-trash2-fill btn" title="Remove Piece" v-on:click="removePiece" ></span>
                </div>    
          </div>
       `

    });


    let app = new Vue({
        el: '#jobCardApp',
        data: {
            jobCard: {},
            items: [],
        },
        methods: {
            addItem: function (e) {
                e.preventDefault();
                this.items.push(this.createNewItem())
            },
            createNewItem: function () {
                return {
                    'id': 0,
                    'jobCardId': 0,
                    'itemId': 0,
                    'sku': '',
                    'expectedProduction': 0.0,
                    'actualProduction' : 0.0,
                    'length' : '',
                    'width' : '',
                    'gsm' : '',
                    'wtPly' : '',
                    'ply' : '',
                    'accountId' : 0,
                    cutPieces: []
                }
            },
            removeItem: function () {
                e.preventDefault();

            },
            hasDuplicates: function () {
                const ids = this.items.map(item => item.itemId);
                const uniqueIds = new Set(ids);
                return ids.length !== uniqueIds.size;
            },
            hasEmptyItems: function () {
                if( this.items.length === 0 ) return true;
                for( let x of this.items ){
                    if( x.itemId === 0 ){
                        return true;
                    }
                }
               return false;
            }
        },
        mounted: function () {
            this.jobCard = window.ctp.jobCard;
            this.items = this.jobCard.items;

        }
    });

})(jQuery);