const axios = require("axios");
const settings = require("../../config/settings");
const system = require("../system");
const annualreportDao = system.getObject("db.delivery.annualreportDao");
const uuidv4 = require('uuid/v4');

const BUSINESSTYPE = {
    ICP: "/qcfw/icp/",
    EDI: "/qcfw/edi/"
}
const TXSTATUS = {
    COLLECTING: "70",//手机材料中
    SUBMITING: "80",//递交材料中
    DISPOSEING: "90",//工信部处理中
    POSTING: "150",//证书已邮寄
    SUCCESS: "170",//服务已完成
    CLOSED: "190",//已关闭
    WAITDECLARE: "25",//待申报
    DECLARESUCCESS: "26",//申报成功
}
// 推送到 控制台
const porApi = axios.create({
    baseURL: settings.txurl(), // api 的 base_url
    timeout: 2000, // request timeout
    headers: {
        'Content-Type': 'application/json'
    }
})

// 推送公共服务
const publicApi = axios.create({
    baseURL: settings.requrl(), // api 的 base_url
    timeout: 2000, // request timeout
    headers: {
        'Content-Type': 'application/json'
    }
})

function getUUID() {
    var uuid = uuidv4();
    var u = uuid.replace(/\-/g, "");
    return u;
}

/**
 * 推送 方案
 * @param {*} bizData 
 * @param {*} schemeData 
 */
const pushScheme = async (bizData, schemeData) => {
    let data = {
        actionType: "submitSolution",
        actionBody: {
            needNum: bizData.demand_code,
            solutionContent: {
                scheme_info: schemeData.scheme_info,
                remark_info: schemeData.remark_info,
                businessType: BUSINESSTYPE[bizData.business_type],
                servicerName: bizData.facilitator_name,
                servicerCode: bizData.facilitator_id,
                clerkName: bizData.salesman_name,
                clerkPhone: bizData.salesman_phone
            }
        }
    }
    // 新增 还是修改
    if (schemeData.scheme_number) {
        data.actionBody.solutionNum = schemeData.scheme_number;
    }
    let result = await postRequest('api/receive/entService/springBoard', data);
    return result.data;
}

/**
 * 推送 关闭商机
 * @param {*} bizData 
 * @param {*} note 
 */
const pushCloseNeed = async (bizData, note) => {
    let data = {
        "actionType": "closeNeed",
        "actionBody": {
            "needNum": bizData.demand_code,
            "note": note
        }
    }
    let result = await postRequest('api/receive/entService/springBoard', data);
    return result.data;
}

/**
 * 推送 订单状态改变
 * @param {*} status 
 * @param {*} orderNum 
 * @param {*} data 
 */
const pushChangeOrder = async (status, orderNum, data = {}) => {
    let req = {
        "actionType": "updateOrderStatus",
        "actionBody": {
            "orderNum": orderNum,
            "status": status,
            "deliverContent": data
        }
    }
    let result = await postRequest('api/receive/entService/springBoard', req);
    return result.data;
}

/**
 * 提交材料
 * @param {*} deliverData 
 * @param {*} materials 
 */
const submitMaterials = async (deliverData, materials) => {
    let status;
    if (deliverData.delivery_status === system.SERVERSESTATUS.COLLECTING || deliverData.delivery_status === system.SERVERSESTATUS.SUBMITING) {
        status = TXSTATUS.SUBMITING;
    }
    if (deliverData.delivery_status === system.SERVERSESTATUS.DISPOSEING) {
        status = TXSTATUS.DISPOSEING;
    }
    materials.proposerInfo.businessInformation.ifListed = materials.proposerInfo.businessInformation.ifListed === "true"
    await pushChangeOrder(status, deliverData.delivery_code, {
        servicerName: deliverData.facilitator_name,
        servicerCode: deliverData.facilitator_id,
        clerkId: deliverData.salesman_id,
        clerkName: deliverData.salesman_name,
        clerkPhone: deliverData.salesman_phone,
        ...materials
    });
}

const pushDeclareReport = async (annualReport, deliverData) => {
    const annualReports = await annualreportDao.findAll({
        deliver_id: deliverData.id
    });
    let status = TXSTATUS.DECLARESUCCESS;
    if (annualReports && annualReports.filter(item => {
        return item.status === system.ANNUALREPORT.WAITDECLARE
    }).length <= 0) {
        status = TXSTATUS.SUCCESS;
    }
    const result = annualReports && annualReports.map((item) => {
        if (item.id === annualReport.id) {
            item.updated_at = new Date();
            item.file = annualReport.file;
            item.status = system.ANNUALREPORT.DECLARESUCCESS;
        }
        // item.status = item.status === system.ANNUALREPORT.WAITDECLARE ? "待申报" : "已申报"
        return item
    })

    await pushChangeOrder(status, deliverData.delivery_code, { annualReport: result })
}

/**
 * 退费
 * @param {*} orderNum 
 */
const returnPremium = async (orderNum) => {
    try {
        let data = {
            "actionType": "produceData",
            "actionBody": {
                "pushUrl": settings.txurl() + "/api/action/order/springBoard",
                "actionType": "refundOrder",
                "identifyCode": "icp-manage",
                "messageBody": {
                    "orderNum": orderNum//订单编码
                }
            }
        }
        console.log("请求数据 ------- ");
        console.log(data);

        let result = await publicApi.post('api/queueAction/producer/springBoard', data);
        result = result.data;
        console.log("返回数据 ------- ");
        console.log(result);
        if (result.status === 1) {
            return result
        } else {
            throw new Error(result.message)
        }
    } catch (err) {
        console.log("------ err -----");
        console.log(err)
        throw (err)
    }
}

const trademark = async (body) => {
    try {
        let data = {
            "actionType": "produceData",
            "actionBody": {
                "pushUrl":  settings.tmtransactionurl() + "/tmtransaction/action/trademarktransaction/springBoard",
                "actionType": "tmBatchUpload",
                "identifyCode": "trademark",
                "notifyUrl": settings.serviceurl() + "/web/trademark/trademarkCtl/notify",
                "messageBody": body,
                // "headData":{
                //     "XAPPKEY":"42d814c1-4daa-4643-88b2-f5dd3ec853f3"
                // }
            },
            requestId:getUUID()
        }
        console.log("请求数据 ------- ");
        console.log(data);

        let result = await publicApi.post('/api/queueAction/producer/springBoard', data);
        result = result.data;
        console.log("返回数据 ------- ");
        console.log(result);
        if (result.status === 1) {
            return result
        } else {
            throw new Error(result.message)
        }
    } catch (err) {
        console.log("------ err -----");
        console.log(err)
        throw (err)
    }
}

/**
 * 发送请求
 * @param {*} url 
 * @param {*} data 
 */
const postRequest = async (url, data) => {
    try {
        console.log("请求数据 ------- ");
        console.log(data);
        console.log(JSON.stringify(data.actionBody.deliverContent));
        let result = await porApi.post(url, data);
        result = result.data;
        console.log("返回数据 ------- ");
        console.log(result);
        if (result.status === 1) {
            return result
        } else {
            throw new Error(result.message)
        }
    } catch (err) {
        console.log("------ err -----");
        console.log(err)
        throw (err)
    }
}




module.exports = {
    pushScheme,
    pushCloseNeed,
    submitMaterials,
    pushChangeOrder,
    pushDeclareReport,
    TXSTATUS,
    returnPremium,
    trademark
}