const system=require("../../system");
const ServiceBase=require("../sve.base");
const moment = require("moment");
class EcompanyService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(EcompanyService));
     this.etemplateDao = system.getObject("db.etemplateDao");
     this.wxSve = system.getObject("service.wxSve");

     this.emessageDao = system.getObject("db.emessageDao");
     this.ecompanyeventDao = system.getObject("db.ecompanyeventDao");
     this.userDao = system.getObject("db.userDao");
  }

  async importCompany(name, nameA, encryptkey, posturl, etemplate) {
    let self = this;

    if(!name) {
      return 0;
    }
    var company = await super.findOne({name:name});
    if(company) {
      return 0;
    }

    company = {
      "name" : name,
      "nameA" : nameA || '智信云（天津）科技有限公司',
      "isEnabled" : true,
      "isQuiet" : true,
      "sealurl" : "",
      "encryptkey" : encryptkey || "",
      "posturl": posturl || ""
    }
    return this.db.transaction(async function (t) {
        // 更新派工态
        company = await self.dao.create(company, t);

        var newTemplate = {
          ecompany_id:company.id,
          name:name,
          templateid:etemplate.templateid,
          filekey:etemplate.filekey,//e签宝返回文件key
          filepath:etemplate.filepath,//需要在后台补充
          placeholderkey:etemplate.placeholderkey,//模板占位信息
          isEnabled:true,
        };

        newTemplate = await self.etemplateDao.create(newTemplate, t);

        var qrcodeurl = await self.wxSve.makeQrWithScene("wxf616c0a459d66081", newTemplate.id);
        newTemplate.qrcodeurl = qrcodeurl;
        await newTemplate.save();
        return company.id;
    });
  }

  async isExistsCompanyName(name) {
    //0-不存在，1-存在
    var company = await super.findOne({name:name});
    if(company) {
      return 1;
    }
    return 0;
  }

  async companyBycontrId(contractId) {

    var sql = "SELECT name from c_ecompany where isEnabled = 1 AND ecompanycontract_id = :contractId"
    var list = await this.customQuery(sql, {contractId:contractId});
    if(list && list.length > 0) {
      return list;
    }
      
    return null;
  }

  async savebpo(company) {
    if(!company) {
      return null;
    }

    var self = this;

    var etemplate = await this.etemplateDao.findById(495);
    return this.db.transaction(async function (t) {
      // 更新派工态
      company = await self.dao.create(company, t);

      var newTemplate = {
        ecompany_id: company.id,
        name: company.name,
        templateid: etemplate.templateid,
        filekey: etemplate.filekey, //e签宝返回文件key
        filepath: etemplate.filepath, //需要在后台补充
        placeholderkey: etemplate.placeholderkey, //模板占位信息
        isEnabled: true,
      };

      newTemplate = await self.etemplateDao.create(newTemplate, t);

      var qrcodeurl = await self.wxSve.makeQrWithScene("wxf616c0a459d66081", newTemplate.id);
      newTemplate.qrcodeurl = qrcodeurl;
      await newTemplate.save();
      return company;
    });
  }

  async findMapByIds(ids) {
    return await this.dao.findMapByIds(ids);
  }

  async signPage(params) {
    var currentPage = Number(params.currentPage || 0);
    var pageSize = Number(params.pageSize || 10);

    var where = {};
    if (params.name) {
      where.name = {
        [this.db.Op.like]: "%" + params.name + "%"
      };
    }

    if(params.ownerIds && params.ownerIds.length > 0) {
      where.owner_id = {[this.db.Op.in]: params.ownerIds};
    }

    if(params.owner_id) {
      where.owner_id = params.owner_id;
    }

    var orderby = [
      ["id", 'desc']
    ];

    var attributes = ["id", "created_at", "updated_at", "encryptkey", "posturl", "name", "owner_id", "isEnabled"];
    var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
    if (page && page.rows) {
      for(var row of page.rows) {
        this.handleDate(row, ["created_at" , "updated_at"]);
      }
      await this.setOwner(page.rows);
    }
    return page;
  }

  async setOwner(rows) {
    if (!rows || rows.length == 0) {
      return;
    }

    var ownerIds = [];
    for (var row of rows) {
      if (row.owner_id) {
        ownerIds.push(row.owner_id);
      }
    }

    if (ownerIds.length == 0) {
      return;
    }

    var ownerMap = await this.userDao.findMapByIds(ownerIds);
    for (var row of rows) {
      if (row.owner_id) {
        row.owner = ownerMap["id_" + row.owner_id] || {};
      }
    }

    console.log(rows);
  }

  async authPage(params) {
    var currentPage = Number(params.currentPage || 0);
    var pageSize = Number(params.pageSize || 10);

    var where = {};
    where.user_id = {[this.db.Op.gt]: 0};
    if (params.name) {
      where.name = {
        [this.db.Op.like]: "%" + params.name + "%"
      };
    }

    if (params.contractName) {
      where.contractName = {
        [this.db.Op.like]: "%" + params.contractName + "%"
      };
    }

    if (params.industry) {
      where.industry = params.industry;
    }

    if (params.jdAuthStatus) {
      where.jdAuthStatus = params.jdAuthStatus;
    }

    this.addWhereTime(where, 'jdAuthApplyTime', params.applyBegin, params.applyEnd);
    this.addWhereTime(where, 'jdAuthTime', params.auditBegin, params.auditEnd);

    var orderby = [
      ["id", 'desc']
    ];
    
    var attributes = ["id", "created_at", "jdAuthApplyTime", "jdAuthTime", "name", "nature", "industry", 
      "addr","intro", "contractName", "contractMobile","jdAuthStatus", "jdAuthStatusName"];
    
    var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
    if (page && page.rows) {
      for(var row of page.rows) {
        this.handleDate(row, ["created_at" , "jdAuthApplyTime", "jdAuthTime"]);
      }
    }
    return page;
  }

  async getInfo(id) {
    var attrs = ["businessLicense", "logo", "nature", "industry", "addr", "intro", "telephone", "email", 
    "jdAuthStatus", "jdAuthStatusName","jdAuthApplyTime", "jdAuthTime", "authNotes", "created_at" ];

    return await this.dao.model.findOne({
      where: { id: id }, attrs, raw: true
    });
  }

  async getCompany(id) {
    var attrs = ["id", "name"];

    return await this.dao.model.findOne({
      where: { id: id }, attrs, raw: true
    });
  }

  async jdAuth(id, jdAuthStatus, auditRemark, userId) {
    var ecompany = await this.findById(id);
    if(!ecompany) {
      return -1;
    }
    if(ecompany.jdAuthStatus != '0') {
      return -2;
    }
    if(jdAuthStatus == '2' && !auditRemark) {
      return -3;
    }

    var msg = "您的企业认证";
    if(jdAuthStatus == '1') {
      ecompany.jdAuthStatus = '1';
      ecompany.jdAuthStatusName = "已认证";
      ecompany.authNotes = "";
      msg = msg + "成功";
    } else {
      ecompany.jdAuthStatus = '2';
      ecompany.jdAuthStatusName = "已驳回";
      ecompany.authNotes = auditRemark;
      msg = msg + "失败, 原因【" + auditRemark + "】";
    }
    ecompany.jdAuthTime = new Date();
    ecompany.jdAuthId = userId;
    await ecompany.save();

    this.emessageDao.create({
      user_id : ecompany.user_id,
      type : 5,
      title : jdAuthStatus == '1' ? "认证成功" : "认证失败",
      read : 0,
      content : msg
    });
    this.ecompanyeventDao.doBiz(ecompany.id, 2);
    return 1;
  }

  async findNamesByEPartnerId(epartnerId) {
    return await this.dao.findNamesByEPartnerId(epartnerId);
  }

  async findNamesByOwnerIds(ownerIds) {
    return await this.dao.findNamesByOwnerIds(ownerIds);
  }

  async findIdsByOwnerIds(ownerIds) {
    return await this.dao.findIdsByOwnerIds(ownerIds);
  }


  async suggest(name, ownerIds) {
    return await this.dao.suggest(name, ownerIds);
  }
}

module.exports=EcompanyService;
