const system = require("../../system");
const Dao = require("../dao.base");

class EcontractDao extends Dao {
  constructor() {
    super(Dao.getModelName(EcontractDao));
  }

  extraModelFilter(qobj) {
    var usereaccountWhere = {};
    if (qobj.accountMobile) {
      usereaccountWhere.mobile = qobj.accountMobile;
    }

    if (qobj.accountName) {
      usereaccountWhere.userName = qobj.accountName;
    }

    if (qobj.accountIdno) {
      usereaccountWhere.personsSign = qobj.accountIdno;
    }

    let v = [
      {model: this.db.models.ecompany, attributes: ["id", "name"]},
      {
        model: this.db.models.usereaccount,
        attributes: ["id", "userName", "mobile", "personsSign", "email"],
        where: usereaccountWhere
      },
      {model: this.db.models.etemplate, attributes: ["id", "name"]}
    ];
    //return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
    return {"key": "include", "value": v};
  }

  async findUserSinedCompanyIds(usereaccount_id) {
    let sql = "SELECT ecompany_id FROM `c_econtract` WHERE usereaccount_id = :usereaccount_id AND begin_at < NOW() AND end_at > NOW() AND eflowstatus = '2' GROUP BY ecompany_id";

    let tmpParas = {usereaccount_id: usereaccount_id}

    let rs = await this.customQuery(sql, tmpParas);
    let list = [];
    if (rs && rs.length > 0) {
      for (let r of rs) {
        list.push(r.ecompany_id);
      }
    }
    return list;
  }

  async findUserSinedTemplateIds(usereaccount_id) {
    let sql = "SELECT etemplate_id FROM `c_econtract` WHERE usereaccount_id = :usereaccount_id AND begin_at < NOW() AND end_at > NOW() AND eflowstatus = '2' GROUP BY etemplate_id";

    let tmpParas = {usereaccount_id: usereaccount_id}

    let rs = await this.customQuery(sql, tmpParas);
    let list = [];
    if (rs && rs.length > 0) {
      for (let r of rs) {
        list.push(r.etemplate_id);
      }
    }
    return list;
  }

  async getFlowIdsAccountIds(accountIds, etemplate_id) {
    if (!accountIds || accountIds.length == 0) {
      return [];
    }
    let sql = "SELECT id, fileurl FROM `c_econtract` WHERE usereaccount_id IN (:accountIds) AND eflowstatus = '2' AND etemplate_id = :etemplate_id ORDER BY id DESC";

    let tmpParas = {etemplate_id: etemplate_id, accountIds: accountIds};
    let rs = await this.customQuery(sql, tmpParas);
    if (!rs || rs.length === 0) {
      return [];
    }
    return rs;
  }
}

module.exports = EcontractDao;
