var system = require("../../../system");
const http = require("http");
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const moment = require('moment');
const appconfig = system.getSysConfig();
const sha235 = require("sha256");
class BizOptCtl extends CtlBase {
    constructor() {
        super("bizchance", CtlBase.getServiceName(BizOptCtl));
        this.schemeService = system.getObject("service.bizchance.schemeSve");
        this.schemeSve = system.getObject("service.bizchance.fitaxschemeSve"); //财税-方案信息
        this.fitaxcompanySve = system.getObject("service.bizchance.fitaxcompanySve"); //财税-企业信息
        this.operationrecordSve = system.getObject("service.bizchance.operationrecordSve"); //财税-需求分配记录
        this.deliverbillSve = system.getObject("service.bizchance.deliverybillSve"); //财税-需求分配
        this.logService = system.getObject("service.bizchance.statuslogSve");
        this.shisService = system.getObject("service.bizchance.salesmanhisSve");
        this.receiveUrl = settings.receiveUrl();
        this.queueUrl = settings.queueUrl();
        this.rysUrl = settings.rysUrl();
        //this.wdyUrl = settings.wdyUrl();
        this.dateUtil = system.getObject("util.dateClient");
    }

    /**
     * 根据用户id获取商机信息，分页获取
     * @param {*} pobj
     */
    async findAndCountAll(pobj, qobj, req) {
        try {
            //设置查询条件
            console.log("bizoptCtl/findAndCountAll pobj--", pobj);
            if (pobj.search && pobj.search.dateType) {
                if (pobj.search.dateType !== '全部') {
                    pobj.search.created_at = this.dateUtil.betweenTime(pobj.search.dateType);
                }
                delete pobj.search.dateType
            }
            const rs = await this.service.findAndCountAll(pobj);
            console.log("rs-------------" + JSON.stringify(rs));
            let rarr = [];
            let results = rs.results.rows;
            results.forEach(element => {
                let robj = {};
                robj.id = element.id; //数据的id
                robj.demand_code = element.demand_code; //商机编号
                robj.v_cophone = element.v_cophone; //联系电话-shousuo
                robj.business_status = element.business_status; //商机当前状态
                if (element.service_address && element.service_address != 'undefined') {
                    robj.address = element.service_address; //服务地区
                } else {
                    robj.address = "";
                }
                // robj.updated_at = this.timeFormat(element.updated_at);//商机当前状态日期
                robj.updated_at = element.updated_at; //商机当前状态日期
                robj.business_type = element.business_type; //商机类型
                robj.v_coname = element.v_coname; //联系人-shousuo
                robj.source_name = element.source_name; //渠道来源--前端服务
                robj.servicerName = element.facilitator_name; //服务商名称

                // robj.facilitator_name = element.facilitator_name;//服务商名称
                // robj.sourceName = element.source_name;//渠道来源
                // robj.business_info_person = element.business_info.contactsName;//联系人
                // robj.business_info_phone = system.decryptStr(element.business_info.contactsPhone);//联系电话

                robj.salesman_name = element.salesman_name;
                robj.salesman_phone = element.salesman_phone;

                rarr.push(robj);
            });
            rs.results.rows = rarr;
            console.log("rsresults-------------" + JSON.stringify(rs));
            return system.getResult(rs);
        } catch (error) {
            console.log("error------------------------" + error);
            return system.getResultError(error);
        }
    }

    /**
     * 需求分配
     * @param {*} mobj
     * @param {*} qobj
     * @param {*} req
     * {
        demand_code_list: ["1", "2", "3"],//至少一个需求编号
        salesman_name: "",//销售员姓名
        salesman_id: "",//销售员id
        salesman_opcode: "",//唯一标识
        salesman_phone: "",//销售员手机号
      }
    */
    async distribution(mobj, qobj, req) {
        console.log("bizoptCtl/distribution分配需求");
        let pobj = mobj.d;
        let obj = {
            numbers: pobj.demand_code_list,
            nickName: pobj.salesman_name,
            userId: pobj.salesman_id,
            opCode: pobj.salesman_opcode,
            phone: pobj.salesman_phone,
            type: "BIZ",
        }
        try {
            let res = await this.deliverbillSve.distributionPerson(obj);
            return system.getResult("分配需求成功:" + res);
        } catch (error) {
            console.log("bizoptCtl/distribution分配需求失败:", error);
            return system.getResultError(error);
        }
    }

    /**
     * 关闭需求
     * @param {*} mobj
     * {
        demand_code: "",//需求编号
        close_reason: "",//关闭原因
        remarks: ""//备注
      }
    */
    async closeBizopt(mobj, qobj, req) {
        console.log("bizoptCtl:closeBizopt:mobj-----------------",JSON.stringify(mobj));
        let pobj = mobj.d;
        console.log("bizoptCtl:closeBizopt:pobj-----------------",JSON.stringify(pobj));
        pobj.business_status = "isClosed";
        if (!pobj.demand_code || !pobj.close_reason) {
            return system.getResultError("缺少必要参数.");
        }
        //根据需求编号去更新该条需求的状态为已关闭
        try {
            let res = await this.service.updateStatusByDemandCode(pobj);
            console.log("bizoptCtl:closeBizopt:res-----------------",JSON.stringify(res));

            //添加到记录表
            pobj.operator = {
                id: mobj.userid ? mobj.userid : "",
                name: mobj.username ? mobj.username : ""
            }
            pobj.operation_type = "close";
            pobj.operation_details = {
                close_reason: pobj.close_reason,
                remarks: pobj.remarks
            }
            let recordRes = await this.operationrecordSve.insertInfo(pobj);
            console.log("bizoptCtl:operationrecordSve-----------------",JSON.stringify(recordRes));
            //异步将该需求关闭信息同步到其他系统(走队列，融易算接口文档2.3)
            //构造参数，添加判断(有方案信息的才走队列同步到融易算，没有的直接关闭)
            let schemeRes = await this.schemeSve.findInfo(pobj);
            if (schemeRes && schemeRes.solution_bizid) {
                let pushObj = this.buildObj(pobj, schemeRes);
                system.queueOper(pushObj);
            } else {
                console.log(pobj.demand_code + "该需求没有方案信息，不需要同步");
            }
            console.log("bizoptCtl:closeBizopt-----------------关闭需求成功");
            return system.getResult("关闭需求成功!");
        } catch (error) {
            console.log("bizoptCtl/closeBizopt 关闭需求出错------------------",error);
            return system.getResultError("bizoptCtl/closeBizopt 关闭需求出错!");
        }
    }

    async testCloseProposal(obj){
        console.log("testCloseProposal-------------------");
        return { 
            "requestId": "d51aa427-738f-4bed-b48d-282da0a74432", 
            "status":1,
            "success": true, 
            "errorCode": 0,
            "errorMsg": "ok",
            "data": { 
            } 
        } 

    }

    buildObj(pobj, schemeRes) {
        //let pushUrl = this.rysUrl + "leads/proposal/close";
        let pushUrl = this.rysUrl + "/web/bizchance/bizoptCtl/testCloseProposal";
        let solutionBizId;
        if (schemeRes.solution_bizid) {
            solutionBizId = schemeRes.solution_bizid.replace(/_book/g, "");
        }
        let pushObj = {
            pushUrl: pushUrl,
            actionType: "close",
            messageBody: {
                IntentionBizId: pobj.demand_code,
                BizType: "bookkeeping",
                Solution: {
                    SolutionBizId: solutionBizId,//方案编号
                    Note: pobj.close_reason //备注
                }
            },
            headData: {
                'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTg0MzQ2ODcsImlzcyI6InJFRVN6TU5ZUlM2RnBWNnZlY09vdExPNWdPcUNXSmFQIiwiaWF0IjoxNTk4NDMxMDg3fQ.isQ40HqHHfJ-rTsUQOhRIdu4XCitZU-AfzeqSH4kPbQ',
                'XAPPKEY': 'f6b59b74-f943-4735-bb86-e05d6b7fd78e',
                'Source': 'GSB'
            }
        }
        return pushObj;
    }

    /**
     * 获取跟进详情页所有信息
     * @param {*} mobj
     * {
        demand_code: "",//需求编号
      }
    */
    async getFollowUpInfo(mobj, qobj, req) {
        var pobj = mobj.d;
        if (pobj.demand_code && pobj.demand_code != 'undefined') {
            try {
                var bizoptInfo = await this.service.findInfoByDemandCode(pobj);
                var companyInfo = await this.fitaxcompanySve.findInfo(pobj);

                pobj.operation_type = "followUp";
                var followUpinfos = await this.operationrecordSve.findAllInfo(pobj);
                var followUpinfo = {};
                if (followUpinfos.length > 0) {
                    followUpinfo = followUpinfos[0];
                }
                return system.getResult({ bizoptInfo: bizoptInfo, companyInfo: companyInfo, followUpinfo: followUpinfo });
            } catch (error) {
                console.log("bizopt/getFollowUpInfo err: " + error);
                return system.getResultError("bizoptCtl/closeBizopt 获取跟进详情页信息出错!");
            }
        }
    }

    /**
      * 获取记录详情页所有信息
      * @param {*} mobj
      * {
         demand_code: "",//需求编号
       }
     */
    async getRecordInfo(mobj, qobj, req) {
        var pobj = mobj.d;
        if (pobj.demand_code && pobj.demand_code != 'undefined') {
            try {
                var bizoptInfo = await this.service.findInfoByDemandCode(pobj); //需求信息
                var companyInfo = await this.fitaxcompanySve.findInfo(pobj); //企业信息
                var schemeInfo = await this.schemeSve.findInfo(pobj); //方案详情
                var followUpinfos = await this.operationrecordSve.findAllInfo(pobj); //线索记录

                var rtn = { bizoptInfo: bizoptInfo, companyInfo: companyInfo, schemeInfo: schemeInfo, followUpinfos: followUpinfos };
                console.log("获取记录详情页所有信息-------------------",JSON.stringify(rtn));

                return system.getResult(rtn);
            } catch (error) {
                console.log("bizopt/getFollowUpInfo err: " + error);
                return system.getResultError("bizoptCtl/closeBizopt 获取跟进详情页信息出错!");
            }
        }
    }

    /**
     * @param {*} mobj
     */
    async findInfoByDemandCode(mobj, qobj, req) {
        var pobj = mobj.d;
        if (pobj.demand_code && pobj.demand_code != 'undefined') {
            try {
                var rs = await this.service.findInfoByDemandCode(pobj);
                var ms = await this.schemeService.findInfoByDemandCode(pobj);
                var rarr = {}
                if (rs) {
                    var statusInfo = { "currentStatus": rs.business_status }; //商机状态
                    var businessInfo = {};
                    businessInfo.demand_code = rs.demand_code; //商机编号
                    businessInfo.channelSource = appconfig.pdict.source[rs.source_name]; ///渠道来源
                    // businessInfo.businessType = rs.business_type;//商机类型代码
                    businessInfo.businessType = appconfig.pdict.businessType[rs.business_type]; //商机类型名称
                    // businessInfo.serviceArea = rs.service_address;//服务地区
                    if (businessInfo.businessName == "云上园区注册") {
                        businessInfo.serviceArea = appconfig.pdict.registeredParkDict[rs.service_address]; //服务地区名称
                    } else {
                        businessInfo.serviceArea = appconfig.pdict.registeredAreaDict[rs.service_address]; //服务地区名称
                    }
                    if (businessInfo.businessName == "注册地址") {
                        businessInfo.registeredAddress = appconfig.pdict.registeredAreaDict[rs.service_address]; //注册地址名称
                    }
                    businessInfo.statusReason = rs.close_reason; //商机关闭原因
                    businessInfo.memoInfo = rs.business_info.memoInfo; //备注信息
                    businessInfo.contactsName = rs.business_info.contactsName; //联系人名称
                    businessInfo.contactsPhone = system.decryptStr(rs.business_info.contactsPhone); //联系人联系方式
                    businessInfo.createdTime = this.timeFormat(rs.created_at); //商机创建时间
                    rarr.statusInfo = statusInfo;
                    rarr.businessInfo = businessInfo;
                }
                if (ms) {
                    var planInfo = ms.scheme_info;
                    planInfo.schemeNumber = ms.scheme_number;
                    planInfo.currentStatus = ms.scheme_status;
                    if (ms.scheme_status && ms.scheme_status == "isReject") {
                        planInfo.currentStatus = "已退回";
                    } else {
                        planInfo.currentStatus = ms.scheme_status;
                    }
                    planInfo.statusReason = ms.reject_reason;
                    rarr.planInfo = planInfo;
                }
                return system.getResult(rarr);
            } catch (error) {
                console.log("eeeeeeeeeeeeeeeeeeeeee");
                console.log(error);
                return system.getResultError(error);
            }
        } else {
            return system.getResultError("参数错误！");
        }
    }

    /*更新业务员信息*/
    async updateSalesmanInfoByDemandCode(mobj, qobj, req) {
        var pobj = mobj.d;
        if (pobj.businessMode && pobj.businessMode != 'undefined') {
            try {
                var res = await this.service.findInfoByDemandCode(pobj);
                if (res) {
                    var sInfo = {
                        "flowType": "BIZ",
                        "flowId": res.id,
                        "flowCode": pobj.businessMode,
                        "salesmanInfo": {
                            "oldOpcode": res.salesman_opcode,
                            "oldClerkName": res.salesman_name,
                            "oldClerkId": res.salesman_id,
                            "oldClerkPhone": res.salesman_phone,
                            "oldFacilitatorId": res.facilitator_id,
                            "oldFacilitatorName": res.facilitator_name,
                            "newOpcode": pobj.salesmanOpcode,
                            "newClerkName": pobj.salesmanName,
                            "newClerkId": pobj.salesmanId,
                            "newClerkPhone": pobj.salesmanPhone,
                            "newFacilitatorId": pobj.facilitatorId,
                            "newFacilitatorName": pobj.facilitatorName
                        }
                    }
                    await this.shisService.insertInfo(sInfo); //之前业务员转历史
                    await this.service.updateSalesmanInfoByDemandCode(pobj); //更新业务员信息
                    return system.getResult("操作成功！");
                } else {
                    return system.getResultError("未找到相关数据");
                }

            } catch (error) {
                return system.getResultError(error);
            }
        } else {
            return system.getResultError("参数错误!");
        }
    }
    /*根据商机编号更新商机状态*/
    async updateStatusByDemandCode(mobj, qobj, req) {
        var pobj = mobj.d;
        if (pobj.businessMode && pobj.businessMode != 'undefined' && pobj.currentStatus && pobj.currentStatus != 'undefined') {
            try {
                await this.service.updateStatusByDemandCode(pobj);
                await this.schemeService.updateStatusByDemandCode(pobj); //同时更新方案的状态
                var res = await this.service.findInfoByDemandCode(pobj);
                if (res && res != 'undefined') {
                    var logInfo = {
                        "flowType": "BIZ",
                        "flowId": res.id,
                        "statusCode": pobj.currentStatus,
                        "statusReason": res.close_reason,
                        "clerkName": res.salesman_name,
                        "clerkId": res.salesman_id
                    }
                    await this.logService.insertInfo(logInfo); //插入状态日志表
                }

                if (pobj.currentStatus == "isClosed") { //关闭需求时调用
                    var rc = system.getObject("util.execClient");
                    var requrl = this.queueUrl;
                    var params = {
                        "actionType": "produceData",
                        "actionBody": {
                            "pushUrl": this.receiveUrl,
                            "actionType": "closeNeed",
                            "identifyCode": "ic-manage",
                            "messageBody": {
                                "needNum": pobj.businessMode,
                                "note": pobj.statusReason
                            }
                        }
                    }
                    var rtn = await rc.execPost(params, requrl);
                    var j = JSON.parse(rtn.stdout);
                    if (j.status == 1) {
                        return system.getResult("操作成功！");
                    } else {
                        return system.getResultError("更新方案状态出错！");
                    }
                } else {
                    return system.getResult("操作成功！");
                }
            } catch (error) {
                return system.getResultError(error);
            }
        } else {
            return system.getResultError("参数错误!");
        }
    }

    /*插入数据信息 */
    async insertInfo(nobj, qobj, req) {
        console.log("融易算需求插入参数-------------------------------------------",JSON.stringify(nobj));
        var pobj = nobj.actionBody;
        if (pobj.intentionBizId && pobj.intentionBizId != 'undefined') {
            try {
                var cachestr = sha235(JSON.stringify(nobj));
                var cacheInfo = await this.cacheManager["TxCache"].getCache(cachestr);
                if (cacheInfo && cacheInfo != 'undefined') {
                    return {
                        "status": 1,
                        //1代表成功，否则失败
                        "msg": "已处理成功!",
                        "data": cachestr,
                        "requestId": nobj.requestId
                    }
                } else {
                    pobj.intentionBizId = pobj.intentionBizId + "_book";
                    pobj.businessStatus = 'received';
                    pobj.sourceNumber = 'tx';
                    pobj.facilitatorId = '10';
                    pobj.facilitatorName = '公司宝';
                    pobj.sourceName = 'tencentCloud';

                    //插入操作
                    var buInfo = await this.service.insertInfo(pobj);
                    console.log("融易算需求插入结果-----------------------------------------",JSON.stringify(buInfo));
                    if (buInfo) {
                        await this.cacheManager["TxCache"].cache(cachestr, JSON.stringify({ cachestr: cachestr }), 180);
                        //日志
                        var logInfo = {
                            "flowType": "BIZ",
                            "flowId": buInfo.id,
                            "statusCode": pobj.businessStatus,
                            "clerkName": pobj.salesmanName,
                            "clerkId": pobj.salesmanId
                        }
                        await this.logService.insertInfo(logInfo); //插入状态日至表
                        return {
                            "status": 1, //1代表成功，否则失败
                            "message": "操作成功",
                            "data": buInfo,
                            "requestId": nobj.requestId
                        };

                    }
                }
            } catch (error) {
                //异常处理
                console.log("融易算需求插入异常-------------------------",error);
                return system.getResultError(error);
            }
        } else {
            //字段错误处理
            console.log("-----------------------------融易算需求插入参数错误!");
            return system.getResultError("参数错误!");
        }
    }

    /*根据需求编号更新需求状态*/
    async updatepayStatusByDemandCode(mobj, qobj, req) {
        console.log("融易算更新需求状态参数-----------------------",JSON.stringify(mobj));
        var pobj = mobj.actionBody;
        if (pobj.solutionBizId && pobj.solutionBizId != 'undefined') {
            try {
                pobj.demand_code = pobj.solutionBizId + "_book";
                if (pobj.operateType == 'PAID') {
                    pobj.business_status = 'isFinished';
                }
                var res = await this.service.findInfoByDemandCode(pobj);
                console.log("融易算更新需求返回结果-----------------------",JSON.stringify(res));
                if (res) {
                    Object.assign(res.business_info, { "payStatus": "已支付" })
                    await res.update({ business_info: res.business_info })
                    await this.service.updateStatusByDemandCode(pobj);
                    return system.getResult("操作成功！");
                } else {
                    return system.getResultError("更新需求状态出错");
                }
            } catch (error) {
                console.log("融易算更新需求返回error-----------------------",error);
                return system.getResultError(error);
            }
        } else {
            console.log("融易算更新需求参数错误");
            return system.getResultError("参数错误!");
        }
    }



    timeFormat(date) {
        let localTime = moment.utc(date).toDate();
        localTime = moment(localTime).format("YYYY-MM-DD");
        return localTime;
    }
    //根据bizId查询商机表中的所有信息
    async getInfo(pobj, qobj, req) {
        try {
            if (!pobj.bizId) {
                throw new Error("bizId 不能为空");
            }
            const rs = await this.service.getInfo(pobj);
            //console.log("got message");
            return system.getResult(rs);
        } catch (err) {
            return system.getResult(null, err.message)
        }
    }
}
module.exports = BizOptCtl;

// var task = new BizOptCtl();
// var obj={
//   "d": {
//       "businessMode": "20200728103902194833",
//       "servicerName": "公司宝",
//       "serviceCode": "110100",
//       "serviceName": "北京",
//       "contactsName": "张三",
//       "contactsPhone": "15801599965",
//       "businessType": "/ic/gsreg/",
//       "businessName": "公司注册",
//       "channelSource": "tencentCloud",
//       "channelNumber": "tx",
//       "memoInfo": "测试一下下",
//       "companyName": "腾讯科技有限公司",
//       "UserName": "张三",
//       "salesmanOpcode": "root/ic/j2",
//       "salesmanId": "15",
//       "clerkName": "j2",
//       "clerkPhone": "13800138000",
//       "servicerCode": "10"
//   }
// }
// task.findInfoByDemandCode(obj,{},{}).then(d=>{
//   console.log(JSON.stringify(d));
// })