/*
    *服务 接口
    *和后端交互的接口
    *
    *
*/

import { Common } from '@/utils/http';
import { SERVICE_CODE, STATE_CODE } from '@/config/interface';
import {
    BASE_CONFIG
} from '@/config/config'
import axios from 'axios'
import {MessageBox,Toast} from 'mint-ui';

let CommonAlert = function(msg){
    return Toast({
        message: msg,
        duration: 15000
    })
}

let InterfaceService = {

    //--------------上传公共服务 start--------------

    //一次性获取签名 用于:多文件file 一次性上传 遍历文件的时间很短 一般在签名有效期以内 所以不需要判断签名时效
    getOssSignatureDisposable: (params, callback, errorCallback, loadingStartCb, loadingEndCb) => {
        Common.request(SERVICE_CODE.OSS_SIGNATURE, params, (data) => {
            let respData = data.respData
            typeof callback === 'function' && callback(respData);
        }, (data) => {
            if(data.respData && data.respData.respMsg){
                CommonAlert(data.respData.respMsg);
            }
            typeof errorCallback === 'function' && errorCallback(data);
        }, loadingStartCb, loadingEndCb);

    },
    getOssSignature: (params, callback, errorCallback, loadingStartCb, loadingEndCb) => {
        let signature = sessionStorage.getItem('signature') || '{}';
        signature = JSON.parse(signature)
        let now = new Date().getTime();
        if(signature && signature['expire'] > now){  //签名未过期 直接上传
            typeof callback === 'function' && callback(signature);
        }else{ //签名过期 直接上传
            sessionStorage.removeItem('signature');
            Common.request(SERVICE_CODE.OSS_SIGNATURE, params, (data) => {
                let respData = data.respData
                sessionStorage.setItem('signature',JSON.stringify(respData));

                typeof callback === 'function' && callback(respData);
            }, (data) => {
                typeof errorCallback === 'function' && errorCallback(data);
            }, loadingStartCb, loadingEndCb);
        }
    },
    /*
    *   signature  后端获取的签名
    *   file       上传文件对象
        dirName    文件名 string
            product/[productId]/main/     (商品图：商品/商品id/主图/)
            product/[productId]/detail/   (商品图：商品/商品id/主图/)
            company/                    (公司/)
        pos        多文件上传 pos对应文件的索引 单文件上传输入0即可
        callBack   oss上传成功回调
    *
    */
    uploadToOss: (signature, file, dirName, pos, callBack, reName, timestampFlag)=>{

      let fileName = new Date().getTime()+file.name; //文件是否重命名
        //let fileName = new Date().getTime()+file.name; //文件是否重命名
        let key = signature.dir + dirName;
        if (timestampFlag) { //是否加时间戳区别文件名
            key = key + new Date().getTime() + '/';
        }
        key += fileName

        let param = new FormData(); //创建form对象
        let now = Date.parse(new Date()) / 1000;
        param.append('key', key)
        param.append('policy', signature.policy)
        param.append('OSSAccessKeyId', signature.accessid)
        param.append('success_action_status', '200')
        param.append('signature', signature.signature)
        //param.append('file',file,file.name)
        param.append('file', new Blob([file], {type: "jpg"}), fileName)
        let config = {
            headers:{'Content-type': 'multipart/form-data'},
            // withCredentials:true
        };


        (function(pos){
            axios.post(signature.host,param,config)
            .then(response=>{
                //console.log(pos)
                //console.log(file)
                if(response.status===200){
                    typeof callBack === 'function' && callBack(pos,file,dirName,signature,fileName);
                }else{
                    Message.error("oss签名获取错误");
                }
            })
        })(pos)
    },
    //--------------oss静态文件获取 start--------------
    //类目
    getCategoryList:(callback)=>{
        axios.get(BASE_CONFIG.OSS_CATEGORY)
            .then(response=>{
                if(response.status===200){
                    typeof callback === 'function' && callback(response.data);
                }
            })
    },
    //爆款商品列表
    getGoodsList:(callback)=>{
        axios.get(BASE_CONFIG.OSS_HOT_PRODUCT + '?v=' + Math.random())
        .then(response=>{
            if(response.status===200){
            typeof callback === 'function' && callback(response.data);
            }
        })
    },
    getAreaList:(callback)=>{
        axios.get(BASE_CONFIG.OSS_AREA_LIST + '?v=' + Math.random())
        .then(response=>{
            if(response.status===200){
            typeof callback === 'function' && callback(response.data);
            }
        })
    },
    getCategroyList:(callback)=>{
        axios.get(BASE_CONFIG.OSS_CATEGORY_LIST + '?v=' + Math.random())
        .then(response=>{
            if(response.status===200){
            typeof callback === 'function' && callback(response.data);
            }
        })
    },
    getCategroyImgMap:(callback)=>{
        axios.get(BASE_CONFIG.OSS_CATEGORY_IMG_MAP + '?v=' + Math.random())
        .then(response=>{
            if(response.status===200){
            typeof callback === 'function' && callback(response.data);
            }
        })
    },
    //--------------oss静态文件获取 start--------------

}
const interMap = [
    { method: 'testInter', code: SERVICE_CODE.TEST_CODE },//--------------auth satrt--------------
    { method: 'testInsert', code: SERVICE_CODE.TEST_INDSERT },
    //--------------auth satrt--------------
    //--------------auth end--------------
    { method: 'miniProgramInnit', code: "500004" },   //微信小程序初始化
    { method: 'bindWxPhone', code: "500000" },  //用户注册(授权)
    { method: 'wxLogin', code: "500001" }, //用户登录（小程序）
    { method: 'sumbitGoods', code: "500002" }, // 抢购
    { method: 'getOrderList', code: "500003" }, // 订单详情
    { method: 'getRemainingGoodsList', code: "500006" },
    { method: 'getProductDetails', code: "500008" }, // 商品详情
    { method: 'addAddress', code: "500009" },//新增收货地址
    { method: 'oaLogin', code: "500010" },//绑定OA页面
    { method: 'getAddressList', code: "500011" },//收货地址一览
    { method: 'getCarGoodsList', code: "500012" },//购物车一览
    { method: 'operateCarThings', code: "500013" },//加入购物车
    { method: 'initOrder', code: "500014" },//订单初始化
    { method: 'orderList', code: "500017" },//订单列表
    { method: 'orderDetail', code: "500018" },//订单详情
    { method: 'logisticsDetail', code: "500019" },//物流信息
    { method: 'doCancellOrder', code: "500020" },//取消订单接口
    { method: 'rePayOrder', code: "500021" },//重新发起订单接口
    { method: 'getCouponList', code: "500022" },//优惠券列表
    { method: 'upDateOrderStatus', code: "500023" },//刷新订单状态
    { method: 'getHomeProductList', code: "500024" },//首页自由商品列表
    { method: 'getHomeCouponList', code: "500025" },//首页查询可领优惠券列表
    { method: 'doGetCoupons', code: "500026" },//首页领取优惠券
    { method: 'getCateProductList', code: "500027" },//类目对应商品list
    { method: 'doGetCateNameList', code: "500028" },//类目树
    { method: 'doSaveShareFlow', code: "500029" },//C端新增分享流水

    
    // { method: 'oaLogin', code: "040076" },
    // { method: 'getWXConfig', code: "500007" },
    // { method: 'submitBill', code: "1060003" },//账单提交

    //     500000 注册
    // 500010Oa账号绑定
    // 500001登录接口

]

let interAPI = {};

interMap.forEach( m => {
    interAPI[m.method] = (params, callback, errorCallback, loadingStartCb, loadingEndCb) => {
        Common.request(m.code, params, (data) => {
            typeof callback === 'function' && callback(data);
        }, (data) => {
            if(m.showMsg && data.respData && data.respData.respMsg){
                CommonAlert(data.respData.respMsg);
            }else if(m.showError && data.respData && data.respData.respCode === '9999' && data.respData.respMsg){
                CommonAlert(data.respData.respMsg);
            }
            typeof errorCallback === 'function' && errorCallback(data);
        }, loadingStartCb, loadingEndCb);
    }
});
Object.assign(InterfaceService,interAPI);




export { InterfaceService};
