const system = require('../../../system');
const ServiceBase = require('../../sve.base');
const settings = require('../../../../config/settings');
const appconfig = system.getSysConfig();
class BizOptService extends ServiceBase {
  constructor() {
    super('bizchance', ServiceBase.getDaoName(BizOptService));
  }
  async statBizChanceCountBySp(bizStatus, betweenTime) {
    const params = {};
    params.group = {
      byFields: ['facilitator_name'],
      actionType: 'count',
      aggField: 'id',
      aliasField: ' as  chanceCount',
      tblName: 'bussiness_opportunity',
      where: bizStatus != '' ? `where business_status='${bizStatus}'` : '',
      having: '',
    };
    if (betweenTime.length > 0) {
      params.group.where = `${params.group.where} ${params.group.where ? 'AND' : 'WHERE'} (created_at BETWEEN '${betweenTime[0]}' AND '${betweenTime[1]}')`;
    }
    const s = await this.dao.statGroupBy(params, null);
    return s;
  }
  /**
     * 公司id,平台公司ID为1
     * @param {*} companyId
     * @param {*} opath
     * @param {*} username
     * @param {*} userid
     */
  async statBizChance(companyId, opath, username, userid, betweenTime) {
    // 时间 筛选
    const andWhere = [];
    if (betweenTime.length > 0) {
      andWhere.push({
        created_at: { [this.db.Op.between]: betweenTime },
      });
    }
    // 如果当前登录人是平台,返回所有商机
    let waittoHandledCount = 0;
    let handlingCount = 0;
    let finishedCount = 0;
    let closedCount = 0;
    if (companyId == 1) {
      waittoHandledCount = await this.dao.findCount({ where: { business_status: 'beforeSubmission', [this.db.Op.and]: andWhere } });
      handlingCount = await this.dao.findCount({ where: { business_status: 'beforeConfirmation', [this.db.Op.and]: andWhere } });
      finishedCount = await this.dao.findCount({ where: { business_status: 'isFinished', [this.db.Op.and]: andWhere } });
      closedCount = await this.dao.findCount({ where: { business_status: 'isClosed', [this.db.Op.and]: andWhere } });
    } else {
      let opathstr = '';
      if (opath) {
        opathstr = opath;
        waittoHandledCount = await this.dao.findCount({ where: { business_status: 'beforeSubmission', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, facilitator_id: companyId, [this.db.Op.and]: andWhere } });
        handlingCount = await this.dao.findCount({ where: { business_status: 'beforeConfirmation', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, facilitator_id: companyId, [this.db.Op.and]: andWhere } });
        finishedCount = await this.dao.findCount({ where: { business_status: 'isFinished', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, facilitator_id: companyId, [this.db.Op.and]: andWhere } });
        closedCount = await this.dao.findCount({ where: { business_status: 'isClosed', salesman_opcode: { [this.db.Op.like]: `%${opathstr}%` }, facilitator_id: companyId, [this.db.Op.and]: andWhere } });
      } else {
        waittoHandledCount = await this.dao.findCount({ where: { business_status: 'beforeSubmission', facilitator_id: companyId, [this.db.Op.and]: andWhere } });
        handlingCount = await this.dao.findCount({ where: { business_status: 'beforeConfirmation', facilitator_id: companyId, [this.db.Op.and]: andWhere } });
        finishedCount = await this.dao.findCount({ where: { business_status: 'isFinished', facilitator_id: companyId }, [this.db.Op.and]: andWhere });
        closedCount = await this.dao.findCount({ where: { business_status: 'isClosed', facilitator_id: companyId }, [this.db.Op.and]: andWhere });
      }
    }
    // 成单率
    const allChance = waittoHandledCount + handlingCount + finishedCount + closedCount;
    const successRadio = Math.ceil((finishedCount / allChance) * 100);
    // 如果当前登录人不是平台,那么需要按照opath查询
    return { waittoHandledCount, handlingCount, finishedCount, closedCount, successRadio };
  }
  async findAndCountAll(obj) {
    const self = this;
    const apps = await this.dao.findAndCountAll(obj);
    return apps;
  }

  /* 根据商机编号获取商机详情*/
  async findInfoByDemandCode(qobj) {
    return await this.dao.findInfoByDemandCode(qobj);
  }

  /* 根据商机编号更新商机状态 */
  async updateStatusByDemandCode(qobj) {
    const self = this;
    return self.db.transaction(async t => await self.dao.updateStatusByDemandCode(qobj, t));
  }

  /* 更新业务员信息*/
  async updateSalesmanInfoByDemandCode(qobj) {
    const self = this;
    return self.db.transaction(async t => await self.dao.updateSalesmanInfoByDemandCode(qobj, t));
  }

  /* 插入商机信息*/
  async insertInfo(qobj) {
    const self = this;
    return self.db.transaction(async t => await self.dao.insertInfo(qobj, t));
  }

  /**
     * 查询商机表信息
     * @param pobj
     * @returns {Promise<{}>}
     */
  async getInfo(pobj) {
    const result = {};
    const bizOpInfo = await this.dao.findByBizId(pobj);
    if (!bizOpInfo) {
      throw new Error('没有服务信息');
    }
    // 封装deliverybill表数据
    result.bizOpInfo = {
      demandCode: bizOpInfo.demand_code, // 商机编码
      business_type: bizOpInfo.business_type, // 商机类型
      businessStatus: bizOpInfo.business_status, // 当前商机状态
      businessInfo: bizOpInfo.business_info, // 商机信息
      vConame: bizOpInfo.v_coname, // 联系人-虚拟字段
      vCophone: bizOpInfo.v_cophone, // 联系电话-虚拟字段
      sourceNumber: bizOpInfo.source_number, // 渠道来源编号
      serviceAddress: bizOpInfo.service_address, // 服务地区
      closeReason: bizOpInfo.close_reason, // 状态为关闭原因
      facilitatorId: bizOpInfo.facilitator_id, // 服务商id
      facilitatorName: bizOpInfo.facilitator_name, // 服务商名称
      salesmanOpcode: bizOpInfo.salesman_opcode, // 业务员opcode
      salesmanId: bizOpInfo.salesman_id, // 业务员id
      salesmanName: bizOpInfo.salesman_name, // 业务员名称
      salesmanPhone: bizOpInfo.salesman_phone, // 业务员联系方式
      sourceName: bizOpInfo.source_name, // 渠道名称
      createdAt: bizOpInfo.created_at, // 创建时间
      updatedAt: bizOpInfo.updated_at, // 更新时间
      version: bizOpInfo.version, // o
      bizId: pobj.bizId, // 融易算-服务实例id
    };
    return result;
  }
}
module.exports = BizOptService;

// let test = new BizOptService();
// let a = {
//     "demand_code": "111"
// }
// start(a);
// async function start(a) {
//     let res = await test.findInfoByDemandCode(a);
//     console.log("结果:" + JSON.stringify(res));
// }
