const system = require("../../system");
const ServiceBase = require("../sve.base");
const settings = require("../../../config/settings");
var moment = require('moment');
const claimAddHours = 72;//认领添加的时间（单位小时）=3天
const protectAddHours = 168;//保护添加的时间（单位小时）=7天
class BusinessCompanyService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(BusinessCompanyService));
    this.orderflowDao = system.getObject("db.orderflowDao");
    this.businessinfoDao = system.getObject("db.businessinfoDao");
    this.businessinfoSve = system.getObject("service.businessinfoSve");
    this.companyDao = system.getObject("db.companyDao");
    this.userDao = system.getObject("db.userDao");
    this.companyDao = system.getObject("db.companyDao");
    this.utilstmSve = system.getObject("service.utilstmSve");
    this.buscompanynotesSve = system.getObject("service.buscompanynotesSve");
  }
  async recycleBusiness() {//回收商机
    // 商机状态business_status!=wrl未认领,手机无效次数mobile_invalid_num<2,业务无效次数bus_invalid_num<2 or 收回截止时间recovery_time<new date()
    var sqlWhere = {
      where: {
        business_status: { [this.dao.db.Op.ne]: "wrl" },
        mobile_invalid_num: { [this.dao.db.Op.lt]: 2 },
        bus_invalid_num: { [this.dao.db.Op.lt]: 2 },
        recovery_time: { [this.dao.db.Op.lt]: new Date() }
      },
      attributes: ["id", "code", "total_amount", "invalid_num"],
      raw: true
    };
    var list = await this.dao.model.findAll(sqlWhere);
    if (!list || list.length == 0) {
      return "目前没有要回收的商机信息"
    }
    var self = this;
    var putIds = [];
    var busFlowList = [];
    var putBusFlowList = [];
    var setBusField = { createuser_id: null, createcompany_id: null, recovery_time: null, business_status: "wrl", check_mobile: 1 };
    for (let index = 0; index < list.length; index++) {
      const element = list[index];
      if (element) {
        if (Number(element.total_amount) > Number(element.invalid_num)) {
          putIds.push(element.id);
          if (element.code) {
            busFlowList.push({
              sourceOrderNo: element.code,
              notes: "系统已回收，将进行重新认领",
            });
            putBusFlowList.push(element.code);
          }
        }
        if (putIds.length > 5) {
          await this.db.transaction(async function (t) {
            await self.dao.putItemByCustomFieldName(setBusField, putIds, t);
            putIds = [];
            if (busFlowList.length > 0 && putBusFlowList.length > 0) {
              await self.orderflowDao.putItemBySourceOrderNo({ createuser_id: null, createcompany_id: null }, putBusFlowList, t);
              await self.orderflowDao.bulkCreate(busFlowList, t);
              putBusFlowList = [];
              busFlowList = [];
            }
          });

        }
      }
    }
    if (putIds.length > 0) {
      this.db.transaction(async function (t) {
        await self.dao.putItemByCustomFieldName(setBusField, putIds, t);
        if (busFlowList.length > 0 && putBusFlowList.length > 0) {
          await self.orderflowDao.putItemBySourceOrderNo({ createuser_id: null, createcompany_id: null }, putBusFlowList, t);
          await self.orderflowDao.bulkCreate(busFlowList, t);
        }
      });
    }
  }

  async freeClaimOperation(user, bus_type, ids) {//免费认领商机操作
    // if (Number(user.freeBusNum) <= 0) {
    //   return { code: -201, msg: "认领失败，您目前认领次数为0" }
    // }
    // if (Number(user.freeBusNum) < ids.length) {
    //   return { code: -201, msg: "认领失败，认领次数必须小于商机数量，您目前认领次数为" + user.freeBusNum + "，您将要认领的商机数量为" + ids.length }
    // }
    var self = this;
    var sqlWhere = {
      where: {
        business_status: "wrl",
        tm_company_type: bus_type,
        id: { [this.dao.db.Op.in]: ids },
      },
      attributes: ["id", "applicant_cn", "code"],
      raw: true
    };
    var list = await this.dao.model.findAll(sqlWhere);
    if (!list || list.length == 0) {
      return { code: -201, msg: "目前没有符合您要认领的商机" };
    }

    await this.db.transaction(async function (t) {
      for (let index = 0; index < list.length; index++) {
        const element = list[index];
        if (element && element.applicant_cn) {
          var tmpId = element.id;
          var rlCode = await self.getBusUid("rl");
          var setField = {
            createuser_id: user.id,
            createcompany_id: user.company_id,
          };
          //修改商机
          var claim_time = moment();
          var recovery_time = moment().add(claimAddHours, "hours");
          var setBusField = {
            createuser_id: user.id,
            createcompany_id: user.company_id,
            claim_time: claim_time,
            recovery_time: recovery_time,
            business_status: "yrl"
          };
          if (!element.code) {
            setBusField.code = rlCode;
            setField.sourceCode = rlCode;
          }
          await self.businessinfoDao.updateByWhere(setField, { where: { applicant_cn: element.applicant_cn, tm_company_type: bus_type } }, t);
          await self.updateByWhere(setBusField, { where: { id: tmpId } }, t);
          await self.orderflowDao.create({
            company_id: user.company_id,
            createuser_id: user.id,
            sourceOrderNo: rlCode,
            opContent: "成功认领商机",
            notes: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + ":用户id=" + user.id + "，用户公司id=" + user.company_id + "，成功认领商机"
          }, t);
        }
      }
    });
    return { code: 1, msg: "认领成功" }
  }
  async protectBus(user, bus_type, code_list) {//保护商机操作
    var self = this;
    var sqlWhere = {
      where: {
        business_status: "yrl",
        tm_company_type: bus_type,
        code: { [this.dao.db.Op.in]: code_list },
      },
      attributes: ["id", "claim_time", "code"],
      raw: true
    };
    var list = await this.dao.model.findAll(sqlWhere);
    if (!list || list.length == 0) {
      return { code: -201, msg: "目前没有符合你要保护的商机信息" };
    }
    await this.db.transaction(async function (t) {
      for (let index = 0; index < list.length; index++) {
        const element = list[index];
        if (element && element.claim_time) {
          var tmpId = element.id;
          var recovery_time = moment(element.claim_time).add(protectAddHours, "hours");
          //修改商机
          var setBusField = {
            updateuser_id: user.id,
            recovery_time: recovery_time,
            business_status: "bhz"
          };
          await self.updateByWhere(setBusField, { where: { id: tmpId } }, t);
          await self.orderflowDao.create({
            company_id: user.company_id,
            createuser_id: user.id,
            sourceOrderNo: element.code,
            opContent: "成功保护商机",
            notes: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + ":用户id=" + user.id + "，用户公司id=" + user.company_id + "，成功保护商机"
          }, t);
        }
      }
    });
    return { code: 1, msg: "保护成功" }
  }
  //获取订单详情
  async getBusinessDetail(obj) {
    var user = obj.user;
    var sourceCode = obj.sourceCode;
    var applicant_cn = obj.applicant_cn;
    var tm_company_type = obj.tm_company_type;
    if (!sourceCode && (!applicant_cn || !tm_company_type)) {
      return { code: -1, msg: "参数错误" };
    }
    var bc = null;
    var biList = null;
    var bnList = null;
    if (sourceCode) {
      bc = await this.dao.model.findOne({ where: { code: sourceCode }, raw: true });
      biList = await this.businessinfoSve.dao.model.findAll({ where: { sourceCode: sourceCode }, raw: true });

    } else {
      bc = await this.dao.model.findOne({ where: { applicant_cn: applicant_cn }, raw: true });
      biList = await this.businessinfoSve.dao.model.findAll({ where: { applicant_cn: applicant_cn, tm_company_type: tm_company_type }, raw: true });
    }
    if (biList && biList.length > 0) {
      console.log("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
      for (var i = 0; i < biList.length; i++) {
        var qobj = { reg_num: biList[i].tm_regist_num, nclone_code: biList[i].ncl_one_codes };
        var r = await this.utilstmSve.getTmNclSmallCodes(qobj, "businesscompanySve");
        console.log(r);
        if (r.status == 0 && r.data && r.data.length > 0) {
          var nclthree = "";
          for (var j = 0; j < r.data.length; j++) {
            if (r.data[j].ncl_last) {
              nclthree = nclthree + r.data[j].ncl_last + ";"
            }
          }
          biList[i]["nclthree"] = nclthree;

        }
      }
      console.log("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
    }
    if (bc) {
      var fromcompany = await this.companyDao.model.findOne({ where: { id: bc.company_id }, raw: true });
      var createcompany = await this.companyDao.model.findOne({ where: { id: bc.createcompany_id }, raw: true });
      var createuser = await this.userDao.model.findOne({ where: { id: bc.createuser_id }, raw: true });
      bc["fromcompany"] = fromcompany;
      bc["createcompany"] = createcompany;
      bc["createuser"] = createuser;
      if(bc && bc.mobile_list){
        console.log(bc.mobile_list);
        var reg = new RegExp("'","g");//g,表示全部替换。
        bc.mobile_list=bc.mobile_list.replace(reg,"\"");
      }
      if(bc && bc.company_mail){
        var reg = new RegExp("'","g");//g,表示全部替换。
        bc.company_mail=bc.company_mail.replace(reg,"\"");
      }
      var bnObj={tm_company_type:bc.tm_company_type,createuser_id:user.id,company_id:user.company_id,businesscompany_id:bc.id};
      bnList= await this.buscompanynotesSve.dao.model.findAll({where:bnObj,raw:true,'order': [['created_at', 'DESC']]});
    }
    var data = { bc: bc, biList: biList,bnList:bnList };
    return { code: 1, data: data };

  }

  /*
    参数信息：
    user：用好
    code：商机公司code
    opType：操作类型（1无效电话，2商机无效）
  */
  async updateBusinessStatus(user, code, opType) {//业务认为商机：无效电话或商机无效
    var self = this;
    var companySqlWhere = { code: code };
    var busCompanyItem = await self.dao.findOne(companySqlWhere);
    if (!busCompanyItem) {
      return { code: -201, msg: "没有该条商机信息" }
    }
    if (!busCompanyItem.createuser_id || busCompanyItem.createuser_id != user.id) {
      return { code: -202, msg: "目前该商机不属于当前登录人" }
    }
    var setParams = {
      business_status: "wx",
      updateuser_id: user.id,
    }
    if (opType == 1) {
      setParams.mobile_invalid_num = Number(busCompanyItem.mobile_invalid_num || 0) + 1;
      setParams.check_mobile = 0;
    }//电话无效
    if (opType == 2) {
      setParams.bus_invalid_num = Number(busCompanyItem.bus_invalid_num || 0) + 1;
    }//商机无效
    await self.updateByWhere(setParams, { where: { id: busCompanyItem.id } });
    return { code: 1, msg: "操作成功" };
  }
  async updateCustomerIntention(obj) {
    var pobj = { code: obj.code, customer_intention: obj.customer_intention };
    var result = this.dao.model.update(pobj, { where: { code: pobj.code } });
    return { code: 1 };
  }
  //提交客戶意向
  async submitCustomerIntention(obj) {
    var user = obj.user;
    var bc = await this.dao.model.findOne({where:{code:obj.code,createcompany_id:user.company_id,createuser_id:user.id},raw:true});
    if(!bc){
      return {code:-1,msg:"商机信息不存在"};
    }
    var that=this;
    await this.db.transaction(async function (t) {
      var noteObj={
        tm_company_type:bc.tm_company_type,customer_intention:obj.customer_intention,notes:obj.notes,
        businesscompany_id:bc.id,createuser_id:user.id,company_id:user.company_id
      };
      var bn = await that.buscompanynotesSve.dao.model.create(noteObj,t);
      var pobj = {id:bc.id,customer_intention: obj.customer_intention };
      var result = await that.dao.update(pobj,t);
      
    })
    return { code: 1 };
  }
  //获取该业务员累计商机数量 商标数量 下单数量
  async getBusinessStatisticForSalesman(companyid, user_id,statisticType) {
    var result = null;
    if(statisticType==2){//统计当前月份
      result = await this.db.query(
        'SELECT count(*) as num, sum(total_amount) as total_amount,sum(order_num) as order_num from `bi_businesscompany` where DATE_FORMAT( claim_time, \'%Y%m\' ) = DATE_FORMAT( CURDATE( ) , \'%Y%m\' ) and createcompany_id=:status and createuser_id=:userId ',
        { replacements: { status: companyid, userId: user_id }, type: this.db.QueryTypes.SELECT });
     }else{
      result = await this.db.query(
        'SELECT count(*) as num, sum(total_amount) as total_amount,sum(order_num) as order_num from `bi_businesscompany` where createcompany_id=:status and createuser_id=:userId ',
        { replacements: { status: companyid, userId: user_id }, type: this.db.QueryTypes.SELECT });
     }
    
    console.log("----------fetchBusinessForSalesman------------");
    console.log(result);
    if(result){
      if(result.length>0){
        var data = result[0];
        return {code:1,data:data};
      }else{
        return {code:1,data:{ num: '0', total_amount: '0', order_num: '0' }};
      }
    }
    return {code:-1,msg:"操作失败"};
  }

   //获取该公司所有员工累计商机数量 商标数量 下单数量
   async getBusinessStatisticForBoss(companyid,statisticType) {
     var result=null;
     if(statisticType==2){//统计当前月份
      result = await this.db.query(
        'SELECT count(*) as num, sum(total_amount) as total_amount,sum(order_num) as order_num from `bi_businesscompany` where DATE_FORMAT( claim_time, \'%Y%m\' ) = DATE_FORMAT( CURDATE( ) , \'%Y%m\' ) and createcompany_id=:status',
        { replacements: { status: companyid}, type: this.db.QueryTypes.SELECT });
     }else{
      result = await this.db.query(
        'SELECT count(*) as num, sum(total_amount) as total_amount,sum(order_num) as order_num from `bi_businesscompany` where createcompany_id=:status',
        { replacements: { status: companyid}, type: this.db.QueryTypes.SELECT });
     }
    console.log("----------fetchBusinessForSalesman------------");
    console.log(result);
    if(result){
      if(result.length>0){
        var data = result[0];
        return {code:1,data:data};
      }else{
        return {code:1,data:{ num: '0', total_amount: '0', order_num: '0' }};
      }
    }
    return {code:-1,msg:"操作失败"};

  }

}
module.exports = BusinessCompanyService;
