var system = require("../../../system");
const apiBase = require("../../api.base");
const axios = require("axios");
const moment = require("moment");
class XbgApi extends apiBase {

  constructor() {
    super();
    this.restClient = system.getObject("util.restClient");
    //this.url = "http://127.0.0.1:3333/api/xbgApi/";
    this.url = "https://bpohhr.gongsibao.com/api/xbgApi/";
    this.testCompanyIds = 12;
    this.ecompanyId = '1103817785420820481';
    this.recruitSve = system.getObject("service.operator.recruitSve");
    this.userlabourSve = system.getObject("service.operator.userlabourSve");
    this.usersSve = system.getObject("service.operator.usersSve");
    this.userconfSve = system.getObject("service.operator.userconfSve");
    this.excelClient = system.getObject("util.excelClient");
    // this.companyConfig = {
    //   yd: {
    //     signCompanyIds: [10173, 492],
    //     payCompanyIds: ['1152185172836229121', '1152186076306087937', '1165922409285480450', '1169516233595670529', '1174219506669584386', '1197064800073707522', '1199605424102690818'],
    //     companyInfo: {
    //       companyName: "上海韵达货运有限公司",
    //       taxType: "一般纳税人",
    //       contactName: "陈梁",
    //       contactEmail: "chenliang8725@yundasys.com",
    //       contactAddr: "上海市青浦区赵巷镇盈港东路6679号",
    //       bankAccount: "上海韵达货运有限公司",
    //       openBank: "邮政储蓄银行青浦支行",
    //       bankno: "100360752790012735",
    //       sign_body: "舟山兰和科技有限公司",
    //       signBeginTime: "2019-08-26",
    //       signEndTime: "2020-08-26",
    //       contract_url: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_247111576475725735201916135525735contract_yd.pdf",
    //       business_license: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_2671115777007820212019301813221yd_b.jpg",
    //     },
    //     dataView: {
    //       actual_amt: "157073.09",
    //       contractCount: 11804,
    //       income_tax: "0",
    //     },
    //   },
    //   tfb: {
    //     signCompanyIds: [11410, 492],
    //     payCompanyIds: ['1187270470698082306', '1187272600083308546', '1187274198010056705', '1202100969987661826'],
    //     companyInfo: {
    //       companyName: "杭州淘粉吧网络技术股份有限公司",
    //       taxType: "一般纳税人",
    //       contactName: "王萍",
    //       contactEmail: "wangping@taofen8.com",
    //       contactAddr: "浙江省杭州市西湖区西斗门路9号福地创业园1号楼2楼",
    //       bankAccount: "杭州淘粉吧网络技术股份有限公司",
    //       openBank: "杭州银行学院路支行",
    //       bankno: "3301040160000822687",
    //       sign_body: "舟山兰和科技有限公司",
    //       signBeginTime: "2019-10-24",
    //       signEndTime: "2020-10-24",
    //       contract_url: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_59111576475747388201916135547388contract_tfb.pdf",
    //       business_license: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_142111576475271657201916134751657bl_tfb.jpg",
    //     },
    //     dataView: {
    //       actual_amt: "197701.2",
    //       contractCount: 16,
    //       income_tax: "0",
    //     },
    //   },
    //   heifan: {
    //     signCompanyIds: [10284],
    //   }
    // }

    // this.userConfig = {
    //   26: this.companyConfig.yd,
    //   29: this.companyConfig.yd,
    //   44: this.companyConfig.heifan,
    //   30: this.companyConfig.tfb
    // }
  }

  async test(pobj, query) {
    return system.getResultSuccess({
      hello: "ok"
    });
  }

  async setCompanyIds(qobj) {
    let config = await this.userconfSve.findById(qobj.userId);
    console.log("config", config);
    // var config = this.userConfig[qobj.userId];
    if (!config) {
      return;
    }
    qobj.ecompany_id = [];
    let ids = (config.signCompanyIds || "").split(",");
    for (let id of ids) {
      if (id) {
        qobj.ecompany_id.push(Number(id));
      }
    }
    console.log("qobj.ecompany_id", qobj.ecompany_id);
  }

  async setPayCompanyIds(qobj) {
    let config = await this.userconfSve.findById(qobj.userId);
    // var config = this.userConfig[qobj.userId];
    if (!config) {
      return;
    }
    qobj.busiIds = [];

    let arr = (config.payCompanyIds || "").split(",");
    for (let id of arr) {
      if (!id) {
        continue;
      }
      qobj.busiIds.push(id);
    }
  }

  //合同模板
  async etemplateList(qobj) {
    var params = qobj || {};
    await this.setCompanyIds(params);

    if (!params.ecompany_id || params.ecompany_id.length == 0) {
      return system.getResultSuccess({count: 0, rows: []})
    }
    try {
      var params = qobj || {};
      console.log("params", params);
      var rs = await this.restClient.execPost(params, this.url + "etemplateList");
      console.log("rs", rs);
      return JSON.parse(rs.stdout);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "接口异常");
    }
  }

  //已签合同
  async acontractList(qobj) {
    var params = qobj || {};
    await this.setCompanyIds(params);
    if (!params.ecompany_id || params.ecompany_id.length == 0) {
      return system.getResultSuccess({count: 0, rows: []})
    }
    try {
      var rs = await this.restClient.execPost(params, this.url + "acontractList");
      return JSON.parse(rs.stdout);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "接口异常");
    }
  }

  //已签协议合同
  async acontracttoMtchIdList(qobj) {
    var params = qobj || {};
    try {
      let response = await axios({
        method: "POST",
        url: this.url + "acontracttoMtchIdList",
        data: params
      })
      return response.data;
    } catch (e) {
      console.log(e);
      return system.getResult(null, "接口异常");
    }
  }

  //导出已签合同

  async allExport(queryobj,odj,req, res,) {
    var search = decodeURIComponent(odj.search)
    var params = JSON.parse(search);
    try {
      let response = await axios({
        method: "POST",
        url: this.url + "allExport",
        data: params
      })

      var csvobj = {
        fileName: "签约协议" + moment().format("YYYYMMDD") + ".csv",
        rows: response.data.rows,
        opts: {
          fields: ['id', 'ecompany.name', 'template.nameA', 'eaccount.userName', 'eaccount.mobile', 'eaccount.personsSign', 'eaccount.bankno', 'fileurl'],
          unwind: ['ecompany', 'eaccount'],
          unwindBlank: true,
          excelStrings: true,
        },
        headers: {'id': '编号', 'ecompany.name': "公司名", 'template.nameA' : '签约主体', 'eaccount.userName': "姓名", 'eaccount.mobile': "手机号", 'eaccount.personsSign': "身份证", "eaccount.bankno": "银行卡号", 'fileurl': "签约合同"},
      };


      return await this.excelClient.exportCsv(req,res, csvobj);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "接口异常");
    }
  }


  //纳税人人员
  async ratepayingListToPe(qobj) {
    var params = qobj || {};
    await this.setPayCompanyIds(params);
    if (!params.busiIds || params.busiIds.length == 0) {
      return system.getResultSuccess({count: 0, rows: []})
    }

    try {
      var rs = await this.restClient.execPost(params, this.url + "ratepayingListToPe");
      return JSON.parse(rs.stdout);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "接口异常");
    }
  }

  //纳税人按月
  async ratepayingListToMonth(qobj) {
    var params = qobj || {};
    await this.setPayCompanyIds(params);
    if (!params.busiIds || params.busiIds.length == 0) {
      return system.getResultSuccess({count: 0, rows: []})
    }
    try {
      var rs = await this.restClient.execPost(params, this.url + "ratepayingListToMonth");
      return JSON.parse(rs.stdout);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "接口异常");
    }
  }

  //纳税人个人详情
  async ratepayingListToOne(qobj) {

    var params = qobj || {};
    await this.setPayCompanyIds(params);
    if (!params.busiIds || params.busiIds.length == 0) {
      return system.getResultSuccess({count: 0, rows: []})
    }
    try {
      var rs = await this.restClient.execPost(params, this.url + "ratepayingListToOne");
      return JSON.parse(rs.stdout);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "接口异常");
    }
  }

  //数据概览
  async dataOverview(qobj) {
    var params = qobj || {};
    let config = await this.userconfSve.findById(qobj.userId);

    // var config = this.userConfig[qobj.userId];
    if (!config) {
      return system.getResultSuccess({});
    }
    qobj.busiIds = (config.payCompanyIds || "").split(",");
    // qobj.busiIds = config.payCompanyIds;
    let dataView;
    if(!config.dataView || config.dataView == "{}") {
      dataView = {actual_amt: 0, contractCount: 0, income_tax: 0};
    } else {
      try {
        dataView = JSON.parse(config.dataView);
      } catch (e) {
        dataView = {actual_amt: 0, contractCount: 0, income_tax: 0};
      }
    }

    try {
      var recruit_info = await this.recruitSve.findAllList(params);
      var dv = dataView || {actual_amt: 0, contractCount: 0, income_tax: 0};
      var rcount = 0;
      if (recruit_info.status == 0) {
        rcount = recruit_info.data.count;
      }
      dv.recruit_count = rcount;
      return system.getResultSuccess(dv);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "接口异常");
    }
  }

  async validSign(qobj) {
    let userlabour_id = Number(qobj.userlabour_id || 0);

    try {
      let userlabour = await this.userlabourSve.findById(userlabour_id);
      if (!userlabour) {
        return system.getResult(null, "应聘信息不存在");
      }

      if (!userlabour.ecid) {
        return system.getResult(null, "应聘信息未发起邀请");
      }

      let userInfo = await this.usersSve.findById(userlabour.labour_user_id);
      if(!userInfo) {
        return system.getResult(null, "用户信息不存在");
      }

      let id_card = userInfo.id_card || userlabour.id_no;
      if (!id_card) {
        return system.getResult(null, "用户未实名认证，身份证不存在");
      }

      let params = {
        // idNo: "222403198301071778",
        idNo: id_card,
        // ecid: 495,
        ecid: userlabour.ecid,
      };
      let rs = await this.restClient.execPost(params, this.url + "validLwbSign");
      try {
        rs = JSON.parse(rs.stdout);
        if (rs.data) {
          userlabour.apply_stauts = 60;
          userlabour.sign_at = new Date();
          userlabour.contract_url = rs.data;
          await userlabour.save();
          return system.getResultSuccess(true);
        }

        return system.getResultSuccess(false);
      } catch (e) {
        console.log(e);
        return system.getResult(null, "bpo接口错误");
      }
      return JSON.parse(rs.stdout);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "接口异常");
    }
  }

  async syncContractUrl() {
    let ids = await this.userlabourSve.findUnSyncIds();
    if (!ids || ids.length == 0) {
      return system.getResultSuccess("数据已经同步完成");
    }

    for (let id of ids) {
      this.contractUrl({userlabour_id: id});
    }
    return system.getResultSuccess("数据同步请求提交完成");
  }

  async contractUrl(qobj) {
    let userlabour_id = Number(qobj.userlabour_id || 0);

    try {
      let userlabour = await this.userlabourSve.findById(userlabour_id);
      if (!userlabour) {
        return system.getResult(null, "应聘信息不存在");
      }

      if (!userlabour.ecid) {
        return system.getResult(null, "应聘信息未发起邀请");
      }

      if (userlabour.contract_url) {
        return system.getResultSuccess(userlabour.contract_url);
      }

      let userInfo = await this.usersSve.findById(userlabour.labour_user_id);
      if(!userInfo) {
        return system.getResult(null, "用户信息不存在");
      }

      let id_card = userInfo.id_card || userlabour.id_no;
      if (!id_card) {
        return system.getResult(null, "用户未实名认证，身份证不存在");
      }

      let params = {
        // idNo: "222403198301071778",
        idNo: id_card,
        ecid: userlabour.ecid,
      };

      var rs = await this.restClient.execPost(params, this.url + "lwbContractUrl");
      try {
        rs = JSON.parse(rs.stdout);
        if (rs.status !== 0) {
          return rs;
        }

        if (rs.data) {
          userlabour.contract_url = rs.data;
          await userlabour.save();
        }
        return rs;
      } catch (e) {
        console.log(e);
        return system.getResult(null, "bpo接口错误");
      }

    } catch (e) {
      console.log(e);
      return system.getResult(null, "接口异常");
    }
  }

  exam() {
    return "xxx";
  }

  classDesc() {
    return {
      groupName: "auth",
      groupDesc: "认证相关的包",
      name: "AccessAuthAPI",
      desc: "关于认证的类",
      exam: "",
    };
  }

  methodDescs() {
    return [{
      methodDesc: "生成访问token",
      methodName: "getAccessKey",
      paramdescs: [{
        paramDesc: "访问appkey",
        paramName: "appkey",
        paramType: "string",
        defaultValue: "x",
      },
        {
          paramDesc: "访问secret",
          paramName: "secret",
          paramType: "string",
          defaultValue: null,
        }
      ],
      rtnTypeDesc: "xxxx",
      rtnType: "xxx"
    }];
  }

}

module.exports = XbgApi;

// var tesk = new XbgApi();
// var parm = {
//     ecompany_id:""
//  };
// tesk.dataOverview(parm).then(function(result){
//   console.log(result);
//   //console.log(result.data.rows);
// }).catch(function(e){
//   console.log(e);
// });
