var system = require("../../system")
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
const moment = require("moment");
class DKcompanyCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(DKcompanyCtl));

    this.userSve = system.getObject("service.userSve");

    this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");

  }


  async signList(queryobj, qobj, req) {
    var params = qobj.search;
    try {
      var page = await this.service.pageByCondition(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    } 
  }

  async signSave(queryobj, qobj, req) {
    try {
      var rtn = null;
      var dkcompany = await this.buildCompeny(qobj);
      var isCreateSealKey = dkcompany.isCreateSealKey;
      if (dkcompany.id) {
        //修改
        await dkcompany.save();
      } else {
        //新增
        dkcompany = await this.service.create(dkcompany);
      }

      if(isCreateSealKey || !dkcompany.sealFileKey) {
        // 创建企业印章fileKey
        // var accountId = "740b19e0799a4d7abacfa1a31fb72b1e";  // 测试
        // var accountId = "f50d8f8cdd8d4bcda6b1aaad1d4b14bf";  // 生产
        var accountId = settings.apiconfig.companyAccountId();  // 生产
        var aliasName = dkcompany.id + "-" + uuidv4();
        var rs = await this.utilesignbaoSve.createEntSeal(dkcompany.sealUrl, accountId,  aliasName, "dkcompanyCtl");
        if(rs.code == 1) {
          dkcompany.sealFileKey = rs.data.fileKey;
          dkcompany.sealId = rs.data.sealId;
          await dkcompany.save();
        }
      }
      return system.getResult2(1, null);
    } catch (e) {
      console.log("-----------------------------e");
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async buildCompeny(qobj) {
    var dkcompany = null;
    if (qobj.id) {
      dkcompany = await this.service.findById(qobj.id);
      dkcompany.isCreateSealKey = dkcompany.sealUrl != qobj.sealUrl;
    } else {
      dkcompany = {isCreateSealKey: true};
    }

    dkcompany.name = qobj.name;
    dkcompany.isEnabled = true;
    dkcompany.isQuiet = true;

    dkcompany.legal = qobj.legal || "";
    dkcompany.phone = qobj.phone || "";
    dkcompany.addr = qobj.addr || "";
    dkcompany.owner_id = qobj.owner_id;

    dkcompany.sealUrl = qobj.sealUrl || "";
    return dkcompany;
  }

  async mySignList(queryobj, qobj, req) {
    var params = qobj.search;
    if(!req.session.myIds || req.session.myIds.length == 0) {
      params.ownerIds = [req.session.user.id];
    } else {
      params.ownerIds = req.session.myIds;
    }

    try {
      var page = await this.service.signPage(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    } 
  }

  async mySignSave(queryobj, qobj, req) {
    try {
      var dkcompany = null;
      if (qobj.id) {
        dkcompany = await this.service.findById(qobj.id);
      }
      var rtn = null;
      if (dkcompany) { //修改
        dkcompany.name = qobj.name;
        dkcompany.encryptkey = qobj.encryptkey || "";
        dkcompany.posturl = qobj.posturl || "";
        dkcompany.isEnabled = qobj.isEnabled;
        dkcompany.owner_id = req.session.user.id;
        await dkcompany.save();
      } else { //新增
        var dkcompany = {};
        dkcompany.name = qobj.name;
        dkcompany.encryptkey = qobj.encryptkey || "";
        dkcompany.posturl = qobj.posturl || "";
        dkcompany.isEnabled = qobj.isEnabled;
        dkcompany.owner_id = req.session.user.id;
        dkcompany = await this.service.create(dkcompany);
      }

      return system.getResult2(dkcompany, null);
    } catch (e) {
      console.log("-----------------------------e");
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async suggest(queryobj, qobj, req) {
    var name = this.trim(qobj.name);
    if(!name) {
      return system.getResult2([])
    }
    var ids = [];
    if(qobj.ismy) {
      ids.push(req.session.user.id);
    }
    
    var list = await this.service.suggest(name, ids);
    return system.getResult2(list);
  }
 


  async allList(queryobj, qobj, req) {
    var params = {};

    var loginUser = req.session.user;
    var roles = loginUser.Roles || [];
    var isZC = false;
    for(var r of roles) {
      if(r.code == 'zcry' || r.code == 'zcgl') {
        isZC = true;
        break;
      }
    }
    if(!loginUser.isAdmin && !isZC) {
      if(!req.session.myIds || req.session.myIds.length == 0) {
        return system.getResult2({count: 0, rows: []});
      }
      params.ownerIds = req.session.myIds;
    }
    return await this.list(queryobj, qobj, req, params);
  }

  async myList(queryobj, qobj, req) {
    var params = {
      owner_id: req.session.user.id
    }
    return await this.list(queryobj, qobj, req, params);
  }

  async list(queryobj, qobj, req, params) {
    // 1待审核 2通过 3驳回
    // "proxyAuditStatus": {"0":"待审核","1":"审核通过","2":"审核驳回"},
    if (!qobj.search) {
      qobj.search = {};
    }
    var auditType;
    if (params) {
      if (params.owner_id) {
        qobj.ownerIds = [params.owner_id];
      } else if(params.ownerIds) {
        qobj.ownerIds = params.ownerIds;
      }
    }
    qobj.raw = true;
    var rs = await super.findAndCountAll(queryobj, qobj, req);

    if (rs && rs.data && rs.data.rows) {
      var ownerIds = [];
      for (var row of rs.data.rows) {
        if (row.updated_at) {
          row.updated_at = new Date(row.updated_at).Format("yyyy-MM-dd hh:mm");
        }
        if (row.created_at) {
          row.created_at = new Date(row.created_at).Format("yyyy-MM-dd hh:mm");
        }
        if (row.updated_at) {
          row.updated_at = new Date(row.updated_at).Format("yyyy-MM-dd hh:mm");
        }

        if (row.owner_id) {
          ownerIds.push(row.owner_id);
        }
      }

      var usermap = await this.userSve.findMapByIds(ownerIds);
      if (ownerIds.length > 0) {
        for (var row of rs.data.rows) {
          if (row.owner_id) {
            row.owner = usermap["id_" + row.owner_id];
          }
        }
      }
    }
    return rs;
  }

  async info(queryobj, qobj, req) {
    var id = qobj.id;
    try {
      var info = await this.service.getInfo(id);
      if(info) {
        if(info.owner_id) {
          info.owner = await this.userSve.findById(info.owner_id);
        }
        if(info.created_at) {
          info.created_at = moment(info.created_at).format("YYYY-MM-DD HH:mm:ss");
        }
      }
      return system.getResult2(info);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    } 
  }
}
module.exports = DKcompanyCtl;