const system = require("../../system");
const ServiceBase = require("../sve.base")
const settings = require("../../../config/settings")
class companyService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(companyService));
    this.userDao = system.getObject("db.userDao");
    this.bankAccountDao = system.getObject("db.moneyaccountDao");
    this.producttypeDao = system.getObject("db.producttypeDao");
    this.serviceitemDao = system.getObject("db.serviceitemDao");
    this.roleDao = system.getObject("db.roleDao");
    this.authDao = system.getObject("db.authDao");
    this.sitethemeDao = system.getObject("db.sitethemeDao");
    this.loopplayDao = system.getObject("db.loopplayDao");
  }
  async findAndCountAll(qobj) {
    if (qobj.search) {
      delete qobj.search.company_id;
    }
    return super.findAndCountAll(qobj);
  }
  //站点订单统计
  async siteOrderStatistic(qobj) {
    var order_created_at = qobj.search.order_created_at || [];
    if (qobj.search) {
      delete qobj.search.company_id;
      delete qobj.search.order_created_at;
    }
    var data = await super.findAndCountAll(qobj);
    if (data && data.results && data.results.count && data.results.count > 0) {
      for (var i = 0; i < data.results.rows.length; i++) {
        var company = data.results.rows[i];
        var sql = "SELECT count(id) orderCount,sum(totalSum) totalSum,sum(totalPublicExpense) totalPublicExpense," +
          "sum(totalTaxes) totalTaxes,sum(totalProfitSum) beforeProfitSum, sum(pfProfitSum) afterProfitSum FROM `biz_order`" +
          " WHERE deleted_at IS NULL ";
        sql = sql + " AND company_id = " + company.id;
        if (order_created_at && order_created_at.length > 0) {
          sql = sql + " AND ( created_at BETWEEN '" + order_created_at[0] + "'  AND '" + order_created_at[1] + "') ";
        }
        sql = sql + " GROUP BY company_id;"
        console.log(sql);
        var ds = await this.dao.customQuery(sql);
        console.log(ds);
        if (ds && ds.length > 0) {
          data.results.rows[i].dataValues["order"] = ds[0];
        } else {
          data.results.rows[i].dataValues["order"] = {
            orderCount: "0",
            totalSum: "0", totalPublicExpense: "0", totalTaxes: "0", beforeProfitSum: "0", afterProfitSum: "0"
          };
        }

      }
    }
    return data;

    // for(var i=0;i<){
    //   var officialsql="SELECT COUNT(*) b from (SELECT count(*) from biz_tmofficial where company_id="+companyId+" and deleted_at is null GROUP BY code) a; "
    // var wscsql="SELECT count(*) b from biz_order where company_id="+companyId+" and deleted_at is null;"
    // var officialCount=await this.service.dao.customQuery(officialsql);
    // var wscCount=await this.service.dao.customQuery(wscsql);
    // }
  }
  async siteupdate(companyInfo, bankaccountinfo) {
    var self = this;
    return this.db.transaction(async function (t) {
      await self.dao.update(companyInfo, t);
      var bnk = await self.bankAccountDao.update(bankaccountinfo, t);
      return {};
    });
  }
  async siteapply(userInfo, companyInfo, bankaccountinfo) {
    var self = this;
    return this.db.transaction(async function (t) {

      var company = await self.dao.create(companyInfo, t);
      userInfo.company_id = company.id;
      var user = await self.userDao.create(userInfo, t);
      //创建账户
      bankaccountinfo.description = "本账户是对外收款账户，线上付款和线下付款，都记入本账户";
      bankaccountinfo.accountType = "bank";
      bankaccountinfo.isOfflinePay = true;
      bankaccountinfo.isPlatformAutopay = true;
      bankaccountinfo.company_id = company.id;
      await self.bankAccountDao.create(bankaccountinfo, t);
      return company;
    });
  }
  //公司数据初始化
  async companyInitdata(obj) {
    //检查是否已经初始化过产品
    var pt = await this.producttypeDao.findOne({ company_id: obj.id });
    if (pt) {
      return {};
    }

    //产品类型
    var productTypeList = await this.producttypeDao.model.findAll({ where: { company_id: 4, isSystem: 1 }, raw: true });
    if (!productTypeList || productTypeList.length == 0) {
      return {};
    }
    //产品
    var serviceitemList = await this.serviceitemDao.model.findAll({ where: { company_id: 4, isSystem: 1 }, raw: true });
    if (!serviceitemList || serviceitemList.length == 0) {
      return {};
    }
    var self = this;
    await this.db.transaction(async function (t) {
      var loopPlayList = await self.loopplayDao.model.findAll({ where: { company_id: 4 }, raw: true });
      if (loopPlayList && loopPlayList.length > 0) {
        var loopitemAddList = [];
        for (let loop = 0; loop < loopPlayList.length; loop++) {
          delete loopPlayList[loop].id;
          loopPlayList[loop].company_id = obj.id;
          loopitemAddList.push(loopPlayList[loop]);
        }
        if (loopitemAddList.length > 0) {
          await self.loopplayDao.bulkCreate(loopitemAddList, t);
        }
      }//轮播图处理
      var rootProductTypeList = productTypeList.filter(f => f.pid == 0);
      if (rootProductTypeList && rootProductTypeList.length > 0) {
        for (let index = 0; index < rootProductTypeList.length; index++) {
          var tmpRootProducttype_id = rootProductTypeList[index].id;//产品大类Id
          delete rootProductTypeList[index].id;
          rootProductTypeList[index].company_id = obj.id;
          var addRootItem = await self.producttypeDao.create(rootProductTypeList[index], t);
          if (addRootItem && addRootItem.id > 0) {
            var tmpProductList = productTypeList.filter(item => item.pid == tmpRootProducttype_id);
            if (tmpProductList && tmpProductList.length > 0) {
              for (let p = 0; p < tmpProductList.length; p++) {
                var tmpProducttype_id = tmpProductList[p].id;//产品类型Id
                delete tmpProductList[p].id;
                tmpProductList[p].company_id = obj.id;
                tmpProductList[p].pid = addRootItem.id;
                var addItem = await self.producttypeDao.create(tmpProductList[p], t);
                if (addItem && addItem.id > 0) {
                  var tmpList = serviceitemList.filter(sItem => sItem.producttype_id == tmpProducttype_id);
                  if (!tmpList || tmpList.length == 0) {
                    continue;
                  }
                  var serviceitemAddList = [];
                  for (var j = 0; j < tmpList.length; j++) {
                    delete tmpList[j].id;
                    delete tmpList[j].channelProfitRate;
                    tmpList[j].company_id = obj.id;
                    tmpList[j].producttype_id = addItem.id;
                    tmpList[j].producttype_pid_id = addItem.pid;
                    serviceitemAddList.push(tmpList[j]);
                  }
                  if (serviceitemAddList.length > 0) {
                    await self.serviceitemDao.bulkCreate(serviceitemAddList, t);
                  }
                }//处理产品
              }//处理产品类型
            }
          }
        }
        //角色
        var rolestocopy = await self.roleDao.model.findAll({ where: { company_id: 1 }, raw: true, });
        for (var i = 0; i < rolestocopy.length; i++) {
          delete rolestocopy[i].id;
          rolestocopy[i].company_id = obj.id;
        }
        await self.roleDao.bulkCreate(rolestocopy, t);
        //授权
        var authcopy = await self.authDao.model.findAll({ where: { company_id: 1 }, raw: true, });
        for (var i = 0; i < authcopy.length; i++) {
          delete authcopy[i].id;
          authcopy[i].company_id = obj.id;
        }
        await self.authDao.bulkCreate(authcopy, t);
      }//有对应的大类
    });
  }

  //站点商机统计
  async siteBusinessStatistic(qobj) {
    var order_created_at = qobj.search.order_created_at || [];
    if (qobj.search) {
      delete qobj.search.company_id;
      delete qobj.search.order_created_at;
    }
    var data = await super.findAndCountAll(qobj);
    if (data && data.results && data.results.rows && data.results.rows.length > 0) {
      for (var i = 0; i < data.results.rows.length; i++) {
        var company = data.results.rows[i];
        var sql = "SELECT business_status as s_name,count(business_status) AS s_value FROM `bi_businesscompany` " +
          " WHERE 1=1 ";
        sql = sql + " AND createcompany_id = " + company.id;
        if (order_created_at && order_created_at.length > 0) {
          sql = sql + " AND ( created_at BETWEEN '" + order_created_at[0] + "'  AND '" + order_created_at[1] + "') ";
        }
        sql = sql + " GROUP BY business_status;"
        console.log(sql);
        var ds = await this.dao.customQuery(sql);
        console.log(ds);
        var statisticObj = { "yff": "0", "wrl": "0", "yrl": "0", "yxd": "0", "bhz": "0", "wx": "0" };
        if (ds && ds.length > 0) {
          for (var j = 0; j < ds.length; j++) {
            var d = ds[j];
            if (d.s_name) {
              //wff未分发、yff已分发、wrl未认领、yrl已认领、bhz保护中、wx无效、yxd已下单
              statisticObj[d.s_name] = d.s_value || 0;
            }
          }
        }
        data.results.rows[i].dataValues["statistic"] = statisticObj;
        data.results.rows[i]["statistic"] = statisticObj;
        var sql2 = "SELECT count(id) AS count FROM `p_user` " +
          " WHERE deleted_at IS NULL ";
        sql2 = sql2 + " AND company_id = " + company.id;
        var us = await this.dao.customQuery(sql2);
        if (us && us.length > 0) {
          var u = us[0];
          data.results.rows[i].dataValues["ucount"] = u.count || "0";
          data.results.rows[i]["ucount"] = u.count || "0";
        } else {
          data.results.rows[i].dataValues["ucount"] = "0";
          data.results.rows[i]["ucount"] = "0";
        }
        var sql3 = "SELECT sum(order_num) AS sum FROM `bi_businesscompany` " +
          " WHERE order_num IS NOT NULL ";
        sql3 = sql3 + " AND createcompany_id = " + company.id;
        if (order_created_at && order_created_at.length > 0) {
          sql3 = sql3 + " AND ( created_at BETWEEN '" + order_created_at[0] + "'  AND '" + order_created_at[1] + "') ";
        }
        var xds = await this.dao.customQuery(sql3);
        if (xds && xds.length > 0) {
          var xd = xds[0];
          data.results.rows[i].dataValues["order_num"] = xd.sum || "0";
          data.results.rows[i]["order_num"] = xd.sum || "0";
        } else {
          data.results.rows[i].dataValues["order_num"] = "0";
          data.results.rows[i]["order_num"] = "0";
        }
      }
    }
    return data;
  }

  async getCompanyThemeById(id) {
    var item = await this.dao.model.findOne({
      where: { id: id },
      attributes: ["id", "sitename", "siteTheme", "sitetheme_id"],
      include: [
        { model: this.sitethemeDao.db.models.sitetheme, attributes: ["id", "siteTheme", "siteThemeName", "themeAddr"] }
      ]
    });
    if (!item || !item.sitetheme) {
      return { code: -201, msg: "站点主题信息有误" }
    }
    return { code: 1, msg: "ok", data: item }
  }
  async putCompanyThemeById(company_id, user_id, sitetheme) {
    var themeItem = await this.sitethemeDao.model.findOne({ where: { isEnabled: 1, siteTheme: sitetheme } });
    if (!themeItem) {
      return { code: -201, msg: "主题信息未启用或有误" }
    }
    await this.updateByWhere({ siteTheme: sitetheme, sitetheme_id: themeItem.id, updated_at: new Date().getTime().toString() },
      { where: { id: company_id } });
    return { code: 1, msg: "ok" }
  }
  async getCompanyByHostname(hostname) {//按照hostname去查找公司站点信息
    return await this.dao.getCompanyInfoByHostname(hostname);
  }

  async aftercreate(result, u, t) {
    if (u.weblinks && u.weblinks.length > 0) {
      var weblinks = await this.db.models.weblink.findAll({ where: { id: { [this.db.Op.in]: u.weblinks } } });
      console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
      console.log(weblinks);
      if (weblinks && weblinks.length > 0) {
        await result.setWeblinks(weblinks, { transaction: t });
      }
    }
    return result;
  }
  async create(qobj) {
    var self = this;
    var code = await this.getBusUid("c");
    qobj["code"] = code;
    return this.db.transaction(async function (t) {
      var result = await self.dao.create(qobj, t);
      await self.aftercreate(result, qobj, t);
      return result;
    });
  }
}
module.exports = companyService;
