const system = require("../../system");
const ServiceBase = require("../sve.base");
const logCtl = system.getObject("web.oplogCtl");

const moment = require('moment');
const crypto = require('crypto');
const cryptoJS = require("crypto-js");
const md5 = require("MD5");

class DKcontractService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(DKcontractService));
    this.dkcompanyDao = system.getObject("db.dkcompanyDao");
    this.dktemplateDao = system.getObject("db.dktemplateDao");

    this.usereaccountDao = system.getObject("db.usereaccountDao")
    this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");
    this.userDao = system.getObject("db.userDao");

    this.restClient = system.getObject("util.restClient");
  }

  async getInfo(id) {
    var attrs = [];
    return await this.dao.model.findOne({
      where: { id: id }, attrs, raw: true
    });
  }


  async findSindIds(accountId, dktemplateId) {
    var sql = [];
    sql.push("SELECT id");
    sql.push("FROM `c_dkcontract` ");
    sql.push("WHERE dktemplate_id = :dktemplate_id AND usereaccount_id = :usereaccount_id AND eflowstatus = '2' ");

    var list = await this.customQuery(sql.join(" "), {usereaccount_id:Number(accountId), dktemplate_id: Number(dktemplateId)});
    if(!list || list.length == 0) {
      return [];
    }

    var ids = [];
    for(var item of list) {
      ids.push(item.id);
    }
    return ids;
  }

  async findSignedList(accountId, dktemplateId) {
    var sql = [];
    sql.push("SELECT *");
    sql.push("FROM `c_dkcontract` ");
    sql.push("WHERE dktemplate_id = :dktemplate_id AND usereaccount_id = :usereaccount_id AND eflowstatus = '2' ");

    var list = await this.customQuery(sql.join(" "), {usereaccount_id:Number(accountId), dktemplate_id: Number(dktemplateId)});
    if(!list || list.length == 0) {
      return [];
    }

    for(var item of list) {
      if(item.completed_at) {
        item.completed_at = moment(item.completed_at).format("YYYY-MM-DD HH:mm");
      }
    }
    return list;
  }

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

    var where = {};

    if(params.templateName && params.templateName.trim()) {
      var templateIds = await this.dktemplateDao.findIdsLikeName(params.templateName.trim());
      if(!templateIds || templateIds.length == 0) {
        return {count: 0, rows: []};
      }

      where.dktemplate_id =  {
        [this.db.Op.in]: templateIds
      };
    }
    if (params.dkcompanyIds) {
      where.dkcompany_id = {
        [this.db.Op.in]: params.dkcompanyIds
      };
    }

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

    if (params.eflowstatusList) {
      where.eflowstatus = {
        [this.db.Op.in]: params.eflowstatusList
      };;
    }

    if (params.accountName || params.accountMobile || params.accountIdno) {
      var accountIds = await this.usereaccountDao.idsByCondition({
        userName: params.accountName || "",
        mobile: params.accountMobile || "",
        personsSign: params.accountIdno || "",
      });

      if (!accountIds || accountIds.length == 0) {
        return {
          total: 0,
          rows: []
        };
      }

      where.usereaccount_id = {
        [this.db.Op.in]: accountIds
      };
    }
    this.addWhereTime(where, 'completed_at', params.signBegin, params.signEnd, true);

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

    var attributes = [`id`, `fileurl`, `eflowstatus`, `eflowstatusname`, `completed_at`, `end_at`, `user_id`, `usereaccount_id`, `dkcompany_id`, `dktemplate_id`];

    var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
    if (page && page.rows) {
      for (var row of page.rows) {
        this.handleDate(row, ["completed_at", "end_at"], null);
      }
      await this.setEaccount(page.rows);
      await this.setDkompany(page.rows);
      await this.setDkTemplate(page.rows);
    }
    return page;
  }

  async setEaccount(list) {
    if (!list || list.length == 0) {
      return;
    }

    var ids = [];
    for (var item of list) {
      ids.push(item.usereaccount_id);
    }
    var attrs = " `id`, `mobile`, `userName`, `personsSign`, `bankno` ";
    var accountMap = await this.usereaccountDao.findMapByIds(ids, attrs);

    for (var item of list) {
      item.eaccount = accountMap["id_" + item.usereaccount_id];
    }
  }

  async setDkompany(list) {
    if (!list || list.length == 0) {
      return;
    }

    var companyIds = [];
    for (var item of list) {
      companyIds.push(item.dkcompany_id || 0);
    }
    var companyMap = await this.dkcompanyDao.findMapByIds(companyIds, " id, name ");
    for (var item of list) {
      item.dkcompany = companyMap["id_" + (item.dkcompany_id || 0)];
    }
  }

  async setDkTemplate(list) {
    if (!list || list.length == 0) {
      return;
    }

    var ids = [];
    for (var item of list) {
      ids.push(item.dktemplate_id || 0);
    }
    var templateMap = await this.dktemplateDao.findMapByIds(ids, " id, name ");
    for (var item of list) {
      item.dktemplate = templateMap[item.dktemplate_id] || {};
    }
  }

  async findInfo(obj) {
    obj = obj || {};
    let v = [{
        model: this.db.models.dkcompany,
        attributes: ["id", "name"]
      },
      {
        model: this.db.models.user,
        attributes: ["id", "userName", "mobile"]
      },
      {
        model: this.db.models.usereaccount,
        attributes: ["id", "userName", "mobile", "personsSign"]
      },
      {
        model: this.db.models.etemplate,
        attributes: ["id", "name"]
      }
    ];
    var result = await this.dao.model.findOne({
      where: obj,
      include: v
    });
    return result;
  }

  async findContracts(obj) {
    obj = obj || {};
    let v = [{
        model: this.db.models.dkcompany,
        attributes: ["id", "name"]
      },
      {
        model: this.db.models.user,
        attributes: ["id", "userName", "mobile"]
      },
      {
        model: this.db.models.usereaccount,
        attributes: ["id", "userName", "mobile", "personsSign"]
      },
      {
        model: this.db.models.etemplate,
        attributes: ["id", "name"]
      }
    ];
    var result = await this.dao.model.findAll({
      where: obj,
      include: v
    });
    return result;
  }

  async updateCallbackStatus(obj) {
    obj = obj || {};

    logCtl.info({
      optitle: "e签宝回调修改合同信息info",
      op: "app/base/service/impl/dkcontractSve/updateCallbackStatus",
      content: "请求参数：" + JSON.stringify(obj),
      clientIp: ""
    });

    let contract;
    try {
      let signTime = obj.signTime;
      let signResult = obj.signResult || "1";
      let thirdOrderNo = Number(obj.thirdOrderNo.substring(3) || 0);

      contract = await this.findById(Number(thirdOrderNo));
      if (!contract) {
        return;
      }

      contract.eflowstatus = signResult.toString();
      contract.completed_at = signTime;
      contract.begin_at = signTime;
      contract.resultDescription = obj.resultDescription || "";
      var end_at = new Date(signTime);
      end_at.setFullYear(end_at.getFullYear() + 1);
      contract.end_at = end_at;

      await contract.save();
    } catch (e) {
      logCtl.error({
        optitle: "e签宝回调修改合同信息error",
        op: "app/base/service/impl/dkcontractSve/updateCallbackStatus",
        content: "错误信息：" + e.stack,
        clientIp: ""
      });
    }
    return contract;
  }

  async downloadCompleteUrl(limit) {
    var sql = "SELECT id FROM `c_dkcontract` WHERE eflowstatus = '2' AND (fileurl IS NULL OR fileurl = '')  ORDER BY id DESC ";
    if (limit) {
      sql = sql + " LIMIT " + limit;
    }
    var list = await this.dao.customQuery(sql);

    if (!list || list.length == 0) {
      return;
    }

    for (var o of list) {
      var id = o.id;
      try {
        var contract = await this.dao.findById(id);
        if (!contract) {
          continue;
        }

        if (contract.eflowstatus != "2") {
          continue;
        }

        if (!contract.fileurl) {
          //  请求文件地址
          let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "dkcontractSve");
          console.log(fileRs, "===============================================================");
          if (fileRs.code == 1 && fileRs.data.selfossUrl) {
            contract.fileurl = fileRs.data.selfossUrl;
            contract.save();
          }
        }
      } catch (e) {
        console.error(e);
        //日志记录
        logCtl.error({
          optitle: "定时下载合同任务异常, id=" + id,
          op: "app/base/service/impl/econtractSve.js",
          content: e.stack,
          clientIp: ""
        });
        return {
          code: -200,
          message: "error",
          data: {}
        };
      }
    }
  }

  async getContractUrl(id) {
    var contract = await this.findById(id);
    if (contract.fileurl) {
      return contract.fileurl;
    }

    let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "econtractSve");
    if (fileRs.code == 1 && fileRs.data.selfossUrl) {
      contract.fileurl = fileRs.data.selfossUrl;
      await contract.save();
      return contract.fileurl;
    }
    return "";
  }

  async testtransfer(result) {
    var date = new Date().Format("yyyy-MM-dd hh:mm:ss");
    var v = JSON.stringify(result) + "---" + date;
    var sql = "INSERT INTO `testtransfer` (`v`) VALUES ('" + v + "')  ";
    await this.dao.customExecAddOrPutSql(sql, {});
  }

  async formateTime(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  }

  async formateTime2(inputTime) {
    if (!inputTime) {
      return '';
    }
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '' + m + '' + d + '' + h + '' + minute + '' + second;
  }

  async getUidStr(len, radix) {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    var uuid = [],
      i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }
}
module.exports = DKcontractService;