<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
    <meta charset="utf-8">
    <title>Auto resize design</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.3/font/bootstrap-icons.css">


    <style media="screen">
        img {
            max-width: 100%;
            max-height: 400px;
            width: auto;
            border: 1px solid black;
            background-color: #777777;
            object-fit: contain;
        }
        [v-cloak] {
            display: none;
        }
    </style>
</head>

<body>
    <div v-cloak id="app" class="container" >
        <h1>Auto resize design</h1>
        <div class="form-group">
            <label for="" title="OK">Product Url</label>
            <input v-model="productUrl" class="form-control" type="text" name=""  placeholder="Product URL">
        </div>
        <div class="form-group">
            <button @click="fetch()" type="button" class="btn btn-primary btn-lg btn-block" v-if="!loading">Fetch design</button>
            <button type="button" class="btn btn-primary btn-lg btn-block" v-if="loading"><span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Loading</button>
        </div>
        <ul class="nav nav-pills">
            <li class="nav-item" v-for="template in templates"><a class="nav-link"  @click="setTemplate(template, true)" aria-current="page">@{{ template.name }}</a></li>
        </ul>
        <br>

        <div class="form-group mb-4">
            <p class="mb-2">Lấy ảnh design theo mẫu có sẵn:</p>
            <div class="row box-btns mb-3">
                <div class="col-md-3" v-for="template in templates" v-show="template.name === 'Garden Flag - Yiwang'">
                    <button class="box-btns__item btn btn-info btn-lg" @click="setTemplate(template, false)"> Flag - Yiwang </button>
                </div>
            </div>
        </div>

        <div class="form-group" v-if="isTemplateOld">

            <div class="row">
                <div class="col">
                    <label for="">Width</label>
                    <input v-model="width" class="form-control" type="text" name=""  placeholder="Width">
                </div>
                <div class="col">
                    <label for="">Height</label>
                    <input v-model="height" class="form-control" type="text" name=""  placeholder="Height">
                </div>
                <div class="col">
                    <label for="">Anchor</label>
                    <select class="form-control" name="" v-model="anchor">
                        <option value="center">Center</option>
                        <option value="top">Top</option>
                        <option value="top">Bottom</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="form-group" v-if="isTemplateOld">

            <div class="row">
                <div class="col col-2">
                    <label for="" title="Preview color: Không làm thay đổi nền design, chỉ dùng cho xem thử">Preview Color: </label>
                    <input v-model="color" class="form-control" type="color" name=""  >
                </div>
                <div class="col col-2">
                    <label for="" title="Đổ màu: Thay nền của design, dùng để đổ cho cờ, cốc, sticker, ...">Đổ màu : @{{ bgColor ? bgColor : 'Trong suốt' }}</label>
                    <input v-model="bgColor" class="form-control" type="color" name=""  placeholder="Màu nền">
                </div>
                <div class="col col-2">
                    <label title="Double sides : Dành cho vật phẩm 2 mặt như cốc, gối" >Double Sides? </label>
                    <input v-model="isDoubleSides" class="form-control" type="checkbox" name=""  >
                </div>
                {{-- <div class="col col-2 ">
                    <label for="" title="Trim : Căn ảnh vào giữa, nhưng sẽ bị chậm đi.">Trim? </label>
                    <input v-model="trim" class="form-control" type="checkbox" name=""  >
                </div> --}}
                <div class="col ">
                    <label for="" title="Độ to: Giảm xuống nếu desize to<">Độ to: @{{ percent }}%</label>
                    <input v-model="percent" class="form-control" type="text" name=""  >
                </div>
                <div class="col ">
                    <label for="" title="Offset: < 0 nếu dịch sang trái">Lệch trái: @{{ offset }}%</label>
                    <input v-model="offset" class="form-control" type="text" name=""  >
                </div>
                <div class="col ">
                    <label for="" title="Cho tụt xuống dưới">Lệch xuống: @{{ yoffset }}%</label>
                    <input v-model="yoffset" class="form-control" type="text" name=""  >
                </div>
            </div>
        </div>
        
        {{-- <div class="form-group">
            <div class="row">
                <div class="col col-2">
                    <label for="" title="Đổ màu: Thay nền của design, dùng để đổ cho cờ, cốc, sticker, ...">Đổ màu : @{{ bgColor ? bgColor : 'Trong suốt' }}</label>
                    <input v-model="bgColor" class="form-control" type="color" name=""  placeholder="Màu nền">
                </div>
            </div>
        </div> --}}

        <div class="row mb-3" v-if="design" >
            <div class="col text-center">
                <div class="design text-center mb-3 d-inline-block">
                    <img width="4200" height="4800" :src="design.image_url"
                    v-bind:style="{ backgroundColor: color }"
                    alt="">

                    <div class="input-group mt-4" @click="copy(design)">
                        <input id="url_image" type="text" class="form-control" v-model="design.image_url" readonly>
                        <div class="input-group-append">
                            <button class="btn btn-outline-primary" type="button">
                                <span v-if="design.copied">Copied</span>
                                <span v-if="!design.copied">Copy</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div v-if="designs" class="row mb-3" v-for="(design, key) in designs">
            <div class="col">
                <div class="design text-center mb-3">
                    <img width="4200" height="4800" :src="design.image_url"
                    v-bind:style="{ backgroundColor: color }"
                    alt="">
                </div>
                <div class="input-group" @click="convert(key)" v-if="!design.loading">
                    <input type="text" class="form-control" v-model="design.resolution" readonly>
                    <input type="text" class="form-control" v-model="design.position" v-if="design.position" readonly>
                    <div class="input-group-append">
                        <button class="btn btn-outline-primary" type="button">Convert</button>
                    </div>
                </div>
                <div class="input-group" v-if="design.loading">
                    <input type="text" class="form-control" v-model="design.resolution" readonly>
                    <input type="text" class="form-control" v-model="design.position" v-if="design.position" readonly>
                    <div class="input-group-append">
                        <button class="btn btn-outline-primary" type="button"><span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Converting</button>
                    </div>
                </div>
            </div>
            <div class="col" v-if="!design.convert">

            </div>
            <div class="col" v-if="design.convert">
                <div class="design text-center mb-3">
                    <img width="4200" height="4800" :src="design.convert"
                    v-bind:style="{ backgroundColor: color }"
                    alt="">
                </div>

                <div class="input-group" @click="copy(design)">
                    <input type="text" class="form-control" v-model="design.convert" readonly>
                    <div class="input-group-append">
                        <button class="btn btn-outline-primary" type="button">
                            <span v-if="design.copied">Copied</span>
                            <span v-if="!design.copied">Copy</span>
                        </button>
                    </div>
                </div>
            </div>

        </div>
    </div>
    <script src="https://unpkg.com/vue@3"></script>
    <script src="https://unpkg.com/axios@0/dist/axios.min.js"></script>
    <script src="https://unpkg.com/clipboard@2/dist/clipboard.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js" charset="utf-8"></script>
    <script>

      const { createApp } = Vue
      createApp({
        data() {
          return {
            message: 'Hello Vue!',
            productUrl : 'https://printerval.com/roma-italia-t-shirt-p8969086?spid=159667709',
            designUrl : '',
            loading: false,
            color: '#777777',
            width: 4200,
            height: 4800,
            msg: '',
            designs: null,
            design: null,
            isTemplateOld:true,
            anchor: 'center',
            country: 'us',
            bgColor: null,
            isDoubleSides: false,
            trim: false,
            percent: 100,
            offset: 0,
            yoffset: 0,
            templates : [
                {
                    name: "Merchize Classic Women T-Shirt",
                    template : {
                        width: 4200,
                        height: 4800,
                        anchor: 'center',
                        bgColor: null,
                        isDoubleSides: false,
                        percent: 100,
                        offset: 0,
                    }
                },
                {
                    name: "Printify Square Pillow",
                    template : {
                        width: 6450,
                        height: 3225,
                        anchor: 'center',
                        // bgColor: '#000000',
                        isDoubleSides: true,
                        percent: 60,
                        offset: 0,
                    }
                },
                {
                    name: "White Mug, 11oz - District Photo",
                    template : {
                        width: 2475,
                        height: 1155,
                        anchor: 'center',
                        // bgColor: '#ffffff',
                        isDoubleSides: true,
                        percent: 50,
                        offset: -9.5,
                    }
                },
                {
                    name: "Black Mug, 11oz - District Photo",
                    template : {
                        width: 2475,
                        height: 1155,
                        anchor: 'center',
                        // bgColor: '#000000',
                        isDoubleSides: true,
                        percent: 50,
                        offset: -5.7,
                    }
                },
                {
                    name: "White Mug, 15oz - District Photo",
                    template : {
                        width:  2475,
                        height: 1155,
                        anchor: 'center',
                        // bgColor: '#ffffff',
                        isDoubleSides: true,
                        percent: 50,
                        offset: -6.7,
                    }
                },
                {
                    name: "Black Mug, 15oz - District Photo",
                    template : {
                        width:  2448,
                        height: 1266,
                        anchor: 'center',
                        // bgColor: '#000000',
                        isDoubleSides: true,
                        percent: 50,
                        offset: -5.5,
                    }
                },
                {
                    name: "Garden Flag - Yiwang",
                    template : {
                        width:  3300,
                        height: 4600,
                        anchor: 'center',
                        // bgColor: '#ffffff',
                        isDoubleSides: false,
                        percent: 50,
                        offset: 0,
                        yoffset: 5,
                    }
                },
                {
                    name: "Horizontal Flag - Merchize",
                    template : {
                        width:  4600,
                        height: 3300,
                        anchor: 'center',
                        // bgColor: '#ffffff',
                        isDoubleSides: false,
                        percent: 50,
                        offset: 4,
                        yoffset: 0,
                    }
                },

            ]
          }
      },
        methods : {
            fetch : function () {
                let self = this;
                try {
                    if (self.productUrl.includes('https://drive.google.com')) {
                        this.getGoogleDesign()
                    } else {
                        self.parseCountry();
                        let url = new URL(this.productUrl);
                        let productId = /-p(\d+)($|\?)/.exec(this.productUrl)[1];
                        let spid = /spid=(\d+)/.exec(this.productUrl)[1];
                        this.getDesign(productId, spid);
                    }
                } catch (e) {
                    alert("URL không hợp lệ");
                    return;
                }
            },
            parseCountry () {
                let self = this;                                                  
                self.country  = 'us';
                let exec = /printerval\.com\/([a-z]{2})\//.exec(this.productUrl);
                if (exec && exec[1]) {
                    self.country = exec[1];
                }
            },

            getDesign : function (productId, spid) {
                let self = this;
                self.loading = true;
                let url = `https://api.printerval.com/design?scopes=getDesignByProductId(productId=${productId})&service_token=megaads@123`;
                if (self.isTemplateOld) {
                    if (self.country != 'us') {
                        url = `https://${self.country}.api.printerval.com/design?scopes=getDesignByProductId(productId=${productId})&service_token=megaads@123`;
                    }
                } else {
                    url = `/module/pod/fill-design-background/?product_id=${productId}&product_sku_id=${spid}`;
                
                }

                axios.get(url)
                  .then(function (response) {
                    if(response.status == 200) {
                        
                        if (self.isTemplateOld) {
                            self.designs = response.data.result;
                        } else {
                            self.design = {};
                            self.design.image_url = response.data[`${productId}_${spid}`];
                        }
                    }
                  })
                  .catch(function (error) {
                    alert("URL không hợp lệ");
                    console.log('function getDesign has something wrong!');
                  })
                  .then(function () {
                    self.loading = false;
                  });
            },
            getGoogleDesign : function () {
                let self = this;
                let match = self.productUrl.match(/\/d\/([a-zA-Z0-9-_]+)/);
                if (match && match[1]) {
                    self.designs = [
                        {
                            image_url : `https://drive.google.com/uc?id=${match[1]}`
                        }
                    ];
                }
            },
            convert : function (key) {
                let self = this;
                self.designs[key].loading = true;
                self.designs[key].convert = null;
                let url = `/print-suppliers/resize-design`;
                axios.post(url, {
                    url : self.designs[key].image_url,
                    width: self.width,
                    height: self.height,
                    anchor: self.anchor,
                    bgColor: self.bgColor,
                    isDoubleSides: self.isDoubleSides,
                    percent: self.percent,
                    offset: self.offset,
                    trim : self.trim,
                    yoffset: self.yoffset,
                }).then(function (response) {
                    self.designs[key].convert = response.data;
                 })
                 .catch(function (error) {
                   console.log('function convert has something wrong!');
                 })
                 .then(function () {
                   self.designs[key].loading = false;
                 });

            },
            setTemplate: function (template, isOldTemplate) {
                let self = this;
                self.designs = null;
                self.design = null;
                self.isTemplateOld = isOldTemplate;
                self.width = template.template.width;
                self.height = template.template.height;
                self.anchor = template.template.anchor;
                self.bgColor = template.template.bgColor;
                self.isDoubleSides = template.template.isDoubleSides;
                self.percent = template.template.percent;
                self.offset = template.template.offset;
                self.yoffset = template.template.yoffset;
            },
            copy : function (design) {
                design.copied = true;
                document.getElementById("url_image").select();
                document.execCommand("copy");
                setTimeout(() => design.copied = false, 2000);
            }
        }
      }).mount('#app')
    </script>
</body>

</html>
