
import { bookingV2Urls,tbIssueUrl } from "../config";
import axios from 'axios'
import {default_tbEnsureIssueJsonV2,default_tbIssueJsonDataV2}  from "../types";
let tbEnsureIssueJsonV2 = default_tbEnsureIssueJsonV2
let tbIssueJsonDataV2:any;
let goodsData:any;
async function booking(info: any) {
    let userData:any = await getStorageItem("tb_user")
    let reqMsg = {
        msg:'',
        status:-200,
        task_id:info.task_id,
        action:'task_result'
    };
    if(!userData){
        reqMsg.msg = "请刷新连接";
        return reqMsg
    }
    let goodsId,result;
    let userDataJson:any = JSON.parse(userData)
    goodsId = await tbGetIssueGoodsIdV2(userDataJson, goodsData,info.goods);
    let goods = info.goods.replaceAll('775011740120',goodsId)
    let default_info = JSON.parse(goods)
    tbIssueJsonDataV2 = default_info
    result = await tbDataJoinAndIssueV2(userDataJson, goodsData, goodsId);
    // let {data:result} = await axios.post('https://item.upload.taobao.com/sell/v2/submit.htm', data, {
    //       headers: {
    //         'Content-Type': 'application/x-www-form-urlencoded',
    //         'Accept':'application/json',
    //         'x-xsrf-token': userDataJson.token
    //       }
    //     })
        let rJson = result
            try {
             if (rJson.hasOwnProperty("ret")) {
                 if (JSON.stringify(rJson.ret).indexOf("被挤爆啦") != -1) {
                     let verifyUrl = rJson.data.url;
                     await openVerifyTab(verifyUrl);
                     await delayDate(1000 * 60);
                     reqMsg.msg = "请完成插件打开的页面提示验证码授权!";
                     reqMsg.status = -200;
                 }
             } else {
                 let rmg = rJson.models.globalMessage;
                 let rSuccessUrl = rmg.successUrl;
                 let rType = rmg.type;
                 reqMsg.status = rType == "status"?10:-200
                 if (rType != "status") {
                     let msg = JSON.stringify(rJson.models);
                     reqMsg.msg = msg;
                 } 
                //  else {
                //      let numIid = getUrlParam(rSuccessUrl, "primaryId");
                //      reqMsg.goods_id = numIid;
                //  }
             }
              return reqMsg
            } catch (e) {
                reqMsg.msg = "发布错误,请重试或者联系客服咨询!";
                reqMsg.status = -200;
                return reqMsg
            }
}
function getStorageItem(key:string) {
    return new Promise((resolve, reject) => {
        chrome.storage.sync.get([key], (item) => {
            resolve(item[key]);
        })
    })

}
function getUrlParam(url:string, paramName:string){
    if (url.indexOf("?") != -1) {
        let params = url.split("?")[1].split("&");
        for (let i in params) {
            if (params[i].indexOf(paramName) != -1) {
                return params[i].replace(paramName + '=', '');
            }
        }
    }
    return '';
}

function delayDate(time: number) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        //console.log(‘开始执行‘)
        resolve('status')
      }, time)
    })
  }
async function openVerifyTab(url:string) {
    chrome.tabs.create({ url: url, active: true }, async (tab) => {
        alert("请手动完成系统自动打开的页面验证码操作!")
    })

}
/**
 *  设置商品的基础信息 
 * @param {商品发布的数据信息} goodsData 
 * @param {商品ID} goodsId 
 */

function setTbBaseDataV2(goodsData:any, goodsId: number) {
    let goodsDataV2 = goodsData.data;
    let goodsModel = goodsDataV2.goodsModel;
    let userId = goodsDataV2.userId;
    tbIssueJsonDataV2.id = goodsId; //设置商品ID
    tbIssueJsonDataV2.userId = goodsDataV2.userId; //设置用户ID
    tbIssueJsonDataV2.tbExtractWay.template = goodsModel.postageId + ""; //设置运费模板ID
    tbIssueJsonDataV2.title = goodsModel.title; //设置标题
    tbIssueJsonDataV2.price = goodsModel.price; //设置价格

    tbIssueJsonDataV2.catProp = JSON.parse(goodsDataV2.specificParamToXytPlusParam); //设置类目属性
    let shelfProcessing = goodsDataV2.shelfProcessing;
    if (shelfProcessing == null || shelfProcessing == 1) shelfProcessing = 2;
    tbIssueJsonDataV2.startTime.type = shelfProcessing; //设置上架还是下架

    let shopCat = goodsModel.classifyId; //设置店铺分类信息
    if (shopCat != null && shopCat != undefined && shopCat != -1) {
        tbIssueJsonDataV2.shopcat = [shopCat];
    } else {
        tbIssueJsonDataV2.shopcat = [];
    }
    tbIssueJsonDataV2.outerId = goodsModel.outerId; //商品编码
    tbIssueJsonDataV2.descRepublicOfSell.descPageRenderParam.userId = userId;
    tbIssueJsonDataV2.descRepublicOfSell.descPageRenderParam.itemId = goodsId;
    tbIssueJsonDataV2.descRepublicOfSell.descPageRenderModel.wholeConfigBO.userId = userId;
    tbIssueJsonDataV2.descRepublicOfSell.descPageRenderModel.extendConfig.wangpuEditorConfig.params.itemId = goodsId;

    //设置退换货承诺
    let sellPromise = goodsModel.expandParam.tbSJKTHHCN;
    if (sellPromise) {
        tbIssueJsonDataV2.sellPromise = [{ text: "退换货承诺", value: 1 }];
    }
}


/**
 * 设置商品的图片信息
 * @param {商品发布的数据信息} goodsData 
 * @param {商品ID} goodsId 
 */
// function setTbImageV2(goodsData:any, goodsId: number) {
//     let goodsModel = goodsData.data.goodsModel;
//     let masterPics = goodsModel.masterPics;
//     let descPics = goodsModel.descPics;
//     let mp = [];
//     let dp = [];
//     masterPics.forEach(elem => {
//         mp.push({ url: elem });
//     });

//     // tbIssueJsonDataV2.mainImagesGroup['mainImagesGroup-imageGroup'].images = mp;
//     tbIssueJsonDataV2.images = mp;


//     let descData = [];


//     for (let i = 0; i < descPics.length; i++) {
//         let elem = descPics[i];
//         let componentId = "component" + randomLenNum(13);
//         let groupId = "group" + randomLenNum(13);
//         let descParam = {
//             "reuseImg": false,
//             "groupId": groupId,
//             "imageUrls": [
//                 elem
//             ],
//             "originImg": true,
//             "imageIds": [
//                 -1
//             ],
//             "width": 620,
//             "size": 310241,
//             "splitHeight": 960,
//             "height": 961,
//         }



//         let copyDesc = $.extend(true, {}, tbDetailsPicJsonDataV2)
//         copyDesc.componentId = componentId;
//         copyDesc.groupId = groupId;
//         let copyTbDetailsSonJsonDataV2 = $.extend(true, {}, TbDetailsSonJsonDataV2)
//         copyTbDetailsSonJsonDataV2.boxStyle['background-image'] = elem;
//         copyTbDetailsSonJsonDataV2.componentId = componentId;
//         copyTbDetailsSonJsonDataV2.groupId = goodsId;
//         copyDesc.components = [copyTbDetailsSonJsonDataV2];
//         descData.push(copyDesc);
//         descParam.imageUrls = [elem];
//         dp.push(descParam);
//     }

//     tbDetailsJsonDataV2.groups = descData;


//     let dpJson = {
//         params: dp,
//     }

//     tbIssueJsonDataV2.descRepublicOfSell.descPageCommitParam.itemId = goodsId;
//     tbIssueJsonDataV2.descRepublicOfSell.descPageCommitParam.userId = goodsData.data.userId;
//     tbIssueJsonDataV2.descRepublicOfSell.descPageCommitParam.detailParam = JSON.stringify(dpJson)
//     tbIssueJsonDataV2.descRepublicOfSell.descPageCommitParam.templateContent = JSON.stringify(tbDetailsJsonDataV2)
//     let whiteImage = goodsModel.whitePic;
//     //如果存在白底图就设置白底图的数据信息
//     if (whiteImage !== null && whiteImage !== undefined && whiteImage != "") {
//         tbIssueJsonDataV2.guideImageGroup.imageGroup.whiteBgImage = [{ url: whiteImage, pix: '800x800' }]
//     } else {
//         tbIssueJsonDataV2.guideImageGroup.imageGroup.whiteBgImage = [];
//     }


//     //3:4的方式上传主图
//     if (goodsModel.masterLongPics != null && goodsModel.masterLongPics.length > 0) {
//         tbIssueJsonDataV2.imageVideoType.text = "3:4";
//         tbIssueJsonDataV2.imageVideoType.value = 1;
//         let longMp = [];
//         goodsModel.masterLongPics.forEach(elem => longMp.push({ url: elem }));
//         tbIssueJsonDataV2.threeToFourImages = longMp;
//     } else {
//         delete tbIssueJsonDataV2['threeToFourImages'];
//         tbIssueJsonDataV2.imageVideoType = {};
//     }


//     tbIssueJsonDataV2.sceneVideos.imageVideo.videoInfo = {};
//     let videoId = goodsModel.videoInfo;
//     //处理主图视频
//     if (videoId != null && videoId != 0) {
//         tbIssueJsonDataV2.sceneVideos.imageVideo.videoInfo.videoId = videoId;
//         tbIssueJsonDataV2.sceneVideos.imageVideo.videoInfo.sceneCode = "imageVideo";

//         let channelList = [];
//         channelList.push({ code: "Detail", name: "详情" });
//         channelList.push({ code: "MiniDetail", name: "微详情" });

//         tbIssueJsonDataV2.sceneVideos.imageVideo.channelList = channelList;


//     }

// }


/**
 * 设置商品的SKU信息
 * @param {商品发布的数据信息} goodsData 
 * @param {商品ID} goodsId 
 */
// function setTbGoodsSkuV2(goodsData:any, goodsId: number) {
//     let skuInfoModels = goodsData.data.goodsModel.skuInfoModels;
//     let skuPropData = goodsData.data.skuPropData;
//     let sku = [];
//     skuInfoModels.forEach(item => {
//         let skuJson = {
//             cspuId: null,
//             skuPrice: item.price,
//             disabled: null,
//             skuId: null,
//             skuOuterId: item.outerId,
//             skuStock: item.stockNum,
//             action: { "selected": true },
//             errorInfo: {},
//         };
//         let skuV = item.items;
//         let props = [];
//         let salePropKey = "";
//         skuV.forEach(sItem => {
//             let suProp = skuPropData[sItem.value];
//             let pid = suProp.pid.replace("p-", "");
//             let prop = {
//                 name: suProp.pid,
//                 label: sItem.alias,
//                 text: sItem.value,
//                 value: suProp.vid,
//             }

//             if (goodsData.data.product.product.productType == '双规格区分SKU图') {
//                 skuJson.skuPicture = [{ url: item.image }];
//             }

//             if (salePropKey != "") salePropKey = salePropKey + "_"
//             salePropKey = salePropKey + pid + "-" + suProp.vid;
//             props.push(prop);
//         })
//         skuJson.props = props;
//         skuJson.salePropKey = salePropKey;
//         sku.push(skuJson);
//     })
//     tbIssueJsonDataV2.sku = sku;
// }


// function setTbSalePropV2(goodsData:any, goodsId: number) {
//     let skuInfoModels = goodsData.data.goodsModel.skuInfoModels;
//     let skuPropData = goodsData.data.skuPropData;
//     let saleProp = {};
//     skuInfoModels.forEach(item => {
//         let values = item.items;
//         values.forEach(vItem => {
//             let suProp = skuPropData[vItem.value];
//             let pId = suProp.pid;
//             let pVals = [];
//             if (saleProp.hasOwnProperty(pId)) pVals = saleProp[pId];
//             let pVal = {
//                 text: vItem.value,
//                 value: suProp.vid,
//             };

//             if ("p-1627207" == pId) {
//                 pVal.img = item.image;
//             }


//             let f = true;

//             for (let k of pVals) {
//                 if (k.value == pVal.value) {
//                     f = false;
//                     break;
//                 }
//             }

//             if (f) {
//                 pVals.push(pVal);
//             }
//             saleProp[pId] = pVals;
//         })
//     })
//     tbIssueJsonDataV2.saleProp = saleProp;
// }

async function tbDataJoinAndIssueV2(userData:any, goodsData:any, goodsId:number) {
    // setTbBaseDataV2(goodsData, goodsId);
    // setTbImageV2(goodsData, goodsId);
    // setTbSalePropV2(goodsData, goodsId);
    // setTbGoodsSkuV2(goodsData, goodsId);
    console.log('tbDataJoinAndIssueV2',tbIssueJsonDataV2,goodsId);
    let data = {
        jsonBody: JSON.stringify(tbIssueJsonDataV2),
        catId: 150704,//tbIssueJsonDataV2.catId,
        itemId: goodsId,
        copyItemMode: 0
    }
    let  {data:result} = await axios.post('https://item.upload.taobao.com/sell/v2/submit.htm', data, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept':'application/json',
            'x-xsrf-token': userData.token
          }
        })
    return result;

}
/**
 * 获取需要发布的商品ID 
 * 关联主图信息然后提交得到一个发布页的链接
 * 访问发布页链接的数据获取商品ID信息
 * 
 * @param {用户登录的信息} userData 
 * @param {发布的商品信息} goodsData 
 * @returns 
 */
async function tbGetIssueGoodsIdV2(userData:any, goodsData:any,data:any) {
    // let goodsModel = goodsData.data.goodsModel;
    // let picPath = goodsModel.masterPics[0];
    // let userId = goodsData.data.userId;
    let default_info = JSON.parse(data)
    tbEnsureIssueJsonV2.userId = default_info.userId;
    tbEnsureIssueJsonV2.catImages = [{
        "url": 'https://img.alicdn.com/imgextra/i3/88897371/O1CN01wCaCGh24JyKxMRdkR_!!88897371.jpg_100x100'
    }];
    let result:any = await axios.post("https://item.upload.taobao.com/sell/merge/submit.htm",{ jsonBody: JSON.stringify(tbEnsureIssueJsonV2) }, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept':'application/json',
          'x-xsrf-token': userData.token
        }
      })
    let issueGoodsIdRd = result.data
    console.log('issueGoodsIdRd',issueGoodsIdRd);
    let link = "https:" + issueGoodsIdRd.link;
    let {data:goodsHtml}:any = await axios.get(link);
    console.log("goodsHtml",goodsHtml);
    let index = goodsHtml.indexOf('data":{"itemId":');
    let startIndex = index + 16;
    let goodsId = goodsHtml.substring(startIndex, startIndex + 12);
    return goodsId;
}
export default {
    booking
}