const system=require("../../system");
const ServiceBase=require("../sve.base")
const settings=require("../../../config/settings")
class InvoiceApplyService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(InvoiceApplyService));
     this.orderDao=system.getObject("db.orderDao");
     this.useraddrDao=system.getObject("db.useraddrDao");
    }
  async submitInvoice(obj){
    var order_id = obj.order_id;
    if(!order_id){
      return {code:-101,msg:"order_id参数错误"};
    }
    var order=await this.orderDao.model.findOne({
      where:{id:order_id},
      raw:true
    });
    if(!order || !order.id){
      return {code:-102,msg:"未知订单"};
    }
    if(!order.isIinvoice){
      return {code:-103,msg:"操作失败，该订单不需要发票"};
    }
    if(order.invoiceApplyStatus!="1"){
      return {code:-104,msg:"操作失败，该订单状态为"+order.invoiceApplyStatusName};
    }
    console.log(obj);
    var invoiceObj = obj;
    var that = this;
    return this.db.transaction(async function (t) {
      console.log(order);
      var invoiceInfo=await that.dao.model.create(invoiceObj,t);
      await that.orderDao.update({id:order.id,invoiceApplyStatus:"2",invoiceapply_id:invoiceInfo.id},t);
      if(invoiceInfo.invoiceType=="3"){
        var addressInfo=await that.useraddrDao.findOne({createuser_id:invoiceInfo.createuser_id,name:invoiceInfo.recipients,mobile:invoiceInfo.mobile,address:invoiceInfo.address});
        if(!addressInfo){
          var obj={
            name:invoiceInfo.recipients,
            mobile:invoiceInfo.mobile,
            address:invoiceInfo.address,
            company_id:invoiceInfo.company_id
          };
          await that.useraddrDao.create(obj,t);
        }
      }
      return {code:1,data:invoiceInfo};
    })
  }
  async aftercreate(result ,tm){
    console.log("----------aftercreate--------------");
    console.log(result);
    var orderInfo=await this.orderDao.findOne({id:result.order_id});
    var p=orderInfo.get({raw:true});
    await this.orderDao.update({id:p.id,invoiceApplyStatus:"2"},tm);
    if(result.invoiceType=="3"){
      var addressInfo=await this.useraddrDao.findOne({user_id:result.createuser_id,name:result.recipients,mobile:result.mobile,address:result.address});
      if(!addressInfo){
        var obj={
          name:result.recipients,
          mobile:result.mobile,
          address:result.address,
          company_id:result.company_id
        };
        await this.useraddrDao.create(obj,tm);
      }
    }
  }

  /**
    * 查询订单发票
    * @param invoiceApplyStatus 发票状态:"1": "未申请", "2": "已申请"
    * @param inputValue 输入框输入值 订单号/申请人名称
    */
  async findAllOrderInvoice(obj){
    var user = obj.user;
    if(!user){
      return {code:-100,msg:"用户数据错误"};
    }
    var sql = "select customerinfo.customerType, biz_order.id as order_id, biz_order.code as orderNum, biz_order.sveItemName, biz_order.name as order_name,"+
    "biz_order.invoiceApplyStatus,biz_order.invoiceApplyStatusName,customerinfo.code as customerinfo_code,customerinfo.identityCardNo,"+
    " biz_order.contacts, biz_order.mobile, biz_order.totalSum,customerinfo.id as customerinfo_id,customerinfo.name as customerinfo_name,"+
    " moneyjourney.id as moneyjourney_id,moneyjourney.accountTypeName,moneyjourney.created_at as moneyjourney_created_at from "+
    "(SELECT id, code, sveItemName, name, contacts, mobile, customerinfo_id, totalSum,"+
    "	invoiceApplyStatus, invoiceApplyStatusName, orderFlowStatus "+
    "FROM `biz_order` WHERE isIinvoice = TRUE AND ( orderPayStatus = 'yfk' OR orderPayStatus = 'zfpz' ) "+
    " AND orderFlowStatus IS NOT NULL AND orderFlowStatus > 1 and deleted_at is null ";
    sql = sql +" and company_id="+user.company_id;
    if(user.mobile ){
      sql = sql +" and (createuser_id="+user.id+" or mobile='"+user.mobile+"')";
    }else{
      sql = sql +" and createuser_id="+user.id ;
    }
    if(obj.invoiceApplyStatus){
      sql = sql +" and invoiceApplyStatus='"+obj.invoiceApplyStatus+"'";
    }
    sql = sql +" ) as biz_order "+
    " LEFT JOIN (select id,name,customerType,code,identityCardNo from biz_customerinfo ) as customerinfo on biz_order.customerinfo_id = customerinfo.id "+
    " LEFT JOIN (select id,sourceOrderNo,accountTypeName,created_at from biz_moneyjourney GROUP BY sourceOrderNo ) as moneyjourney on biz_order.code = moneyjourney.sourceOrderNo ";
    if(obj.inputValue){
      sql = sql +" where biz_order.code='"+obj.inputValue+"' or customerinfo.name like '%"+obj.inputValue+"%' ";
    }
    sql = sql+" order by biz_order.id desc";
    console.log(sql);
    var tmpResult = await this.dao.customQuery(sql);
    return {code:1,data:tmpResult};
  }
  /**
   * 订单发票提交申请
   * @param 
   * {invoiceType:"发票类型：1电子普通发票,2纸质普通发票,3纸质专用发票",
      invoiceContent:"发票内容",
      recipients: "收件人",
      mobile: "收票人手机号",
      email:"收票人邮箱",
      address:"邮寄地址",
      invoiceList:[//发票信息
        {
          invoiceHeadUpType:"发票抬头类型，person个人，ent公司",
          invoiceHeadUp:"发票抬头",
          taxpayerID:"纳税人识别号",
          orderCount:"订单数量",
          orderSum:"订单金额",
          orderCodes:[],//订单号数组
          applyAddr:"",//公司注册地址
          applytelephone: "",//公司备案电话
          bankName: "",//开户行名称
          bankNum:"",//开户行账号
          taxesCertifyUrl:"",//纳税资格证明文件地址
        }
      ]
    }
   */
  async orderInvoiceSubmit(obj){
    var user = obj.user;
    if(!user){
      return {code:-100,msg:"用户数据错误"};
    }
    if(!obj.invoiceType){
      return {code:-106,msg:"invoiceType参数错误"};
    }
    if(!obj.invoiceContent){
      return {code:-107,msg:"invoiceContent参数错误"};
    }
    if(obj.invoiceType=="1" && !obj.email){
      return {code:-108,msg:"email参数错误"};
    }
    if(obj.invoiceType=="2" || obj.invoiceType=="3" ){
      if(!obj.recipients){
        return {code:-109,msg:"recipients参数错误"};
      }
      if(!obj.mobile){
        return {code:-110,msg:"mobile参数错误"};
      }
      if(!obj.address){
        return {code:-111,msg:"address参数错误"};
      }
    }
    var invoiceList = obj.invoiceList;
    var codes=[];
    if(!invoiceList || invoiceList.length<1){
      return {code:-101,msg:"invoiceList参数错误"};
    }else{
      for(var i=0;i<invoiceList.length;i++){
        var inv = invoiceList[i];
        if(obj.invoiceType=="2" || obj.invoiceType=="3" ){
          // applyAddr:"",//公司注册地址
          // applytelephone: "",//公司备案电话
          // bankName: "",//开户行名称
          // bankNum:"",//开户行账号
          // taxesCertifyUrl:"",//纳税资格证明文件地址
          if(!inv.applyAddr){
            return {code:-120,msg:"applyAddr参数错误"};
          }
          if(!inv.applytelephone){
            return {code:-121,msg:"applytelephone参数错误"};
          }
          if(!inv.bankName){
            return {code:-122,msg:"bankName参数错误"};
          }
          if(!inv.taxesCertifyUrl){
            return {code:-123,msg:"taxesCertifyUrl参数错误"};
          }
        }
        if(!inv.invoiceHeadUpType){
          return {code:-102,msg:"invoiceHeadUpType参数错误"};
        }
        if(!inv.invoiceHeadUp){
          return {code:-103,msg:"invoiceHeadUp不能为空"};
        }
        if(!inv.taxpayerID){
          return {code:-104,msg:"taxpayerID不能为空"};
        }
        if(!inv.orderCodes || inv.orderCodes.length<1){
          return {code:-105,msg:"orderCodes参数错误"};
        }
        codes = codes.concat(inv.orderCodes);
        var orderSum =0;
        var orderCount = 0;
        for(var j=0;j<inv.orderCodes.length;j++){
          var code  = inv.orderCodes[j];
          var o = await this.orderDao.model.findOne({where:{code:code},raw:true});
          if(o){
            orderSum = orderSum + Number(o.totalSum);
            orderCount = orderCount +1;
            if(user.mobile){
              if(o.createuser_id!=user.id && o.mobile!=user.mobile){
                return {code:-113,msg:"只能开具自己订单的发票"};
              }
            }else{
              if(o.createuser_id!=user.id ){
                return {code:-114,msg:"只能开具自己订单的发票"};
              }
            }
            if(!o.isIinvoice){
              return {code:-115,msg:"操作失败，订单号为"+o.code+"的订单不需要开具发票"};
            }
            if(o.invoiceApplyStatus!="1"){
              return {code:-116,msg:"操作失败，订单号为"+o.code+"的订单已申请发票"};
            }
          }
        }
        if(inv.orderSum && inv.orderSum!=orderSum){
          return {code:-117,msg:"发票金额与订单不符"};
        }
        if(inv.orderCount && inv.orderSum!=orderSum){
          return {code:-118,msg:"订单数量错误"};
        }
      }
      console.log(codes);
    }
    var that=this;
    return this.db.transaction(async function (t) {
      for(var i=0;i<invoiceList.length;i++){
        var invoiceObj = invoiceList[i];
        invoiceObj["invoiceType"]=obj.invoiceType;
        invoiceObj["invoiceContent"]=obj.invoiceContent || "";
        invoiceObj["recipients"]=obj.recipients || "";
        invoiceObj["mobile"]=obj.mobile || "";
        invoiceObj["email"]=obj.email || "";
        invoiceObj["address"]=obj.address || "";
        invoiceObj["company_id"] = user.company_id;
        invoiceObj["createuser_id"] = user.id;
        var invoice = await that.dao.create(invoiceObj,t);
        await that.orderDao.model.update({invoiceapply_id:invoice.id,invoiceApplyStatus:"2"},{
          where:{code:{[that.db.Op.in]:invoiceObj.orderCodes}},
          transaction:t
        });
      }
      return {code:1};
    }) 

  }
}
module.exports=InvoiceApplyService;
// var task = new InvoiceApplyService();
// // var a = new Date().getTime();
// var obj={
//   invoiceApplyStatus:"3",
//   inputValue:""
// }
// task.findAllOrderInvoice(obj).then(d=>{
//   console.log("dddddddddddddddddddddddddd");
//   console.log(d);
// })
// var obj={invoiceType:"1",
// invoiceContent:"测试申请发票",
// recipients: "测试收件人",
// mobile: "13075556693",
// email:"2577638904@qq.com",
// address:"北京市朝阳区朝来高科技产业园10号楼",
// invoiceList:[//发票信息
//   {
//     invoiceHeadUpType:"ent",
//     invoiceHeadUp:"测试发票抬头",
//     taxpayerID:"1111111111111111111112",
//     orderCount:"1",
//     orderSum:"810",
//     orderCodes:["TMO201908071429o9lxV"],//订单号数组

//   }
// ]
// };

// task.orderInvoiceSubmit(obj).then(d=>{
//   console.log("dddddddddddddddddddddddddd");
//   console.log(d);
//   console.log(new Date().getTime()-a);
// })