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.usereaccountDao = system.getObject("db.usereaccountDao")
    this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");
    this.userDao = system.getObject("db.userDao");

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

  }

  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.ecompanyIds) {
      where.ecompany_id = {
        [this.db.Op.in]: params.ecompanyIds
      };
    }

    if (params.ecompany_id) {
      where.ecompany_id = params.ecompany_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`, `ecompany_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.setCompany(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 setCompany(list) {
    if (!list || list.length == 0) {
      return;
    }

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

  async findInfo(obj) {
    obj = obj || {};
    let v = [{
        model: this.db.models.ecompany,
        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.ecompany,
        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;

      // 合同下载任务
      this.redisClient.rpushBCD({id: contract.id, sve: "dk"});
      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, "econtractSve");
          console.log(fileRs, "===============================================================");
          if (fileRs.code == 1 && fileRs.data.selfossUrl) {
            contract.fileurl = fileRs.data.selfossUrl;
            contract.save();
          } else {
            await this.utilesignbaoSve.archiveProcess({flowId: contract.eflowid}, "econtractSve");
            let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "econtractSve");
            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 downloadContract(id) {
    try {
      let contract = await this.dao.findById(id);
      if (!contract || contract.eflowstatus != "2" || contract.fileurl) {
        return ;
      }

      //await this.syncYzSign(2134);
      //  请求文件地址
      let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "econtractSve");
      if (fileRs.code == 1 && fileRs.data.selfossUrl) {
        contract.fileurl = fileRs.data.selfossUrl;
        await contract.save();
        this.syncYzSign(contract.id);
      } else {
        await this.utilesignbaoSve.archiveProcess({flowId: contract.eflowid}, "econtractSve");
        let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "econtractSve");
        if (fileRs.code == 1 && fileRs.data.selfossUrl) {
          contract.fileurl = fileRs.data.selfossUrl;
          await contract.save();
          this.syncYzSign(contract.id);
        }
      }
    } catch (e) {
      console.error(e);
      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;