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();
class BizOptCtl extends CtlBase {
  constructor() {
    super("bizchance", CtlBase.getServiceName(BizOptCtl));
    this.schemeService = system.getObject("service.bizchance.schemeSve");
    this.logService = system.getObject("service.bizchance.statuslogSve");
    this.shisService = system.getObject("service.bizchance.salesmanhisSve");
    this.receiveUrl = settings.receiveUrl();
    this.queueUrl = settings.queueUrl();
    //this.wdyUrl = settings.wdyUrl();
    this.dateUtil = system.getObject("util.dateClient");
  }

  /*根据用户id获取商机信息，分页获取*/
  async findAndCountAll(pobj, qobj, req) {
    try {
      //TODO 根据业务员id获取该业务员所有列表
      //设置查询条件
      console.log("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);
      let rarr = [];
      let results = rs.results.rows;
      results.forEach(element => {
        let robj = {};
        robj.id = element.id;//数据的id
        robj.demand_code = element.demand_code;//商机编号
        robj.source = element.source_name;//商机来源
       // robj.source_name = element.source_name;//商机来源-jiansuo
        robj.business_type = element.business_type;//商机类型
        robj.business_info_person = element.business_info.contactsName;//联系人
        robj.v_coname = element.v_coname;//联系人-shousuo
        robj.business_info_phone = system.decryptStr(element.business_info.contactsPhone);//联系电话
        robj.v_cophone = system.decryptStr(element.v_cophone);//联系电话-shousuo
        robj.business_status = element.business_status;//商机当前状态
        if (element.business_info.serviceName && element.business_info.serviceName != 'undefined'){
          robj.serviceName = element.business_info.serviceName;//服务地区
        }
       else{
        robj.serviceName = "";
       }
        robj.updated_at = this.timeFormat(element.updated_at);//商机当前状态日期

        robj.servicerName = element.facilitator_name;
        robj.facilitator_name = element.facilitator_name;
        robj.sourceName = element.source_name;//渠道来源
        robj.source_name = element.source_name;//渠道来源--前端服务

        robj.salesman_name=element.salesman_name;
        robj.salesman_phone=system.decryptStr(element.salesman_phone);

        rarr.push(robj);
      });
      rs.results.rows = rarr;
      return system.getResult(rs);
    } catch (error) {
      return system.getResultError(error);
    }
  }

  /*根据商机编号获取商机详情*/
  async findInfoByDemandCode(mobj, qobj, req) {
    var pobj = mobj.d;
    if (pobj.businessMode && pobj.businessMode != '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.businessMode = 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) {
    var pobj = nobj.d;
    if (pobj.businessMode && pobj.businessMode != 'undefined' && pobj.businessType && pobj.businessType != 'undefined') {
      try {
        //pobj.currentStatus = "beforeSubmission";//加上当前状态为待提交方案
        // pobj.channelSource = "tencentCloud";//目前渠道只有腾讯
        // pobj.sourceNumber = "1111111";
        pobj.businessType = appconfig.pdict.dyDict[pobj.businessType];
        var buInfo = await this.service.insertInfo(pobj);
        var logInfo = {
          "flowType": "BIZ",
          "flowId": buInfo.id,
          "statusCode": pobj.currentStatus,
          "clerkName": pobj.clerkName,
          "clerkId": pobj.salesmanId
        }
        await this.logService.insertInfo(logInfo);//插入状态日至表
        return {
          "status": 1,   //1代表成功，否则失败
          "message": "操作成功",
          "data": "",
          "requestId": ""
        };
      }
      catch (error) {
        console.log("TTTTTTTTTTTTTTTTTTTTTTT");
        console.log(error);
        return system.getResultError(error);
      }
    }
    else {
      return system.getResultError("参数错误!");
    }
  }

  timeFormat(date) {
    let localTime = moment.utc(date).toDate();
    localTime = moment(localTime).format("YYYY-MM-DD");
    return localTime;
  }
}
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));
// })
