<?php
/**
 * CRM   订单相关lib
 * 所有业务的真正实现全在lib目录下建controller并且访问modle等，供controller层调用
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: Lilong<Lilong@suxuantech.cn> 2019-10-28 $
 */
namespace app\crm\lib;
use think\Cache;
use think\Controller;
use PHPExcel_IOFactory;
use Excel5;
use PHPExcel;
use app\common\lib\redisQueue;
use think\Exception;

class Order extends Controller{
    protected $errid = 0;
    protected $errmsg = '';

    /**
     * 根据订单号作废订单
     *
     * @param  orderids   需要作废的单号
     * @param  zfTimes    作废时间，默认当前时间
     * @param  zfReason   作废原因，默认 ‘CRM作废该订单’
     * @param  staff_name 操作人
     * @param  staff_id   
     *
     * @return  boolean    
     * @author lilong<lilong@suxuantech.cn>
     */
    public function zfOrder($param){
        if(empty($param['orderids'])){
            return array('code' => 200, 'msg'=>'');
        }
        db()->startTrans();
        db('','db_logs')->startTrans();
        try {
            // 更新订单表
            $zfUpdate['blankoutannal'] = 1;
            $zfUpdate['blankoutannalremark'] = $param['zfReason'] ? $param['zfReason'] : 'CRM作废该订单';
            $zfUpdate['blankoutannalday'] = $param['zfTimes'] ? date('Ymd',strtotime($param['zfTimes'])) : date('Ymd');

            if(customize('xmfc6j1',ini('service.mcProductId'))){
                $now = date('Y-m-d H:i:s');
                //六加一作废时，如果客资初始是无效的，则需要还原成无效状态
                //日志：zuofeiunvalid
                $allCustomer = db('c_customerorder o')
                        ->field('c.id,c.customer_number,c.c_unique,c.valid_new,c.is_valid,c.yx_day')
                        ->join('crm_c_customerinfo c','c.customer_number = o.crm_customer_number','left')
                         ->where('o.orderId','in',$param['orderids'])
                         ->where('o.blankoutannal',0)
                         ->where('o.crm_customer_number is not null')
                         ->select();
                $cid = [];
                $crmlog = [];
                foreach ($allCustomer as $customer) {
                    if($customer['valid_new'] == 0 && ($customer['is_valid'] == 1 || $customer['is_valid'] == 5)){
                        $cid[] = $customer['id'];
                        $crmlog[] = [
                            'module'=>'crm',
                            'controller'=>'order',
                            'action'=>'zuofeiunvalid',
                            'old_data'=>json_encode(
                                [
                                    'is_valid'=>$customer['is_valid'],
                                    'yx_day'=>$customer['yx_day']
                                ]
                            ),
                            'data'=>json_encode(
                                [
                                    'is_valid'=>3,
                                    'yx_day'=>$now
                                ]
                            ),
                            'customer_id'=>$customer['id'],
                            'create_time'=>$now,
                            'staff_name'=>'system',
                        ];
                    }
                }
                if(!empty($cid)){
                    $res = db('crm_c_customerinfo')->where('id','in',$cid)->update(['is_valid'=>3,'yx_day'=>$now]);
                    db('crm_action_log','db_logs')->insertAll($crmlog);
                }   
            }
            $res = db('c_customerorder')
                ->where('orderId','in',$param['orderids'])
                ->where('blankoutannal',0)
                ->update($zfUpdate);
            $erpLog = [];
            foreach ($param['orderids'] as $key => $value) {
                $temp['module'] = 'erp';
                $temp['controller'] = '客户资料';
                $temp['action'] = 'update';
                $temp['old_data'] = 'CRM操作--订单编号：'.$value.'本单作废成功！';
                $temp['customer_id'] = $value;
                $temp['staff_name'] = $param['staff_name'] ? $param['staff_name'] : '系统';
                $temp['staff_id'] = $param['staff_id'] ? $param['staff_id'] : '0';
                $temp['ip'] = $param['ip']?$param['ip']:get_client_ip();
                $temp['create_time'] = date('Y-m-d H:i:s');
                array_push($erpLog, $temp);
            }
            textlog('作废0元无拍摄订单：'.implode(',', $param['orderids']),SX_LOG_LEVEL_WARING,'autozuofei');
            db('action_log','db_logs')->insertAll($erpLog);
            db('','db_logs')->commit();
            db()->commit();
            return array('code' => 200, 'msg'=>'');
        } catch (\Exception $e) {
            db()->rollback();
            db('','db_logs')->rollback();
            textlog('作废订单失败：'.$e->getMessage().'==>'.db()->getLastSql().'==>logSql:'.db('','db_logs')->getLastSql(),SX_LOG_LEVEL_WARING,'autozuofei');
            return array('code' => 100, 'msg'=>'', 'error'=>$e->getMessage());
        }
        
    }

}

