<template>
     <div class="history_page">
        <div class="page_content">
            <img
                class="page_content_bg"
                src="@/assets/images/homePage/bg.png"
            />
            <div class="page_content_body">
                <!-- <HeaderComponent></HeaderComponent> -->
                <div class="history_page_body">
                    <!-- <div class="history_header">{{ $t('HistoryPage.History') }}</div> -->
                    <div class="history_table_search">
                        <a-range-picker class="range_picker" v-model:value="rangePickerValue" :placeholder="[$t('HistoryPage.StartDate'), $t('HistoryPage.EndDate')]" valueFormat="YYYY-MM-DD">
                            <template #suffixIcon>
                                <span class="icon iconfont range_picker_icon icon-rili"></span>
                            </template>
                        </a-range-picker>
                        <div class="content_search_block">
                            <input class="search_input" :placeholder="$t('HistoryPage.inputContent1')" v-model="searchCollectionName"  @keydown.enter="searchHistoryList()">
                            <div class="search_icon_block" @click="searchHistoryList()"><span class="icon iconfont icon-sousuo"></span></div>
                        </div>
                    </div>

                    <div class="history_table_content" ref="historyTable">
                         <a-table :columns="columns" :data-source="collectionList" :scroll="{ y: historyTableHeight }" @change="changePage"
                         :pagination="{
                            showSizeChanger:true,
                            current: currentPage,
                            pageSize:pageSize,
                            total: total,
                            showQuickJumper:true,
                            bordered:false
                         }">
						  <template #bodyCell="{ column, text, record ,index}">
								<div class="operate_list" v-if="column?.Operations">
									<div class="operate_item" @click="turnToDetail(record)">{{ $t('HistoryPage.Detail') }}</div>
									<!-- <div class="operate_item" @click="renameCollection(record,index)">{{ $t('HistoryPage.Rename') }}</div> -->
									<div class="operate_item" @click="setExport(record,'')">{{ $t('HomeView.Export') }}</div>
									<div class="operate_item" @click="deleteGroup(record, index)">{{ $t('HistoryPage.Delete') }}</div>
								</div>
							</template>
                        </a-table>
                    </div>
                </div>
            </div>
        </div>
        <oldHistoryDetail ref="historyDetail" :groupDetails="groupDetails" :collectionName="collectionName"></oldHistoryDetail>

        <!-- <a-modal class="rename_modal_component" 
            v-model:visible="renameVisivle" 
            :footer="null" 
            :title="renameData?.name"
			:keyboard="false"
            width="56rem"
            :maskClosable="false"
            :centered="true"
        >
            <div class="collection_rename_content">
                <div class="rename_form_content">
                    <input class="rename_form_input" :placeholder="$t('HistoryPage.inputContent2')" v-model="newCollectionName" @keydown.enter="confrimRename()">
                </div>
                <div class="rename_submit_button"  @click="confrimRename()">{{ $t('HistoryPage.Submit') }}</div>
            </div>
        </a-modal> -->
		<!-- <RobotAssist></RobotAssist> -->
    </div>
	<OldExportNewCoolection id="oldExportNewCoolection" ref="OldExportNewCoolection" allBoardData="allBoardData"></OldExportNewCoolection>
</template>
<script lang="ts">
import { defineComponent,ref,createVNode,computed, nextTick} from 'vue'
import HeaderComponent from "@/component/HomePage/Header.vue";
import oldHistoryDetail from "@/component/Detail/oldHistoryDetail.vue";
import { Https } from "@/tool/https";
import { formatTime } from "@/tool/util"
import { Modal,message } from 'ant-design-vue';
import RobotAssist from "@/component/HomePage/RobotAssist.vue";
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { rgbToHsv, dataURLtoBlob } from "@/tool/util";
import JSZip, { forEach } from "jszip";
import html2canvas from "html2canvas";
import { useStore } from "vuex";
import { useI18n } from 'vue-i18n';
import { getCookie } from "@/tool/cookie";
import OldExportNewCoolection from "@/component/HomePage/OldExportNewCoolection.vue";

const FileSaver = require("file-saver");
export default defineComponent({
    components: {
        HeaderComponent,
        oldHistoryDetail,
		RobotAssist,
		OldExportNewCoolection
    },
    setup() {
        let rangePickerValue:any = ref([])
		const store = useStore();
        let renameData:any = ref({}) //修改名字选中的数据
        const columns:any = computed(()=>{
			return [
				{ title: useI18n().t('HistoryPage.CollectionsName'), align:'center', ellipsis: true, width: 150, dataIndex: 'name', key: 'collectionName' },
				{ title: useI18n().t('HistoryPage.UptateTime'), align:'center', ellipsis: true,width: 150, dataIndex: 'updateDate', key: 'updateTime',customRender:(record:any)=>{
					let time = formatTime(record.text / 1000, 'YYYY-MM-DD hh:mm:ss')
					return time
				}},
				{ title: useI18n().t('HistoryPage.SketchCounts'), align:'center', ellipsis: true, width: 150, dataIndex: 'sketchCount', key: 'sketchCounts' },
				{
					title: useI18n().t('HistoryPage.Operations'),
					key: 'operation',
					align:'center', 
					fixed: 'right',
					width: 150, 
					// slots:{customRender:'action'}
					Operations:true,
				},
			]
		});
        let collectionList:any = ref([])
		let {t} = useI18n()
		let userInfo:any = ref()
		let allBoardData:any = ref({})
        return {
            rangePickerValue,
            columns,
            collectionList,
            renameData,
			t,
			store,
			userInfo,
			allBoardData,
        }
    },
    data(){
        return{
            currentPage:1,
            pageSize:10,
            total:0,
            historyTableHeight:0,
            newCollectionName:'',
            renameVisivle:false,//修改名字弹窗
            groupDetails:{},//每个collection的详情
            collectionName:'',//选中的名字
			isShowMark: false, //导出的loading蒙层
            searchCollectionName:'',
        }
    },
    mounted(){
		let userInfo:any = getCookie("userInfo")
        this.userInfo = JSON.parse(userInfo);
        let historyTable:any = this.$refs.historyTable
        this.historyTableHeight = historyTable.clientHeight - 130
        this.getHistoryList()
    },
    methods:{
        turnToDetail(record:any){
            // this.groupDetails = record.groupDetails
            let historyDetail:any = this.$refs.historyDetail
            this.collectionName = record.name
            // historyDetail.init(this.data)
			this.setExport(record,'look')
            // historyDetail.changeDetailShow()
        },


        //改变页码
        changePage(e:any){
            this.currentPage = e.current
            this.pageSize = e.pageSize
            this.getHistoryList()
        },

        //查询列表
        searchHistoryList(){
             this.currentPage = 1
             this.getHistoryList()
        },

        getHistoryList(){
            let startDate:any = this.rangePickerValue ? new Date(this.rangePickerValue[0]).getTime(): ''
            let endDate:any = this.rangePickerValue ? new Date(this.rangePickerValue[1]).getTime(): ''
            let data = {
                page:this.currentPage,
                size:this.pageSize,
                collectionName:this.searchCollectionName,
                startDate:startDate,
                endDate:endDate,
				userId:this?.userInfo?.userId,
            }
            Https.axiosPost('https://old.api.aida.com.hk/api/history/queryUserGroup', data).then(
                (rv: any) => {
                    this.collectionList = rv.content
                    this.total = rv.total
                }
            );
        },

        //删除分组
        deleteGroup(record:any,index:number){
            let deleteGroupFun = (id:any,index:number) =>{
                let data = {
                    userGroupId:id
                }
                Https.axiosPost(Https.httpUrls.deleteUserGroup,data).then(
                    (rv: any) => {
                        message.success(this.t('HistoryPage.jsContent1'))
                        this.collectionList.splice(index,1)
                    }
                );
            }
            Modal.confirm({
                title: this.t('HistoryPage.jsContent2'),
                icon: createVNode(ExclamationCircleOutlined),
                okText: 'Yes',
                cancelText: 'No',
                centered:true,
				mask:false,
                onOk() {
                    deleteGroupFun(record.id,index)
                }
            });
        },
		dealViewChooseData(data:any){
            if(!data){
                return []
            }
            let filesList = data.map((v:any)=>{
                let newData:any = {
                    imgUrl:v.url.replace(/www\.aida\.com\.hk/, 'files.aida.com.hk'),
                    id:v.id,
                    status:'done',
                    resData:v,
                }
                if(v.level1Type === 'Sketchboard'){
                    newData.pin = v.isPin
                    newData.category = v.level2Type
                }
                if(v.level1Type === 'Printboard'){
                    newData.pin = v.isPin
                }
                return newData
            })
            return filesList
        },
		dealLikeDesign(data:any){
			let filesList = data.map((v:any)=>{
                let newData:any = {
                    designItemUrl:v.url.replace(/www\.aida\.com\.hk/, 'files.aida.com.hk'),
					imgUrl:v.url.replace(/www\.aida\.com\.hk/, 'files.aida.com.hk'),
                    id:v.designId,
                }
                return newData
            })
			return filesList
		},
		dealHistoryChooseData(data:any,str:any){
            let collectionData = {
                moodboardFiles:this.dealViewChooseData(data.collection.moodBoards),
                printboardFiles:this.dealViewChooseData(data.collection.printBoards),
                generatePrintFiles:[],
                colorBoards:this.dealViewChooseColor(data.collection.colorBoards),
                skecthboardFiles:this.dealViewChooseData(data.collection.sketchBoards),
                marketingSketchFiles:this.dealViewChooseData(data.collection.marketingSketchs),
                moodTemplateId:data.collection.moodTemplateId,
				likeDesignCollectionList:this.dealLikeDesign(data.userLikeDetails)
            }
			this.allBoardData = collectionData
			
			if(str == 'look'){
				let historyDetail:any = this.$refs.historyDetail
				historyDetail.init(collectionData)
				
			}else{
				let OldExportNewCoolection:any = this.$refs.OldExportNewCoolection
				OldExportNewCoolection.init(collectionData)
			}
        },
		dealViewChooseColor(data:any){
            let colorList = data.map((v:any)=>{
                let rgbValue = v.rgbValue.split(' ')
                let newData:any = {
                    id:v.id,
                    name:v.name,
                    tcx:v.tcx || '',
                    rgbValue:{r:rgbValue[0],g:rgbValue[1],b:rgbValue[2],a:1}
                }
                return newData
            })
            return colorList
        },
		setExport(recold:any,str:any){
			 let url = 'https://old.api.aida.com.hk/api/history/choose'  + `?userGroupId=${recold.id}`
            Https.axiosGet(url).then(
                (rv: any) => {
					this.dealHistoryChooseData(rv,str)
					if(str == 'look'){
					}else{
						nextTick().then(()=>{
							this.exportCanvas()
						})
					}
					
                }
            ).catch(rv=>{
            });
		},
		async exportCanvas(){
            let collectionReview:any = document.querySelector("#oldExportNewCoolection")
            let a = document.createElement('a');
            this.isShowMark = true
			let img:any = []
			await html2canvas(collectionReview, { useCORS: true, scale: 3 }).then(
				async (canvas) => {
					let blob: any = dataURLtoBlob(
						canvas.toDataURL("image/png")
					);
					let index = 0;
					img.push({
							imgUrl: URL.createObjectURL(blob),
							name: "collection.png",
						})
					let num = 0
					for (let key in this.allBoardData) {
						if (key !== "colorBoards" && key !== "moodTemplateId") {
								for (let item of this.allBoardData[key]) {
									if(this.allBoardData[key][0]==undefined){
										break
									}
									let nameTail = item?.imgUrl?.split(".").pop().split("?").shift();
									// console.log(item);
									let data = {
										imgUrl: item.imgUrl,
										name:
											(item?.resData?.name?item?.resData?.name:'') +
											index +
											"." +
											nameTail,
									};
									
									img.push(data);
									index++;
								}
							
							num++
						}
					}
					// a.setAttribute('href', URL.createObjectURL(blob));
					// a.setAttribute('download', `collection.png`);
					// a.click();
				}
			);
			this.downImg(img);
        },
		getImgArrayBuffer(url:any) {
            return new Promise((resolve, reject) => {
                //通过请求获取文件blob格式
                let xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", url, true);
                xmlhttp.responseType = "blob";
                xmlhttp.onload = function () {
                if (this.status == 200) {
                    resolve(this.response);
                } else {
                    reject(this.status);
                }
                };
                xmlhttp.send();
            });
        },
		downImg(imagesParams:any) {
            let _this:any = this;
            let zip = new JSZip();
            let cache:any = {};
            let promises = [];

            for (let item of imagesParams) {
                const promise = _this.getImgArrayBuffer(item.imgUrl).then((data:any) => {
                // 下载文件, 并存成ArrayBuffer对象(blob)
                zip.file(item.name, data, { binary: true }); // 逐个添加文件
                cache[item.title] = data;
                });
                promises.push(promise);
            }

            Promise.all(promises)
                .then(() => {
                zip.generateAsync({ type: "blob" }).then((content:any) => {
                    // 生成二进制流
                    FileSaver.saveAs(
                    content,
                    'DesignFiles'
                    ); // 利用file-saver保存文件  自定义文件名
                    this.isShowMark = false
                });
                })
                .catch((res) => {
                    _this.message.error("Failed to export the file");
                    this.isShowMark = false
                });
        },
    }
})
</script>
<style lang="less">
.history_page {
    width: 100%;
    height: 100%;
	padding: 0 9rem;
	overflow: hidden;
	// min-width: 1440px;
	position: relative;
    .page_content {
        position: relative;

        .page_content_bg {
            position: absolute;
            width: 100%;
            height: 100%;
        }

        .page_content_body {
            position: absolute;
            width: 100%;
            height: 100%;
            box-sizing: border-box;

            .history_page_body{
                width: 100%;
                height: calc(100% - 7rem);
                padding: 4rem 2.5rem 4rem;
				margin-top: 4rem;
                box-sizing: border-box;
				top: 50%;
				position: relative;
				transform: translateY(-50%);

                .history_header{
                    font-size: 1.8rem;
                    height: 6.3rem;
                    line-height: 6.3rem;
                    font-weight: 500;
                    color: #333333;
                }

                .history_table_search{
                    display: flex;
                    align-items: center;

                    .range_picker{
                        width: 36rem;
                        height: 4.8rem;

                        .ant-picker-input > input{
                            font-size: 1.6rem;
                        }

                        .range_picker_icon{
                            font-size: 2.2rem;
                        }
                    }

                    .content_search_block{
                        margin-left: 4rem;
                        display: flex;

                        .search_input{
                            width: 32.8rem;
                            padding-left: 1.5rem;
                            height: 4.8rem;
                            line-height: 4.6rem;
                            background: #FFFFFF;
                            border: 0.1rem solid #F1F1F1;
                            font-size: 1.6rem;
                            font-weight: 400;

                            &::placeholder {
                                color: #C2C2C2;
                            }
                        }

                        .search_icon_block{
                            width: 7.2rem;
                            height: 4.8rem;
                            line-height: 4.8rem;
                            text-align: center;
                            background: #343579;
                            cursor: pointer;

                            .icon-sousuo{
                                font-size: 2rem;
                                color: #FFFFFF;
                            }
                        }
                    }
                }

                .history_table_content{
                    margin-top: 2.6rem;
                    width: 100%;
                    height: calc(100% - 13.7rem);
                    background: rgba(255, 255, 255, 0.6);
                    padding-bottom: 3rem;

                    .ant-table{
                        background: transparent;
                    }
                    
                    .ant-table-body{
                        overflow-y: auto !important;
                        -ms-overflow-style: none;
                        overflow: -moz-scrollbars-none;

                        &::-webkit-scrollbar { width: 0 !important }

                    }

                    .ant-table-thead > tr > th{
                        background: #FFFFFF;
                    }

                    .ant-table-tbody > tr > td{
                        border: none;
                        background: transparent;

                        
                    }

                     .ant-table-tbody > tr{

                         &:hover > td{
                            background: #FFFFFF;
                        }
                     }

                     .ant-table-pagination-right{
                         padding-right: 3.5rem;
                     }

                    .operate_list{
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        padding: 0 1rem;

                        .operate_item{
                            font-size: 1.4rem;
                            font-family: Roboto;
                            font-weight: 400;
                            color: #343579;
                            cursor: pointer;
                        }
                    }
                }
            }
        }
    }

    
}

.rename_modal_component{

    .collection_rename_content{
        padding:2rem 9.2rem 3rem;


        .rename_form_content{

            .rename_form_input{
                width: 100%;
                height: 4.6rem;
                margin-top: 1rem;
                border: 0.1rem solid #B4BED7;
                padding-left: 2.1rem;
                line-height: 4.6rem;
                font-size: 1.8rem;
                box-sizing: border-box;

                &::placeholder {
                    color:#A5B0C2,
                }
            }
        }

        .rename_submit_button{
            height: 4.8rem;
            line-height: 4.8rem;
            background: #343579;
            font-size: 2.4rem;
            font-weight: 500;
            color: #FFFFFF;
            width: 16rem;
            text-align: center;
            cursor: pointer;
            margin: 4.5rem auto 0;
        }
    }
}
</style>