const system = require("../../../system")
const settings = require("../../../../config/settings")
const CtlBase = require("../../ctlms.base");
const moment = require("moment");
class OrderCtl extends CtlBase {
  constructor() {
    super();
    this.orderSve = system.getObject("service.order.orderSve");
    this.deliverSve = system.getObject("service.common.deliverSve");

    this.businessmenSve = system.getObject("service.business.businessmenSve");
  }

  async processList(pobj, pobj2, req) {
    try {
      return this.orderSve.allProcess(pobj);
    } catch (e) {
      console.log(e);
      return system.getResultFail(500, "接口错误");
    }
  }

  async allOrders(pobj, pobj2, req) {
    var condition = {
      currentPage: Number(pobj.currentPage || 1),
      pageSize: Number(pobj.pageSize || 10),
      id: this.trim(pobj.id),
      status: pobj.status,
      createdBegin: this.trim(pobj.createdBegin),
      createdEnd: this.trim(pobj.createdEnd),
      deliver_id: pobj.deliver_id,
      order_id:this.trim(pobj.order_id)
    }

    this.doTimeCondition(condition, ["createdBegin", "createdEnd"]);
    try {
      return await this.orderSve.orders(condition);
    } catch (e) {
      console.log(e);
      return system.getResultFail(500, "接口错误");
    }
  }

  async myOrders(pobj, pobj2, req) {
    var condition = {
      currentPage: pobj.currentPage || 1,
      pageSize: pobj.pageSize || 10,
      id: this.trim(pobj.id),
      order_id: this.trim(pobj.order_id),
      operator_id: req.loginUser.id,
      deliver_id: this.trim(pobj.deliver_id),
      status: pobj.status,
      createdBegin: this.trim(pobj.createdBegin),
      createdEnd: this.trim(pobj.createdEnd),
    }
    this.doTimeCondition(condition, ["createdBegin", "createdEnd"]);
    try {
      return await this.orderSve.orders(condition);
    } catch (e) {
      console.log(e);
      return system.getResultFail(500, "接口错误");
    }
  }

    async orderInfo(pobj, pobj2, req) {
    try {
      return await this.orderSve.orderInfoAll({id: this.trim(pobj.id)});
    } catch (e) {
      console.log(e);
      return system.getResultFail(500, "接口错误");
    }
  }

  async orderChooseProducts(pobj, pobj2, req) {
    let orderId = this.trim(pobj.id);

    let order = await this.orderSve.orderInfo({id: orderId});
    if(!order.data || !order.data.product_id) {
      return system.getResult(null, "订单不存在");
    }
    let params = {
      pid: order.data.product_id,
      is_choose: 1,
    }
    try {
      return await this.orderSve.productDics(params);
    } catch (e) {
      console.log(e);
      return system.getResultFail(500, "接口错误");
    }
  }


  /**
   * 分配业务员
   * @param {*} pobj
   * @param {*} pobj2
   * @param {*} req
   */
  async deliverAssignSalesman(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 订单状态不能为空`);
    }
    if (!pobj.operator_id) {
      return system.getResult(null, `参数错误 业务员ID不能为空`);
    }
    let user = await this.deliverSve.deliverUserById({id: pobj.operator_id});
    if (!user || user.status != 0 || !user.data) {
      return system.getResult(null, `业务员【${pobj.operator_id}】不存在`);
    }
    pobj.operator_path = user.data.org_path;
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 分配业务员完成
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async deliverAssignSalesmanComplete(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 订单状态不能为空`);
    }
    
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

    /**
   * 工商注册中
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async businessRegister(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 订单状态不能为空`);
    }
    
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 工商注册完成
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async businessRegisterComplete(pobj, pobj2, req) {
    let deliver = await this.getDeliver(req);
    if (!deliver) {
      return system.getResult(null, `登录信息错误，请重新登录`);
    }

    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }

    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }

    if (!pobj.name) {
      return system.getResult(null, `参数错误 个体工商户名称不能为空`);
    }
    if (!pobj.credit_code) {
      return system.getResult(null, `参数错误 统一社会信用代码不能为空`);
    }
    if (!pobj.business_place) {
      return system.getResult(null, `参数错误 经营场所不能为空`);
    }
    if (!pobj.business_scope) {
      return system.getResult(null, `参数错误 经营范围不能为空`);
    }
    if (!pobj.reg_date) {
      return system.getResult(null, `参数错误 注册日期不能为空`);
    }
    if (!pobj.business_img) {
      return system.getResult(null, `参数错误 执照照片不能为空`);
    }
    // if (!pobj.business_gov_file) {
    //   return system.getResult(null, `参数错误 工商官方文件不能为空`);
    // }

    if(!pobj.deliver_id){
      return system.getResult(null,`请重新登录`);
    }
    pobj.deliver_id = pobj.deliver_id;
    pobj.company_id = deliver.nt_company_id;

    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }


  /**
   * 刻章办理中
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async chapterEngraving(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }
    
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 刻章办理已完成
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async chapterEngravedComplete(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }

    // if (!pobj.gongzhang) {
    //   return system.getResult(null, `参数错误 公章不能为空`);
    // }
    // if (!pobj.fapiaozhang) {
    //   return system.getResult(null, `参数错误 发票章不能为空`);
    // }
    // if (!pobj.caiwuzhang) {
    //   return system.getResult(null, `参数错误 财务章不能为空`);
    // }
    // if (!pobj.hetongzhang) {
    //   return system.getResult(null, `参数错误 合同章不能为空`);
    // }
    // if (!pobj.farenzhang) {
    //   return system.getResult(null, `参数错误 法人章不能为空`);
    // }
    // if (!pobj.zhang_gov_file) {
    //   return system.getResult(null, `参数错误 刻章官方文件不能为空`);
    // }
    
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 银行开户中
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async backAccountOpening(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }
    
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 银行已开户
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async backAccountOpenComplete(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }
    if (!pobj.bank_name) {
      return system.getResult(null, `参数错误 账户名称不能为空`);
    }
    if (!pobj.bank_no) {
      return system.getResult(null, `参数错误 账户号不能为空`);
    }
    if (!pobj.bank) {
      return system.getResult(null, `参数错误 开户行不能为空`);
    }
    // if (!pobj.bank_img) {
    //   return system.getResult(null, `参数错误 账户信息不能为空`);
    // }
    // if (!pobj.bank_gov_file) {
    //   return system.getResult(null, `参数错误 银行开户官方文件不能为空`);
    // }
    
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 税务报道中
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async taxReporting(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }
    
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

    /**
   * 税务报道完成
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async taxReportComplete(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }
    if (!pobj.tax_reg_day) {
      return system.getResult(null, `参数错误 税务登记日不能为空`);
    }
    if (!pobj.tax_org) {
      return system.getResult(null, `参数错误 税务机构名称不能为空`);
    }
    // if (!pobj.ca_img) {
    //   return system.getResult(null, `参数错误 CA照片不能为空`);
    // }
    // if (!pobj.tax_gov_file) {
    //   return system.getResult(null, `参数错误 税务报道官方文件不能为空`);
    // }
    
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 核定税种
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async taxCategoryDetermine(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }
    if (!pobj.common_tax_ladder) {
      return system.getResult(null, `参数错误 普票个税阶梯不能为空`);
    }
    if (!pobj.common_other_ladder) {
      return system.getResult(null, `参数错误 普票增值税、附加税阶梯不能为空`);
    }
    if (!pobj.special_tax_ladder) {
      return system.getResult(null, `参数错误 专票个税阶梯不能为空`);
    }
    if (!pobj.special_other_ladder) {
      return system.getResult(null, `参数错误 专票增值税、附加税阶梯不能为空`);
    }
    if (!pobj.add_value_up_type) {
      return system.getResult(null, `参数错误 增值税累计类型不能为空`);
    }
    if (!pobj.tax_up_type) {
      return system.getResult(null, `参数错误 个税累计类型不能为空`);
    }
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 交付商提交审核
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async submitAudit(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

    /**
   * 交付商订单交付
   * @param {*} pobj 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async mailed(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }
    if (!pobj.deliver_mail_no) {
      return system.getResult(null, `参数错误 交付商交付快递单号不能为空`);
    }
    if (!pobj.deliver_mail_img) {
      return system.getResult(null, `参数错误 交付商交付快递单号图片不能为空`);
    }
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async businessCompletion(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 状态码不能为空`);
    }
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async updateOBusinessmenProinvce(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    try {
      return await this.orderSve.updateOBusinessmenProinvce(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /***************************************************一下是阿里改版的接口*****************************************************************/


  /**
   *  新增订单
   * @returns {Promise<void>}
   * @params product_id 产品ID
   * @params source_id  来源ID
   * @params source_no  来源订单号
   * @params desc 订单信息
   * @params contact_mobile 联系电话
   * @params customer_name  客户名称
   *
   * deliver_id:""
   product_id:"10020000",
   product_items: ["10020200","10020300","10020400","10020500","10020600",10020700],
   customer_name: "",
   contact_mobile:"",
   */
  async addSourceOrder(pobj, pobj2, req) {
    if (!pobj.product_id) {
      return system.getResult(null, `参数错误 产品ID不能为空`);
    }
    if (!pobj.contact_mobile) {
      return system.getResult(null, `参数错误 联系电话不能为空`);
    }
    if (!pobj.customer_name) {
      return system.getResult(null, `参数错误 客户名称不能为空`);
    }
    if(!pobj.chooseItems){
      pobj.chooseItems =  ["10020200","10020300","10020400","10020500","10020600","10020700"];
    }
    if(!pobj.chooseItems.includes("10020200")){
      pobj.chooseItems.push("10020200");
    }
    pobj.service_items =  pobj.chooseItems;
    pobj.source_id = pobj.source_id || '1003';
    pobj.notes = pobj.desc || "工商注册，刻章，银行卡户，税务报到，建账";
    if(!pobj.deliverId){
      return system.getResult(null,`请重新登录`);
    }
    pobj.deliver_id = pobj.deliverId;
    pobj.deliver_name = pobj.deliverName || "";
    pobj.delier_user_id = pobj.delier_user_id || "";
    pobj.deliver_user_path = pobj.deliver_user_path || "";

    try {
      return await this.orderSve.addSourceOrder(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * ali完善订单
   * @param pobj
   * @param pobj2
   * @param req
   * @returns {Promise<void>}
   */
  async aliPerfectInformation(pobj, pobj2, req){
    if(!pobj.id){
      return system.getResult(null,`订单【${pobj.id}】不存在`)
    }
    if(!pobj.status){
      return system.getResult(null,`订单状态不能为空`)
    }
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * ali建账
   * @param pobj
   * @param pobj2
   * @param req
   * @returns {Promise<void>}
   */
  async accountCreation (pobj, pobj2, req){
    let deliver = await this.getDeliver(req);
    if (!deliver) {
      return system.getResult(null, `登录信息错误，请重新登录`);
    }

    if(!pobj.id){
      return system.getResult(null,`订单【${pobj.id}】不存在`)
    }
    if(!pobj.status){
      return system.getResult(null,`订单状态不能为空`)
    }
    if(!pobj.province){
      return system.getResult(null,`省份不能为空`)
    }
    try {
      let rs = await this.orderSve.handleStatus(pobj);
      if (rs && rs.status === 0) {
        this.createAccount(pobj, deliver, req.loginUser);
      }
      return rs;
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * @params 建仗
   */
  async createAccount(params, deliver, loginUser) {
    try {
      // 查个体户
      let businessmen = await this.businessmenSve.byOrderId({order_id: params.id});
      businessmen = businessmen.data;

      let companyId = businessmen.company_id || loginUser.deliver.nt_company_id;

      let user = await this.deliverSve.deliverUserInfo({id: deliver.admin_id}) || {};
      user = (user.data || {}).user || {};
      let data = {
        customerName: businessmen.name,
        initPeriod: Number(moment().format("YYYYMM")),
        // initPeriod:  moment().format("YYYYMM"),
        accountStandard: 1,
        valueAddedTax: 2,
        bankStatus: businessmen.is_bank ? 1 : 0,
        accountant: user.nt_user_id,
        province: businessmen.province,
        companyId: companyId,
      }
      let url = settings.ntapi().createCustomer;
      let res = await this.orderSve.callApi(url, data, "建账");
      console.log(res);
      if (!res || !res.data) {
        return system.getResult(null, "建账失败");
      }
      if (res.data) {
        await this.orderSve.callms("order", "createAccount", {
          id: businessmen.id,
          province: params.province,
          customer_id: res.data
        });
      }
      return system.getResultSuccess();
    } catch (error) {
      console.log(error.stack);
      return system.getResult(error);
    }
  }

  /**
   * ali客户交付
   * @param {*} params
   */
  async orderComplete(pobj, pobj2, req) {
    if (!pobj.id) {
      return system.getResult(null, `参数错误 订单ID不能为空`);
    }
    if (!pobj.status) {
      return system.getResult(null, `参数错误 订单状态不能为空`);
    }
    if (!pobj.guest_mail_no) {
      return system.getResult(null, `参数错误 客户快递单号不能为空`);
    }
    if (!pobj.guest_mail_img) {
      return system.getResult(null, `参数错误 交付商交付快递单号图片不能为空`);
    }
    try {
      return await this.orderSve.handleStatus(pobj);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 阿里 全部订单
   * @returns {Promise<void>}
   */
  async aliOrderPageAll(pobj, pobj2, req){
    let statusMap = {
      "1":"2010", //待完善
      "2":"2020",//工商注册g
      "3":"2030",//刻章办理
      "4":"2040",//银行开户
      "5":"2050",//税务报道
      "6":"2060",//核定税种
      "7":"2070",//建帐
      "8":"2080",//客户交付
      "9":"2090"//订单完成
    };
    var condition = {
      currentPage: Number(pobj.currentPage || 1),
      pageSize: Number(pobj.pageSize || 10),
      deliver_id: pobj.deliver_id,
    }
    if(pobj.createdBegin){
      condition.createdBegin = this.trim(pobj.createdBegin);
    }
    if(pobj.createdEnd){
      condition.createdEnd = this.trim(pobj.createdEnd);
    }
    if(pobj.status){
      condition.status = statusMap[pobj.status];
    }
    if(pobj.order_id){
      condition.id = this.trim(pobj.order_id);
    }
    this.doTimeCondition(condition, ["createdBegin", "createdEnd"]);
    return  await this.orderSve.aliOrderPageAll(condition);
  }

  /**
   * 阿里 我的业务订单
   * @returns {Promise<void>}
   */
  async aliOrderPage(pobj, pobj2, req){
    //1.2010~2090状态
    let statusMap = {
      "1":"2010", //待完善
      "2":"2020",//工商注册g
      "3":"2030",//刻章办理
      "4":"2040",//银行开户
      "5":"2050",//税务报道
      "6":"2060",//核定税种
      "7":"2070",//建帐
      "8":"2080",//客户交付
      "9":"2090"//订单完成
    };
    // if(!statusMap[pobj.status]){
    //   return system.getResult(null, `订单状态错误`);
    // }
    var condition = {
      currentPage: Number(pobj.currentPage || 1),
      pageSize: Number(pobj.pageSize || 10),
      deliver_id: pobj.deliver_id,
      status:statusMap[pobj.status],
      // status:pobj.status,
      isMain:pobj.isMain,
      isManager:pobj.isManager,
      deliver_user_id:pobj.deliver_user_id,
      deliver_user_path:pobj.deliver_user_path
    }
    if(pobj.createdBegin){
      condition.createdBegin = this.trim(pobj.createdBegin);
    }
    if(pobj.createdEnd){
      condition.createdEnd = this.trim(pobj.createdEnd);
    }
    if(pobj.order_id){
      condition.id = this.trim(pobj.order_id);
    }

    if(pobj.statusArray){
      let statusArray = [];
      for (let item of pobj.statusArray) {
        statusArray.push(statusMap[item]);
      }
      condition.statusArray = statusArray;
    }
    this.doTimeCondition(condition, ["createdBegin", "createdEnd"]);
    return await this.orderSve.aliOrderPage(condition);
  }
}
module.exports = OrderCtl;