const system = require("../../../system");
const ServiceBase = require("../../sve.base")

class EorderService extends ServiceBase {
  constructor() {
    super("eorder", ServiceBase.getDaoName(EorderService));
    this.eorderproductDao = system.getObject("db.eorder.eorderproductDao");
    this.eordersignlogDao = system.getObject("db.eorder.eordersignlogDao");
    this.eorderauthlogDao = system.getObject("db.eorder.eorderauthlogDao");
    this.GROUP_PRODUCT_TYPE = "2";
    this.SIGNLE_PRODUCT_TYPE = "1";
    this.AUDIT_STATUS=['10','20','30'];
    this.PAY_STATUS=['10','20','30'];
    this.PRODUCT_TYPE_ARRAY=['1','2'];
  }

  /**
   * fn:保存订单
   * @param params
   * @returns {Promise<void>}
   */
  async saveEorder(params){
    if(!params.merchant_id){
      return system.getResult(null, `参数错误 商户ID不能为空`);
    }
    if(!params.merchant_name){
      return system.getResult(null, `参数错误 商户名称不能为空`);
    }
    if((!params.product_ids || params.product_ids.length==0) && !params.product_id ){
      return system.getResult(null, `参数错误 产品ID列表不能为空`);
    }
    if(!params.product_id ){
      return system.getResult(null, `参数错误 父产品ID列表不能为空`);
    }
    if(!params.product_type || !this.PRODUCT_TYPE_ARRAY.includes(this.trim(params.product_type))){
      return system.getResult(null, `参数错误 未知的产品类型`);
    }
    if(params.product_type==this.SIGNLE_PRODUCT_TYPE && !params.product_unit_price){
      return system.getResult(null, `参数错误 商品单价不能为空`);
    }
    //如果是组合产品 单价为-1
    if(params.product_type==this.GROUP_PRODUCT_TYPE){
      params.product_unit_price=-1;
    }
    if(!params.contract_url){
      return system.getResult(null, `参数错误 业务合同不能为空`);
    }
    if(!params.live_start){
      return system.getResult(null, `参数错误 生效时间不能为空`);
    }
    if(!params.live_end){
      return system.getResult(null, `参数错误 结束时间不能为空`);
    }
    params.product_specifications = Number(params.product_specifications || 0);
    params.audit_status="10";
    params.live_status="10";
    params.pay_status="20";
    params.pay_date=new Date();
    console.log(`eorderSve->saveEorder->params` + JSON.stringify(params));
    try{
      if(params.id){//更新新操作
        let _orderBean = await this.dao.model.findOne({
          where:{
            id:this.trim(params.id)
          }
        });
        if(!_orderBean){
          return system.getResult(null, `订单【${params.id}】不存在`);
        }
        if(_orderBean.audit_status!='10'){
          return system.getResult(null, `订单【${_orderBean.id}】不能编辑`);
        }
        let _orderBeanProperties={id:_orderBean.id};
        _orderBeanProperties.merchant_id = params.merchant_id ? params.merchant_id : _orderBean.merchant_id;
        _orderBeanProperties.merchant_name = params.merchant_name ? params.merchant_name : _orderBean.merchant_name;
        _orderBeanProperties.sign_id = params.sign_id ? params.sign_id : _orderBean.sign_id;
        _orderBeanProperties.sign_name = params.sign_name ? params.sign_name : _orderBean.sign_name;
        _orderBeanProperties.product_id = params.product_id ? params.product_id : _orderBean.product_id;
        _orderBeanProperties.product_type = params.product_type ? params.product_type : _orderBean.product_type;
        _orderBeanProperties.product_unit_price = params.product_unit_price ? params.product_unit_price : _orderBean.product_unit_price;
        _orderBeanProperties.product_desc = params.product_desc ? params.product_desc : _orderBean.product_desc;
        // if(params.hasOwnProperty('price')){
        //   _orderBeanProperties.price = Number(params.price || _orderBean.price);
        // }
        if(params.hasOwnProperty('product_specifications')){
          _orderBeanProperties.product_specifications = Number(params.product_specifications || _orderBean.product_specifications);
        }

        _orderBeanProperties.contract_url = params.contract_url ? params.contract_url : _orderBean.contract_url;
        _orderBeanProperties.live_start = params.live_start ? params.live_start : _orderBean.live_start;
        _orderBeanProperties.live_end = params.live_end ? params.live_end : _orderBean.live_end;
        _orderBeanProperties.audit_status = params.audit_status ? params.audit_status : _orderBean.audit_status;
        _orderBeanProperties.audit_date = params.audit_date ? params.audit_date : _orderBean.audit_date;
        _orderBeanProperties.audit_remark = params.audit_remark ? params.audit_remark : _orderBean.audit_remark;
        _orderBeanProperties.audit_user_id = params.audit_user_id ? params.audit_user_id : _orderBean.audit_user_id;
        _orderBeanProperties.live_status = params.live_status ? params.live_status : _orderBean.live_status;
        _orderBeanProperties.pay_status = params.pay_status ? params.pay_status : _orderBean.pay_status;
        _orderBeanProperties.pay_date = params.pay_date ? params.pay_date : _orderBean.pay_date;
        _orderBeanProperties.engine_account_id = params.engine_account_id ? params.engine_account_id : _orderBean.engine_account_id;

        console.log(`eorderSve->saveEorder->_orderBeanProperties`+JSON.stringify(_orderBeanProperties));
        await  this.db.transaction(async t=>{
          await this.dao.update(_orderBeanProperties, t);
          //首先删除 eorderproduct 表中所用指定order_id的所有记录
          let deleteRows = await this.eorderproductDao.delete({order_id:_orderBean.id});
          if(deleteRows.length==0){
            throw new Error("更新订单失败");
            return system.getResult(null,`系统错误 更新订单商品失败`);
          }
          if(params.product_arr && params.product_arr.length>0){
            // 去重开始
            let productItemMap={};
            for (let item of params.product_arr) {
              productItemMap[item.id]=item
            }
            //去重结束
            let eorderProductProperties = [];
            for(let key in productItemMap){
              eorderProductProperties.push({
                order_id: _orderBean.id,
                product_id: productItemMap[key].id,
                product_name: productItemMap[key].product_name,
                price: productItemMap[key].price,
                product_property:productItemMap[key].product_property
              });
            }
            _orderBeanProperties.eorderProducts=eorderProductProperties;
            await this.eorderproductDao.bulkCreate(eorderProductProperties,t);
          }else{
            await this.eorderproductDao.create({order_id: _orderBean.id, product_id: this.trim(params.product_id),price:this.trim(params.product_unit_price)},t);
          }
        });
        return system.getResult(_orderBeanProperties);
      }else{  //新增操作
        let orderBean =null;
        await this.db.transaction(async t => {
          orderBean=await this.dao.create(params,t);
          if(params.product_arr && params.product_arr.length>0){
            // 去重开始
            let productItemMap={};
            for (let item of params.product_arr) {
              productItemMap[item.id] = item;
            }
            //去重结束
            let eorderProductProperties = [];
            for(let key in productItemMap){
              eorderProductProperties.push({
                order_id: orderBean.id,
                product_id: productItemMap[key].id,
                product_name: productItemMap[key].product_name,
                price: productItemMap[key].price,
                product_property:productItemMap[key].product_property
              });
            }
            await this.eorderproductDao.bulkCreate(eorderProductProperties,t);
          }else{
            await this.eorderproductDao.create({order_id: orderBean.id, product_id: this.trim(params.product_id),price:this.trim(params.product_unit_price)},t);
          }
        });
        this.handleDate(orderBean.dataValues, ['live_start', 'live_end', 'created_at'], null, null);
        return system.getResult(orderBean);
      }
    }catch (e) {
      console.log(e);
      return system.getResult(null,`系统错误`);
    }
  }

  /**
   * fn:审核订单
   * @param params
   * @returns {Promise<void>}
   */
  async auditEorder(params){
    if(!params.audit_status || !this.AUDIT_STATUS.includes(params.audit_status)){
      return system.getResult(null,`参数错误 审核状态错误`);
    }
    if(params.audit_status=="30" && !params.audit_remark){
      return system.getResult(null,`参数错误 审核备注不能为空`);
    }
    if(!params.id){
      return system.getResult(null,`参数错误 订单ID不能为空`);
    }
    let orderBean = await  this.dao.getById(this.trim(params.id));
    if(!orderBean){
      return system.getResult(null, `订单【${params.id}】不存在`);
    }
    // if(params.merchant_id && this.trim(params.merchant_id)!=orderBean.merchant_id){
    //   return system.getResult(null, `参数错误 订单【${params.id}】不存在`);
    // }
    if(orderBean.pay_status!='20'){
      return system.getResult(null, `订单【${params.id}】未支付`);
    }

    try{
      let orderProperties = {id:orderBean.id,audit_status:this.trim(params.audit_status),audit_remark:this.trim(params.audit_remark) || ""};
      orderProperties.live_status = params.audit_status == '20' ? params.audit_status : '30';
      await this.dao.update(orderProperties);
      return system.getResultSuccess();
    }catch (e) {
      console.log(e);
      return system.getResult(null, `系统错误`);
    }
  }

  /**
   * fn:更改订单状态
   * @param params
   * @returns {Promise<void>}
   */
  async updEorderStatus(params){
    if(!params.id){
      return system.getResult(null, `参数错误 订单ID 不能为空`);
    }
    try{
      let orderBean = await this.dao.model.findOne({id:this.trim(params.id)});
      if(!orderBean){
        return system.getResult(null, `订单【${params.id}】不存在`);
      }
      // if(params.merchant_id && this.trim(params.merchant_id)!=orderBean.merchant_id){
      //   return system.getResult(null, `参数错误 订单【${params.id}】不存在`);
      // }
      //如果支付状态
      if (params.pay_status && orderBean.pay_status == '10' && this.PAY_STATUS.includes(this.trim(params.pay_status))) {
        orderBean.pay_status = this.trim(params.pay_status);
        await orderBean.save();
        return system.getResult(orderBean);
      }
      //如果更新的是订单审核的状态
      if(params.audit_status && orderBean.pay_status=='20' && orderBean.audit_status=='10'){
        orderBean.live_status = params.audit_status == '20' ? '20' : '30';
        orderBean.audit_status = this.trim(params.audit_status);
        await orderBean.save();
        return system.getResult(orderBean);
      }
      //如果更新的是生效的状态
      if(params.live_status && orderBean.pay_status=='20' && orderBean.audit_status=='20' && orderBean=='10'){
        orderBean.live_status = this.trim(params.live_status);
        await orderBean.save();
        return system.getResult(orderBean);
      }
      return system.getResult(null, `更新失败`);
    }catch (e) {
      console.log(e);
      return system.getResult(null, `系统错误`);
    }
  }

  /**
   * fn:根据ID查询订单信息
   * @param params
   * @returns {Promise<void>}
   */
  async getEorderById(params){
    if(!params.id){
      return system.getResult(null,`参数错误 订单ID不能为空`);
    }
    let orderBean = await  this.dao.getById(this.trim(params.id));
    if(!orderBean){
      return system.getResult(null, `订单不存在`);
    }
    if(params.merchant_id && this.trim(params.merchant_id)!=orderBean.merchant_id){
      return system.getResult(null, `参数错误 订单【${params.id}】不存在`);
    }
    try{
      let productChildren = await  this.eorderproductDao.model.findAll({
        where:{
          order_id:orderBean.id
        },
        attributes:['product_id','product_name','price','order_id']
      });
      orderBean.product_arr = productChildren;

      this.handleDate(orderBean, ['created_at','pay_date','audit_date','live_start','live_end'], null, null);
      orderBean.product_type_name = orderBean.product_type == '1' ? '单产品' : '组合产品';
      orderBean.product_specifications_unit = orderBean.product_type == '1' ? '份' : '元';
      this.formatStatus(orderBean);
      //格式化认证日志
      let listEorderAuthLog =await this.eorderauthlogDao.model.findAll({
        where:{
          order_id:orderBean.id
        },
        order:[['spended_at','DESC']]
      });
      for (let itemOfauth of listEorderAuthLog) {
        this.handleDate(itemOfauth.dataValues, ['spended_at', 'created_at'],null,null,);
      }
      orderBean.eorderauthlog = listEorderAuthLog;

      //格式化签约日志
      let listEorderSignLog = await  this.eordersignlogDao.model.findAll({
        where:{
          order_id:orderBean.id
        },
        order:[['spended_at','DESC']]
      });
      for (let itemOfsign of listEorderSignLog) {
        this.handleDate(itemOfsign.dataValues, ['spended_at', 'created_at'],null,null,);
      }
      orderBean.eordersignlog = listEorderSignLog;
      return system.getResult(orderBean);
    }catch (e) {
      console.log(e);
      return system.getResult(null, `系统错误`);
    }
  }


  /**
   * fn:订单查询（分页）
   * @param params
   * @returns {Promise<void>}
   */
  async pageEorder(params){
    params.currentPage = Number(params.currentPage || 1);
    params.pageSize = Number(params.pageSize || 10);
    params.startRow = (params.currentPage - 1) * params.pageSize;
    try{
      let countRes = await this.dao.countEorder(params);
      if(countRes.eorderCount==0){
        return system.getResult({count: 0, row: []});
      }
      let list =await  this.dao.pageEorder(params);
      for (let item of list) {
        this.handleDate(item, ['created_at','pay_date','audit_date','live_start','live_end'], null, null);
        item.product_type_name = item.product_type == '1' ? '单产品' : '组合产品';
        item.product_specifications_unit = item.product_type == '1' ? `${item.product_unit_price}元/份` : '分开计价';
        this.formatStatus(item);
      }
      let orderIds = [];
      for(let ele of list){
        orderIds.push(ele.id);
      }
      let eorderProductList = await this.eorderproductDao.findAllByOrderId(orderIds);
      if(!eorderProductList || eorderProductList.length==0){
        return system.getResult(null, `系统错误 订单子产品不存在`);
      }
      let orderProductMap = {};
      for (let childPro of eorderProductList) {
        if(!orderProductMap[childPro.order_id]){
          orderProductMap[childPro.order_id] = [];
        }
        orderProductMap[childPro.order_id].push(childPro);
      }
      for(let element of list){
        element.eorderproduct = orderProductMap[element.id] || {};
      }
      return system.getResult({count: countRes.eorderCount, rows: list});
    }catch (e) {
      console.log(e);
      return system.getResult(null, `系统错误`);
    }
  }

  /**
   * fn:格式化订单状态
   * @param params
   */
  formatStatus(params){
    if(!params){return;}

    if(params.pay_status){
      if(params.pay_status=='10'){
        params.pay_status_name='待付款';
      }else if(params.pay_status=='20'){
        params.pay_status_name='已付款';
      }else if(params.pay_status=='30'){
        params.pay_status_name='付款失败';
      }else{
        params.pay_status_name='';
      }
    }

    if(params.audit_status){
      if(params.audit_status=='10'){
        params.audit_status_name='待审核';
      }else if(params.audit_status=='20'){
        params.audit_status_name='审核成功';
      }else if(params.audit_status=='30'){
        params.audit_status_name='审核失败';
      }else{
        params.audit_status_name='';
      }
    }

    if(params.live_status){
      if(params.live_status=='10'){
        params.live_status_name='待生效';
      }else if(params.live_status=='20'){
        params.live_status_name='已生效';
      }else if(params.live_status=='30'){
        params.live_status_name='已终止';
      }else{
        params.live_status_name='';
      }
    }
  }

  /**
   * fn：简单的单表更新
   * @param params
   * @returns {Promise<void>}
   */
  async updOrderSimple(params){
    if(!params.id){
      return system.getResult(null, `参数错误 订单ID 不能为空`);
    }
    let orderBean = await this.dao.model.findOne({
      where:{
        id: this.trim(params.id)
      }
    });
    if(!orderBean){
      return system.getResult(null, `订单【${params.id}】不存在`);
    }

    if(params.trade_id){
      orderBean.trade_id = this.trim(params.trade_id);
    }
    if(params.engine_account_id){
      orderBean.engine_account_id = this.trim(params.engine_account_id);
    }
    try{
      await orderBean.save();
      return system.getResultSuccess();
    }catch (e) {
      console.log(e);
      return system.getResult(null,`系统错误`);
    }
  }

  async getMerchantLiveProduct(params) {
    if (!params.merchant_id) {
      return system.getResultSuccess([]);
    }
    let res = await this.dao.getMerchantLiveProduct(params.merchant_id);
    return system.getResultSuccess(res);
  }

  /**
   * fn:查询商户下可用订单的产品(所有)
   * @param params
   * @returns {Promise<{msg: *, data, status: number}>}
   */
  async getMerchantLiveAllProducts(params) {
    if (!params.merchant_id) {
      return system.getResultSuccess([]);
    }
    try{
      let res = await this.dao.getMerchantLiveAllProducts(params.merchant_id);
      let map = {};
      for (let item of res) {
        map[item.product_id]=item || {};
      }
      let arr = [];
      for(let ele in map){
        arr.push(map[ele]);
      }
      return system.getResultSuccess(arr);
    }catch (e) {
      console.log(e);
      system.getResult(null, `系统错误`);
    }

  }


}
module.exports = EorderService;