<style>
 @import "../../assets/css/advert/advmanager";
</style>
<template>
    <div class="advmanager-box">
        <div class="query-box">
            <ul>
                <!-- <li>
                    <span>{{$t('advmanager.v_line')}}：</span>
                    <el-select v-model="msg.lineId" clearable  class="w150" filterable @change="changeLine">
                        <el-option :label="$t('advmanager.v_all')" value='0' ></el-option>
                        <el-option v-for='item in lines'
                            :key="item.lineID" 
                            :label="item.lineName"
                            :value="item.lineID">
                        </el-option>
                    </el-select>
                </li>
                <li>
                    <span>{{$t('advmanager.v_xilie')}}：</span>
                    <el-select v-model="msg.teamId" clearable  class="w150" >
                        <el-option :label="$t('advmanager.v_all')" value='0'></el-option>
                        <el-option v-for='item in teams'
                            :key="item.LtID" 
                            :label="item.LtName"
                            :value="item.LtID">
                        </el-option>
                    </el-select>
                </li> -->
                <li>
                    <span>{{$t('advmanager.v_country')}}：</span>
                    <el-select v-model="msg.countryId" clearable  class="w150"  filterable>
                        <el-option :label="$t('advmanager.v_all')" value='0'></el-option>
                        <el-option v-for='item in countrys'
                            :key="item.ID" 
                            :label="item.Name"
                            :value="item.ID">
                        </el-option>
                    </el-select>
                </li>
                <li>
                    <span>{{$t('advmanager.v_type')}}：</span>
                    <el-select v-model="msg.type"  class="w150" clearable filterable>
                        <el-option :label="$t('advmanager.v_all')" value='0'></el-option>
                        <el-option :label="$t('advmanager.v_shoufei')" value='1'></el-option>
                        <el-option :label="$t('advmanager.v_free')" value='2'></el-option>
                    </el-select>
                </li>
                <li>
                    <button class="normalBtn" type="button" @click="openaddbox">{{$t('pub.addBtn')}}</button>
                    <button class="hollowFixedBtn" type="button" @click="getaddatas(0)">{{$t('pub.searchBtn')}}</button>
                </li>
            </ul>
        </div>
        <div class="content" :class="{showAddBox:isAdd}" >
            <vueWaterfallEasy :imgsArr="addatas" @scrollReachBottom="handleCurrentChange" :maxCols='7' :imgWidth='208' :enablePullDownEvent='true'>
                <template slot-scope="props">
                    <span class="money" v-if="props.value.IsFee==1">￥{{props.value.ChargeAmount.toFixed(2)}}</span>
                    <span class="free" v-else>{{$t('advmanager.v_free')}}</span>
                    <div class="star-box">
                        <i class="iconfont icon-star star"></i>&nbsp; {{props.value.AdvertisingCount}}
                    </div>
                    <div class="zezhao">
                        <i class="el-icon-edit" :title="$t('pub.updateMsg')"  @click="update(props.value)"></i>
                        <i class="el-icon-delete" :title="$t('system.table_delete')"  @click="deleteItem(props.value)"  ></i>
                    </div>
                </template>
            </vueWaterfallEasy>
        </div>
        <div class="add-box query-box" v-show="isAdd">
            <ul>
                <!-- <li>
                    <span>{{$t('advmanager.v_line')}}：</span>
                    <el-select v-model="model.LineID" clearable  class="w150" @change="changeLineForm">
                        <el-option v-for='item in lines'
                            :key="item.lineID"
                            :label="item.lineName"
                            :value="item.lineID">
                        </el-option>
                    </el-select>
                </li>
                <li>
                    <span>{{$t('advmanager.v_xilie')}}：</span>
                    <el-select v-model="model.SeriesID" clearable  class="w150"  filterable>
                        <el-option v-for='item in modelTeams'
                            :key="item.LtID" 
                            :label="item.LtName"
                            :value="item.LtID">
                        </el-option>
                    </el-select>
                </li>                 -->
                <li>
                    <span>{{$t('advmanager.v_type')}}：</span>
                    <el-select v-model="model.IsFee"  class="w150" clearable filterable>
                        <el-option :label="$t('advmanager.v_shoufei')" value='1'></el-option>
                        <el-option :label="$t('advmanager.v_free')" value='2'></el-option>
                    </el-select>
                </li>
                <li>
                    <span>{{$t('advmanager.v_country')}}：</span>
                    <el-select v-model="CountryID" multiple collapse-tags clearable class="w240" filterable>
                        <el-option v-for='item in countrys'
                            :key="item.ID"
                            :label="item.Name"
                            :value="item.ID">
                        </el-option>
                    </el-select>
                </li>
                <li v-show='model.IsFee=="1"'>
                    <span>收费金额：</span>
                    <el-input v-model="model.ChargeAmount"  class="w150" clearable filterable></el-input>
                </li>
                <li>
                    
                </li>
            </ul>
            <div class="upload-box">
                <input type="file" value="" ref="loadFile" @change="upload" style="display:none;"/>
                <label>底图：</label>
                <div class="upload-box-normal" v-if='model.PictureUrl==""' @click="openupload(0)" >
                    <i class="iconfont icon-img_jiahao_big"></i>
                </div>
                <div class="upload-box-img" v-else>
                    <img :src='model.PictureUrl'>
                    <div class="zezhao">
                        <i class="el-icon-delete" title="删除" @click="deletePic(0)"></i>
                    </div>
                </div>
                <label>原图：</label>
                <div class="upload-box-normal" v-if='model.SamplePicturesUrl==""' @click="openupload(1)" >
                    <i class="iconfont icon-img_jiahao_big"></i>
                </div>
                <div class="upload-box-img" v-else>
                    <img :src='model.SamplePicturesUrl'>
                    <div class="zezhao">
                        <i class="el-icon-delete" title="删除"  @click="deletePic(1)"></i>
                    </div>
                </div>
            </div>
            <div class="opera-btn-box">
                <button class="normalBtn" type="button" @click="save">{{$t('pub.saveBtn')}}</button>
                <button class="hollowFixedBtn" type="button" @click="close">{{$t('pub.cancelBtn')}}</button>
            </div>
        </div>
        <!-- <el-pagination background @current-change="handleCurrentChange" :current-page.sync="pageIndex" layout="total,prev, pager, next, jumper" :page-size="pageSize" :total="total">
        </el-pagination> -->
    </div>
</template>

<script>
import vueWaterfallEasy from 'vue-waterfall-easy'
export default {
    data(){
        return{
            lines:[],
            teams:[],
            modelTeams:[],
            countrys:[],
            addatas:[],
            CountryID:[],
            pageIndex:0,
            pageSize:50,
            total:0,
            msg:{
                lineId:'0',
                teamId:'0',
                countryId:'0',
                type:'0'
            },
            user:{},
            model:{},
            isAdd:false,
            uploadType:0
        }
    },
    mounted(){
        this.user=JSON.parse(window.localStorage.userInfo)
        this.getline()
        this.getcountry()
        this.getaddatas(0)
    },
    components: {
        vueWaterfallEasy
    },
    methods:{
        deleteItem(x){
            this.apipost("Advertising_post_DelAdvertising", {'BAID':x.ID}, x => {
                if(x.data.resultCode==1){
                    this.$message.success('删除成功')
                    this.getaddatas(0)
                }else{
                    this.$message.error(x.data.message)
                }
            },err => {})
        },
        update(x){
            this.CountryID=[];
            this.getmodelTeams(x.LineID);
            x.CountryIds.forEach(y=>{
                this.CountryID.push(y.CountryID);
            })
            this.model={
                ID:x.ID,
                LineID:x.LineID,
                SeriesID:x.SeriesID,
                CountryID:x.CountryID,
                ScenicSpotID:x.ScenicSpotID,
                PictureUrl:x.PictureUrl,
                SamplePicturesUrl:x.SamplePicturesUrl,
                Title:x.Title,
                ChargeAmount:x.ChargeAmount,
                IsFee:x.IsFee.toString()
            }
            this.isAdd=true
        },
        close(){
            this.isAdd=false
        },
        save(){
            console.log(this.model.SeriesID)
            if(this.model.LineID==''){
                this.$message.error('请选择线路')
            }else if(this.model.SeriesID===''){
                this.$message.error('请选择系列')
            }else if(this.CountryID.length==0){
                this.$message.error('请选择国家')
            }else if(this.model.IsFee==''){
                this.$message.error('请选择类型')
            }else if(this.model.ChargeAmount==''&&this.model.IsFee=='1'){
                this.$message.error('请填写金额')
            }else if(Number.isNaN(this.model.ChargeAmount)&&this.model.IsFee=='1'){
                this.$message.error('填写金额非法')
            }else if(this.model.PictureUrl==''){
                this.$message.error('请选择广告图')
            }else if(this.model.SamplePicturesUrl==''){
                this.$message.error('请选择原图')
            }else{
                this.model.CountryIDs = this.CountryID;
                this.model.ChargeAmount=this.model.IsFee=='1'?this.model.ChargeAmount:'0'
                this.uploadImage(0)
            }
        },
        base64ToBlob(code) {
            let parts = code.split(';base64,');
            let contentType = parts[0].split(':')[1];
            let raw = window.atob(parts[1]);
            let rawLength = raw.length;

            let uInt8Array = new Uint8Array(rawLength);

            for (let i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([uInt8Array], {type: contentType});
        },
        uploadImage(cnt) {
            console.log(this.model)
            if(cnt==2){
                this.apipost("Advertising_post_SetAdvertising", this.model, x => {
                    if(x.data.resultCode==1){
                        this.$message.success('保存成功');
                        this.isAdd=false;
                        this.CountryID = [];
                        this.getaddatas(0);
                    }else{
                        this.$message.error(x.data.message)
                    }
                },err => {})
            } else {
                let dataUrl=cnt==0?this.model.PictureUrl:this.model.SamplePicturesUrl
                console.log(dataUrl.indexOf('base64'))
                if(dataUrl.indexOf('base64')==-1){
                    if(cnt==0){
                        this.model.PictureUrl=`/Adv${this.model.PictureUrl.split('/Adv')[1]}`
                    }else{
                        this.model.SamplePicturesUrl=`/Adv${this.model.SamplePicturesUrl.split('/Adv')[1]}`
                    }
                    this.uploadImage(cnt+1)
                } else {
                    let file=this.base64ToBlob(dataUrl)
                    let newArr = []
                    newArr.push(file)
                    var path = `/Adv/template/${this.uuid(10,10)}.jpg`
                    let that=this
                    this.uploadBlob(path, newArr, x => {
                        if(cnt==0){
                            that.model.PictureUrl=path
                            that.uploadImage(1)
                        }else{
                            that.model.SamplePicturesUrl=path
                            that.uploadImage(2)
                        }
                    })
                }
            }
        },
        uuid(len, radix) {
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            var uuid = [], i;
            radix = radix || chars.length;
            if (len) {
                // Compact form
                for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
            } else {
                var r;
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';
                for (i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random()*16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }
            return uuid.join('');
        },
        deletePic(type){
            if(type==0)
                this.model.PictureUrl=''
            else
                this.model.SamplePicturesUrl=''
        },
        upload(){
            if(this.$refs.loadFile.files.length>0 && this.$refs.loadFile.files[0].size>0){
                let reader = new FileReader()
                let that=this
                reader.readAsDataURL(this.$refs.loadFile.files[0])
                reader.onload=function(e) {
                    if(that.uploadType==0)
                        that.model.PictureUrl=e.target.result
                    else
                        that.model.SamplePicturesUrl=e.target.result
                }
                this.$refs.loadFile.value = "";
            }
        },
        openupload(t){
            this.uploadType=t
            this.$refs.loadFile.click()
        },
        getmodelTeams(t){
            let msg={
                'RB_Branch_id':this.user.RB_Branch_id,
                'isTOOP':1,
                'lineID':t==0?this.lines[0].lineID:t
            }
            this.apipost("team_post_GetList", msg, x => {
                this.modelTeams=x.data.data
                if(t==0)
                    // this.model.SeriesID=this.modelTeams[0].LtID  没这LtID 要报错
                    this.model.SeriesID = 0;
            },err => {})
        },
        openaddbox(){
            this.CountryID = [];
            this.getmodelTeams(0)
            this.model={
                ID:0,
                LineID:this.lines[0].lineID,
                SeriesID:0,
                CountryID:this.countrys[0].ID,
                ScenicSpotID:0,
                PictureUrl:'',
                SamplePicturesUrl:'',
                Title:'无',
                ChargeAmount:'1.00',
                IsFee:'2'
            }
            this.isAdd=true
        },
        handleCurrentChange() {
            console.log('in.................')
            this.pageIndex++
            this.getaddatas(1)
            
        },
        getaddatas(type){
            if(type==0){
                this.pageIndex=0
            }
            let msg={
               pageIndex:this.pageIndex,
               pageSize:this.pageSize,
               lineId:this.msg.lineId,
               SeriesId:this.msg.teamId,
               CountryId:this.msg.countryId,
               AdvName:'',
               IsFee:this.msg.type
            }
            this.apipost("Advertising_get_GetAdvertisingList", msg, x => {
                
                x.data.data.pageData.forEach(x=>{
                    x.src=`${x.SamplePicturesUrl}?x-oss-process=image/resize,w_200`
                    x.id=x.ID
                })
                if(type==0){
                    this.addatas=x.data.data.pageData
                }else{
                    this.addatas=this.addatas.concat(x.data.data.pageData)
                }
                this.total=x.data.data.count
            },err => {})
        },
        getcountry(){
            this.apipost("dict_post_Destination_GetCountry", {}, x => {
                this.countrys=x.data.data
            },err => {})
        },
        getteam(){
            // console.log(this.msg.lineId)
            let msg={
                'RB_Branch_id':this.user.RB_Branch_id,
                'isTOOP':1,
                'lineID':this.msg.lineId
            }
            this.apipost("team_post_GetList", msg, x => {
                this.teams=x.data.data
                 if(x.data.data.length>0)
                        this.msg.teamId=x.data.data[0].LtID
            },err => {})
        },
        changeLine(){
            // console.log(this.msg.lineId!==0)
            this.teams.splice(0,this.teams.length-1)
            if(this.msg.lineId!==0){
                this.getteam()
            }
        },
        changeLineForm(){
            // console.log(this.model.lineId)
            this.modelTeams.splice(0,this.modelTeams.length-1)
            if(this.model.LineID!==0&&this.model.LineID!=''){
                let msg={
                    'RB_Branch_id':this.user.RB_Branch_id,
                    'isTOOP':1,
                    'lineID':this.model.LineID
                }
                this.apipost("team_post_GetList", msg, x => {
                    this.modelTeams=x.data.data
                    if(x.data.data.length>0)
                        this.model.SeriesID=x.data.data[0].LtID
                },err => {})
            }
        },
        getline(){
            let msg={'pageIndex':0,'pageSize':100}
            this.apipost("line_post_GetPageList", msg, x => {
                this.lines=x.data.data.pageData
                console.log(this.lines)
            },err => {})
        }
    }
}
</script>

