import Toast from './toast';
import BizDataCrypt from './BizDataCrypt';
import { httpconfig as httpConfig } from '../config/httpConfig.js';
import Cache from './cache.js';
var app = getApp();
const formatTime = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};
const formatNumber = (n) => {
    n = n.toString();
    return n[1] ? n : '0' + n;
};

//判断是否是为空
const isEmpty = (str) => {
    let type = typeof str;
    switch (type) {
        case 'object':
            //如果是对象用stringify转成str 排除 {} 和 null
            if (str instanceof Array) {
                return str.length > 0 ? false : true;
            } else {
                let template = JSON.stringify(str);
                return template === 'null' || template === '{}' ? true : false;
            }
        default:
            //其他
            str = str + '';
            if (str.length === 0 || str == 'undefined' || str == 'null') {
                return true;
            }
    }
    return false;
};

// 表单必填验证
const formRequire = (data, callback) => {
    let requireArr = [];
    console.log(data);
    if (!data || data.length < 1) {
        return;
    }
    data.map((item, i) => {
        if (isEmpty(item.value)) {
            requireArr.push(item);
        }
    });
    callback(requireArr);
};
/**
 * 防抖函数
 */
const debounce = (fn, interval) => {
    var timer;
    var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
    return function () {
        clearTimeout(timer);
        var that = this;
        var args = arguments; //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
        timer = setTimeout(function () {
            fn.call(that, ...args);
        }, gapTime);
    };
};
const getAppInfo = function (callback) {
    let appInfo = Cache.get('appInfo');
    if (appInfo) {
        callback(appInfo);
    } else {
        var appID = httpConfig.doctorAppID || '';
        // #ifndef H5
        appID = '';
        if (typeof uni.getAccountInfoSync === 'function') {
            try {
                var accountInfo = uni.getAccountInfoSync();
                appID = accountInfo.miniProgram.appId || '';
            } catch (e) {
                appID = '';
            }
        }
        if (!/^wx/.test(appID)) {
            appID = httpConfig.doctorAppID || '';
        }
        // #endif
        if (!appID) {
            callback({});
            return;
        }
        // 登录接口
        let data = {
            params: [
                {
                    appID: appID,
                    flag: 'D'
                }
            ]
        };
        let _this = this;
        $http.post('urlDeault', this, {
            code: '03100143',
            data: data,
            success: function (res) {
                if (res.errorCode == '0') {
                    Cache.set('appInfo', res.result);
                    callback(res.result);
                }
            }
        });
    }
};
const getOpenID = (code, callback) => {
    getAppInfo((appInfo) => {
        if (!code || !appInfo.docAppID || !appInfo.docSecret) {
            return;
        }
        let url = httpConfig.openIDAddress + '?appid=' + appInfo.docAppID + '&secret=' + appInfo.docSecret + '&js_code=' + code + '&grant_type=authorization_code';
        app.globalData.appID = appInfo.docAppID;
        uni.request({
            url: url,
            success: function (res) {
                if ((res.statusCode = '200')) {
                    callback(res.data.openid);
                    app.globalData.sessionKey = res.data.session_key;
                } else {
                    uni.showToast({
                        title: '获取OpenID异常',
                        icon: 'none'
                    });
                }
            }
        });
    });
};
const getPhoneNumber = (encryptedData, iv) => {
    var pc = new BizDataCrypt(app.globalData.appID, app.globalData.sessionKey);
    var data = pc.decryptData(encryptedData, iv);
    console.log(data);
};
/**计算开始日期与结束日期之间的所有日期 */
const getDateOfSpace = (startDate, endDate) => {
    let array = [`${startDate.substr(0, 4)}-${startDate.substr(4, 2)}-${startDate.substr(6, 2)}`];
    let start;
    let end;
    if (new Date(parseInt(startDate.substr(0, 4)), parseInt(startDate.substr(4, 2)) - 1, parseInt(startDate.substr(6, 2)))) {
        start = new Date(parseInt(startDate.substr(0, 4)), parseInt(startDate.substr(4, 2)) - 1, parseInt(startDate.substr(6, 2)));
    } else {
        throw new Error('startDate params Error');
    }
    if (new Date(parseInt(endDate.substr(0, 4)), parseInt(endDate.substr(4, 2)) - 1, parseInt(endDate.substr(6, 2)))) {
        end = new Date(parseInt(endDate.substr(0, 4)), parseInt(endDate.substr(4, 2)) - 1, parseInt(endDate.substr(6, 2)));
    } else {
        throw new Error('endDate params Error');
    }
    let endSecond = Date.parse(end);
    for (let i = 0; ; i++) {
        let getDate = getTargetDate(start, 0);
        start = new Date(getDate);
        let getDateTemp = Date.parse(new Date(parseInt(getDate.substr(0, 4)), parseInt(getDate.substr(5, 2)) - 1, parseInt(getDate.substr(8, 2))));
        if (getDateTemp <= endSecond) {
            array.push(getDate);
        } else {
            break;
        }
    }
    return array;
};

// startDate: 开始时间；dayLength：每隔几天，0-代表获取每天，1-代表日期间隔一天
const getTargetDate = (date, dayLength) => {
    dayLength = dayLength + 1;
    // var tempDate = new Date(date);
    let tempDate = date;
    tempDate.setDate(tempDate.getDate() + dayLength);
    var year = tempDate.getFullYear();
    var month = tempDate.getMonth() + 1 < 10 ? '0' + (tempDate.getMonth() + 1) : tempDate.getMonth() + 1;
    var day = tempDate.getDate() < 10 ? '0' + tempDate.getDate() : tempDate.getDate();
    return year + '-' + month + '-' + day;
};
export default {
    formatTime,
    formRequire,
    debounce,
    getOpenID,
    getDateOfSpace,
    getPhoneNumber
};
