<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\crm\lib;
use think\Controller;
use app\common\lib\redisQueue;
class RunHistoryData extends Controller {

    /**
     * 接收队列传值，判断处理类型
     */
    public function allotData($data){
        $success = 0;
        $false = 0;
        $hid = $data['hid'] ? $data['hid'] : 0;
        $eid = $data['eid'] ? $data['eid'] : 0;
        $this->log('[hid==>'.$data["hid"].'],[eid==>'.$data["eid"].']');
        // 单条
        if ($data['type'] == 1) {

            $this->log('[data_type==>'.$data["type"].']');
            $res = $this->disposeHistoryData($eid, $hid, $data['staff_id'],$data['identity'],$data['cinfo'],$data['old_data'],$data['new_data'],$data['controller'],$data['action'],$data['ip'],$data['create_time']);
            $this->log('[single==>'.$res.']');

            $resDel = db('c_history_data')->where('id',$hid)->delete();
            $this->log('[delStatus==>'.$res.']');

        }else if ($data['type'] == 2) { // 客资批量导入

            $this->log('[data_type==>'.$data["type"].']');
            // 根据eid获取所有批量导入的客资
            $customers = db('c_customerinfo')->where('eid', $data['eid'])->select();
            $this->log('---sql---:'.db()->getLastSql());
            foreach ($customers as $key => $value) {
                $this->log('--onecustomer--'.json_encode($value));
                $cinfo = [
                    'id'     => $value['id'],
                    'dj_id'  => $value['dj_staff_id'],
                    'dj_day' => $value['dj_day'],
                ];
                $oldData = [];
                $newData = $value;
                $res = $this->disposeHistoryData($eid, $hid, $data['staff_id'],$data['identity'],$cinfo,$oldData,$value,$data['controller'],$data['action'],$data['ip'],$data['create_time']);
                if ($res) {
                    $success++;
                }else{
                    $false++;
                }
            }
            if ($false==0) {
                db('c_history_data')->where('id',$hid)->delete();
                $this->log('[delStatusAll==>'.$res.']');
            }
            $this->log('[multi==>'.$res.']');
        }
        // action('Message/historyDataRedisList');
    }

    /**
     * 对历史数据的处理(记录与更改)
     * @param  str      staff_id    操作者ID          exp：6
     * @param  str      identity    操作身份           exp：录入record，筛客filter，销售sale 
     * @param  str      cinfo       customerinfo       exp：array(id,dj_id,dj_day,sel_id,sel_day,jr_id,jr_day)
     * @param  array    oldData     原始数据
     * @param  array    newData     新数据
     * @param  str      controller  控制器名
     * @param  str      action      方法名
     *
     * @return boolean
     * @author Eric
     */
    public function  disposeHistoryData($eid, $hid, $staff_id, $identity, $cinfo, $oldData, $newData, $controller, $action, $ip, $create_time){
        // 在客资编辑功能（customerInfo）
        if ($controller=='Customer' && ($action=='customerInfo' || $action=='customerSign')) {
            // $this->log('对比');
            foreach ($newData as $key => $value) {
                // 对比提交数据和原始数据
                if ($value != $oldData[$key]) {
                    // 将字段  对应成  中文
                    $kStr = translate('c_customerinfo',$key);
                    if ($kStr) {
                        // 记录日志  用
                        $oldDataL[$kStr]  = $oldData[$key];
                        $newDataL[$kStr]  = $value;
                    }
                    // 数据统计用
                    $old_data[$key] = $oldData[$key];
                    $new_data[$key] = $value;
                }
            }
        }else{
            // $this->log('不对比');
            // 记录日志  用
            $oldDataL = $oldData;
            $newDataL = $newData;
            // 数据统计  用
            $old_data = $oldData;
            $new_data = $newData;
        }
        
        $this->log('outforeach');
        $staffInfo = getStaffInfoById($staff_id);
        // $data,$oldData,$customerId ,$staffId ,$staffName ,$module ,$controller ,$action
        $module = 'crm';
        $oldDataSql = '';
        foreach($oldDataL as $k=>$v){
            $oldDataSql .= $k.":".$v.";<br />";
        }
        $newDataSql = '';
        foreach($newDataL as $k=>$v){
            $newDataSql .= $k.":".$v.";<br />";
        }
        // $this->log('进入action_log的odata==>>'.$oldDataSql);
        // $this->log('进入action_log的ndata==>>'.$newDataSql);
        // $this->log('---进入history_log:::module:'.$module.';controller:'.$controller.';action:'.$action.';ip:'.$ip.';create_time'.$create_time);
        history_log($newDataSql,$oldDataSql,$cinfo['id'],$staff_id,$staffInfo['staffname'],$module,$controller,$action, $ip, $create_time);
        // action_log($newDataL,$oldDataL,$cinfo['id'],$staff_id,$staffInfo['staffname'],$module,$controller,$action, $ip, $create_time);
        // $this->log('out_history_log');
        unset($staffInfo);
        // exit;
        // 字段 setInc+1/setDec-1
        /*
        'dj_customer'      '提报客资数',                         录入相关
        'dj_mobile'        '提报手机号数',                       录入相关
        'sel_customer'     '筛客 客资数量',                 筛客、
        'fp_customer'      '分配客资数',          销售相关、筛客、
        'fp_no_mobile'     '分配无手机号数',      销售相关、筛客、
        'add_mobile'       '新增手机号数',        销售相关、筛客、
        'valid_customer'   '有效客资数',          销售相关、筛客、录入相关
        'no_valid_customer''无效客资数',          销售相关、筛客、录入相关
        'yjd'              '预约进店数',          销售相关、筛客、录入相关
        'syjd_jk'          '实际进店数，进客',    销售相关、筛客、录入相关 erp提供
        'syjd_no_jk'       '实际进店数，非进客',  销售相关、筛客、录入相关 erp提供
        'order'            '成单数',              销售相关、筛客、录入相关 erp提供
        'valid_order'      '有效成单数',          销售相关、筛客、录入相关 erp提供
        'tel_visit'        '电访量'               销售相关、筛客、录入相关
        'a_customer'       'A客数',               销售相关、筛客、
        */
        
        // 如果存在登记人
        if ($cinfo['dj_id']) {
            $data[$cinfo['dj_id']] = date('Y-m-d H:i:s');
        }
        // 如果存在筛客人
        if ($cinfo['sel_id']) {
            $data[$cinfo['sel_id']]= date('Y-m-d H:i:s');
        }
        // 如果存在接收人
        if ($cinfo['jr_id']) {
            $data[$cinfo['jr_id']] = date('Y-m-d H:i:s');
        }
        // $this->log('[staffData==>'.json_encode($data).']');
        // // 如果cinfo为空怎么处理
        // $this->log('[new_data==>'.json_encode($new_data).']');
        // $this->log('[old_data==>'.json_encode($old_data).']');
        // exit;
        foreach ($new_data as $key => $value) {
            $this->log('[key==>'.$key.'],[value==>'.$value.'],[identity==>'.$identity.']');
            $this->log('[cid==>'.$cinfo["id"].'],[hid==>'.$hid.'],[eid==>'.$eid.']');
            // 存在客资 录入
            if ($key == 'customer_number' && $value && $identity == 'record') {
                $this->log('dj_customer');
                $res = controller('crm/Systemlist','lib')->dj_customer($data, $cinfo['id'], $hid, $eid);
                $this->log('dj_customer  STATUS:'.$res);
            }
            // 客资存在手机号 录入
            if ($key == 'customer_tel' && $value && $identity == 'record') {
                $this->log('dj_mobile');
                $res = controller('crm/Systemlist','lib')->dj_mobile($data, $cinfo['id'], $hid, $eid);
                $this->log('dj_mobile==>[[STATUS:'.$res.']]');
            }
            // 筛客数
            if ($key == 'is_sk' && $value == 1 && $identity == 'filter') {
                $this->log('is_sk');
                $res = controller('crm/Systemlist','lib')->sel_customer($data, $staff_id);
                $this->log('is_sk==>[[STATUS:'.$res.']]');
            }
            // 分配客资数
            if ($key == 'is_fp' && $value == 1 && $identity == 'sale') {
                // 人工重新分配，从  已分配  到  已分配
                if ($old_data['is_fp'] == 1) {
                    $this->log('is_fp from p to p');
                    $odata[$old_data['jr_id']]= $old_data['jr_day'];
                    // $ndata[$new_data['jr_id']]= $new_data['jr_day'];
                    $res = controller('crm/Systemlist','lib')->fp_customer_new($odata);
                    $this->log('is_fp from p to p ==>[[STATUS:'.$res.']]');
                }else{
                    $this->log('is_fp auto');
                    $res = controller('crm/Systemlist','lib')->fp_customer($data);
                    $this->log('is_fp auto ==>[[STATUS:'.$res.']]');
                }
            }
            // 手机号相关
            if ($key == 'customer_tel' && $identity == 'sale') {
                // 分配无手机号数
                if (!$old_data['customer_tel'] && !$value) {
                    $this->log('customer_tel no_tel');
                    $res = controller('crm/Systemlist','lib')->fp_no_mobile($data);
                    $this->log('customer_tel no_tel==>[[STATUS:'.$res.']]');
                }
                // 新增手机号数 客资存在手机号 编辑  // 无 ==> 有  +1
                else if (!$old_data['customer_tel'] && $value) {
                    $this->log('customer_tel add_tel from no to have');
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->add_mobile($data, $sta);
                    $this->log('customer_tel add_tel from no to have==>[[STATUS:'.$res.']]');
                } 
                // 有 ==> 无 -1
                else if ($old_data['customer_tel'] && !$value) {
                    $this->log('customer_tel add_tel from have to no');
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->add_mobile($data, $sta);
                    $this->log('customer_tel add_tel from have to no==>[[STATUS:'.$res.']]');
                }
            }
            // 有效 客资数  1有效；2：待定；3：无效
            if ($key == 'is_valid' && $value == 1 && $identity == 'sale') {
                // 从无状态（录入）到标记有效
                if ($old_data['is_valid'] == 2) {
                    $this->log('valid_customer  from no to have');
                    // 有效数+1
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->valid_customer($data, $sta);
                    $this->log('valid_customer  from no to have==>[[STATUS:'.$res.']]');
                }
                // 从 ‘无’ 效标记为 ‘有’ 效
                else if ($old_data['is_valid'] == 3) {
                    // 无效数-1   有效数+1
                    $this->log('valid_customer  from not to yes');
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->valid_customer($data, $sta);
                    $this->log('valid_customer  from not to yes==>[[STATUS:'.$res.']]');
                }
            }
            // 无效 客资数 1有效；2：待定；3：无效
            if ($key == 'is_valid' && $value == 3 && $identity == 'sale') {
                // 从无状态（录入）到标记无效
                if ($old_data['is_valid'] == 2) {
                    $this->log('no_valid_customer  from no to have');
                    // 无效数+1 
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->no_valid_customer($data, $sta);
                    $this->log('no_valid_customer  from no to have==>[[STATUS:'.$res.']]');
                }
                // 从 ‘有’ 效标记为 ‘无’ 效
                else if ($old_data['is_valid'] == 1) {
                    $this->log('no_valid_customer  from not to yes');
                    // 有效数 -1   无效数+1
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->no_valid_customer($data, $sta);
                    $this->log('no_valid_customer  from not to yes==>[[STATUS:'.$res.']]');
                }
            }
            // 预约进店数  yjd
            if ($key == 'yjd_day' && $identity == 'sale') {
                // 预约 +1
                if (!$old_data['yjd_day'] && $value) {
                    $this->log('yjd  from no to have');
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->yjd($data, $sta);
                    $this->log('yjd  from no to have==>[[STATUS:'.$res.']]');
                }
                // 取消预约 -1
                if ($old_data['yjd_day'] && !$value) {
                    $this->log('yjd  from have to no');
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->yjd($data, $sta);
                    $this->log('yjd  from have to no==>[[STATUS:'.$res.']]');
                }
            }
            // 实际进店数
            if ($key == 'is_intostore' && $value && $identity == 'sale') {
                // 未进店
                if ($value == 1) {
                    // 由进店进客  转为  未进店
                    if ($old_data['is_intostore'] == 2) {
                        $this->log('syjd_jk  from jk to out');
                        $sta = 'dec';
                        $res = controller('crm/Systemlist','lib')->syjd_jk($data, $sta);
                        $this->log('客资进店进客-1--数据统计，保存失败状态:'.($res?'成功':'失败' ));
                    }
                    // 由进店非进客  转为  未进店
                    if ($old_data['is_intostore'] == 3) {
                        $this->log('syjd_jk  from no_jk to out');
                        $sta = 'dec';
                        $res = controller('crm/Systemlist','lib')->syjd_jk($data, $sta);
                        $this->log('客资进店非进客-1--数据统计，保存失败状态:'.($res?'成功':'失败' ));
                    }
                }
                // 进店进客  syjd_jk
                if ($value == 2) {
                    // 由未进店  转为  进店进客
                    if ($old_data['is_intostore'] == 1) {
                        $sta = 'inc';
                        $res = controller('crm/Systemlist','lib')->syjd_jk($data, $sta);
                        $this->log('is_intostore:'.($res?'success':'false'));
                    }
                    // 由进店非进客  转为  进店进客
                    if ($old_data['is_intostore'] == 3) {
                        $sta = 'no';
                        $res = controller('crm/Systemlist','lib')->syjd_jk($data, $sta);
                        $this->log('客资进店进客+1，进店非进客-1--数据统计，保存失败状态:'.($res?'成功':'失败' ));
                    }
                }
                // 进店非进客  syjd_no_jk
                if ($value == 3) {
                    // 由未进店  转为  进店非进客
                    if ($old_data['is_intostore'] == 1) {
                        $sta = 'inc';
                        $res = controller('crm/Systemlist','lib')->syjd_no_jk($data, $sta);
                        $this->log('客资进店非进客+1--数据统计，保存失败状态:'.($res?'成功':'失败' ));
                    }
                    // 由进店进客  转为  进店非进客
                    if ($old_data['is_intostore'] == 2) {
                        $sta = 'no';
                        $res = controller('crm/Systemlist','lib')->syjd_no_jk($data, $sta);
                        $this->log('客资进店进客-1，进店非进客+1--数据统计，保存失败状态:'.($res?'成功':'失败' ));
                    }
                }
            }
            // 成单数  orders
            if ($key == 'order_status' && $value && $identity == 'sale') {
                // 成单
                if ($old_data['order_status'] !=1 && $value == 1) {
                    $this->log('order    +1');
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->orders($data, $sta);
                    $this->log('order    +1==>[[STATUS:'.$res.']]');
                }
                // 由成单 ==> 未成单
                else if ($old_data['order_status'] ==1 && $value == 2) {
                    $this->log('order    -1');
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->orders($data, $sta);
                    $this->log('order    -1==>[[STATUS:'.$res.']]');
                }
            }
            // 有效成单数valid_order
            if ($key == 'order_valid' && $value && $identity == 'sale') {
                // 有效
                if ($old_data['order_valid'] != 2 && $value == 2) {
                    $this->log('order_valid   +1');
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->valid_order($data, $sta);
                    $this->log('order_valid   +1==>[[STATUS:'.$res.']]');
                }
                // 由 有效 ==> 未 无效
                else if ($old_data['order_valid'] == 2 && $value == 1) {
                    $this->log('order_valid   -1');
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->valid_order($data, $sta);
                    $this->log('order_valid   -1==>[[STATUS:'.$res.']]');
                }
            }
            // A客数  a_customer
            if ($key == 'sign_name' && $value && $identity == 'sale') {
                if( ($old_data['sign_name']!='a'||$old_data['sign_name'] !='A')&&($value=='a'||$value=='A') ){
                    $this->log('sign_name a+1');
                    $sta = 'inc';
                    $res = controller('crm/Systemlist','lib')->a_customer($data, $sta);
                    $this->log('sign_name a+1==>[[STATUS:'.$res.']]');
                }
                if( ($old_data['sign_name']=='a'||$old_data['sign_name']=='A')&&($value!='a'||$value!='A') ){
                    $this->log('sign_name a-1');
                    $sta = 'dec';
                    $res = controller('crm/Systemlist','lib')->a_customer($data, $sta);
                    $this->log('sign_name a-1==>[[STATUS:'.$res.']]');
                }
            }
            // 电访量
            if ($key == 'tel_num' && $value && $identity == 'sale') {
                $this->log('tel_num');
                // $sta = 'inc';
                $res = controller('crm/Systemlist','lib')->tel_num($data);
                $this->log('tel_num==>[[STATUS:'.$res.']]');
            }
        }
        // exit;
        return $res;
    }


    function log($str){
        if(config('app_debug')){
            echo date('Y-m-d H:i:s').$str."\r\n";
        }
    }

}  
