<?php
/**
 * CRM 基本模块
 * 默认接口方法，此方法内定议基础框架所需要的方法，用于验证模块合法性，模块版本，对接基础架构中需要的方法
 * 
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 * 
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\crm\controller;
use think\Controller;

class Repair extends controller {
    protected $count = 0;

    public function pwd(){
        var_dump(think_decrypt('MDAwMDAwMDAwMJp_0GR-znzbhorMng-znzbhorMng'));
    }

    public function test(){
        $count = $this->count;
        echo $count.'<br/>';
        $this->count++;
        echo $this->count.'<br />';

    }

    // 根据追踪店面，group by 追踪人 将电商的花费平均到每个追踪人上
    public function channelCostByStaff(){
        set_time_limit(0);
        // 当前日期 （几号）
        $day   = date('d');
        $today = date('Y-m-d');
        // 查最近两个月的客资的 add_shop_code （accounting_channel_cost_LSDS01）
        $shop_codes = db('c_customerinfo')
            ->where('c_from', 1)->whereTime('dj_day','-60 days')
            ->group('add_shop_code')
            ->field('add_shop_code')
            ->select();
        $this->log(' -- 客资录入店列表'.json_encode($shop_codes));

        // 部门数据
        $departments = controller('crm/Customer', 'lib')->getDepartment();
        foreach ($shop_codes as $key => $value) {
            if (!$value['add_shop_code']) {
                continue;
            }
            $this->log(' -- 客资录入店'.$value['add_shop_code']);
            // 获取花费核算日期
            $accDay = db_config('accounting_channel_cost_'.$value['add_shop_code']);
            $this->log(' -- 核算日期：'.$accDay);
            
            // 如果存在
            if ($accDay) {
                // 如果核算日期 小于 当前日期  只统计当月 渠道花费 平均给渠道的每一个客资
                if ($accDay<$day) {
                    // $this->log(' -- <');
                    $start= date('Y-m-01');
                    $end  = $today;
                }
                // 如果核算日期 大于等于 当前日期  只统计当月 及上月 渠道花费 平均给渠道的每一个客资
                else{
                    // $this->log(' -- >=');
                    $start= date('Y-m-01', strtotime('-1 month'));
                    $end  = $today;
                }
                // $this->log(' -- 开始：'.$start.'；结束：'.$end);
                $channelCost= db('s_channel_cost')->where('cost','>','0')->where('shop_code',$value['add_shop_code'])->where('cost_date', 'between', [$start, $end])->order('channel_id,belong_shop_code')->field('channel_id,channel_name,belong_shop_code,belong_shop_name,cost,cost_date')->select();
                // $this->log(' -- SQL：'.db()->getLastSql());
                // $i = 0;
                foreach ($channelCost as $k => $v) {
                    // var_dump($v);
                    // exit;
                    $where['customer_channel_id'] = $v['channel_id'];
                    $where['customer_channel'] = $v['channel_name'];
                    $where['shop_code'] = $v['belong_shop_code'];
                    $where['is_status'] = 1;
                    $where['c_from']    = 1;
                    $cStart= date('Y-m-d 00:00:00', strtotime($v['cost_date']));
                    $cEnd  = date('Y-m-d 23:59:59', strtotime($v['cost_date']));
                    $cInfos= db('c_customerinfo')
                        ->where($where)->where('dj_day','between',[$cStart, $cEnd])
                        ->field('count(id) as num,sales_staff,sales_staff_id,sales_department_id')
                        ->group('sales_staff')
                        ->select();
                    // $this->log(' -- customerInfo-->SQL：'.db()->getLastSql());
                    $c_all_num = 0;
                    foreach ($cInfos as $k1 => $v1) {
                        $c_all_num +=  $v1['num'];
                    }
                    // $this->log('--ave--：'.$ave);
                    $ave = $v['cost']/$c_all_num;
                    $inData = [];
                    foreach ($cInfos as $k2 => $v2) {
                        $isId = db('c_staff_channel_cost')
                            ->where('staff_id',$v2['sales_staff_id'])
                            ->where('channel_id',$v['channel_id'])
                            ->where('day',$v['cost_date'])
                            ->delete();
                        $costData['c_num']    = $v2['num'];
                        $costData['c_all_num']= $c_all_num;
                        $costData['cost']     = $v2['num']*$ave;
                        $costData['all_cost'] = $v['cost'];
                        // 
                        $costData['staff_id']       = $v2['sales_staff_id'];
                        $costData['staff_name']     = $v2['sales_staff'];
                        $gInfo = getGroupInfo($v2['sales_staff_id']);
                        $costData['group_id']       = $gInfo['id'];
                        $costData['group_name']     = $gInfo['group_name'];
                        $costData['department_id']  = $v2['sales_department_id'];
                        $costData['department_name']= $departments[$v2['sales_department_id']]['department_name'];
                        $costData['shop_code']      = $v['belong_shop_code'];
                        $costData['shop_name']      = $v['belong_shop_name'];
                        $costData['day']            = $v['cost_date'];
                        $costData['channel_id']     = $v['channel_id'];
                        $costData['channel_name']   = $v['channel_name'];
                        array_push($inData,$costData);
                        unset($isId,$costData,$gInfo);
                    }
                    if (!empty($inData)) {
                        db('c_staff_channel_cost')->insertAll($inData);
                        unset($inData);
                    }
                    unset($where,$cStart,$cEnd,$cInfos,$c_all_num,$ave);
                }
            }
        }
        unset($day,$today,$shop_codes,$departments);
        unset($key,$k,$k1,$k2,$value,$v,$v1,$v2);
        unset($accDay,$start,$end,$channelCost,$where,$cStart,$cEnd,$cInfos,$c_all_num,$ave,$inData,$isId,$costData);
    }

    public function channelCost(){
        set_time_limit(0);
        // 当前日期 （几号）
        $day   = date('d');
        $today = date('Y-m-d');
        // 查最近两个月的客资的 add_shop_code （accounting_channel_cost_LSDS01）
        $shop_codes = db('c_customerinfo')->whereTime('dj_day','-90 days')->group('add_shop_code')->field('add_shop_code')->select();
        $this->log(' -- 渠道花费店'.json_encode($shop_codes));
        foreach ($shop_codes as $key => $value) {
            if (!$value['add_shop_code']) {
                continue;
            }
            $this->log(' -- 渠道花费店'.$value['add_shop_code']);
            // 获取花费核算日期
            $accDay = db_config('accounting_channel_cost_'.$value['add_shop_code']);
            $this->log(' -- 核算日期：'.$accDay);
            
            // 如果存在
            if ($accDay) {
                // 如果核算日期 小于 当前日期  只统计当月 渠道花费 平均给渠道的每一个客资
                if ($accDay<$day) {
                    // $this->log(' -- <');
                    $start= date('Y-m-01');
                    $end  = $today;
                    // $time_area = getDateFromRange($start,$end);
                    // $channelCost = db('s_channel_cost')->where('cost_date', 'between', [$start, $end])->field('channel_id,belong_shop_code,cost')->select();
                }
                // 如果核算日期 大于等于 当前日期  只统计当月 及上月 渠道花费 平均给渠道的每一个客资
                else{
                    // $this->log(' -- >=');
                    $start= date('Y-m-01', strtotime('-1 month'));
                    $end  = $today;
                    // $time_area  = getDateFromRange($start,$end);
                    // $channelCost= db('s_channel_cost')->where('cost_date', 'between', [$start, $end])->column('channel_id,belong_shop_code,cost','cost_date');
                }
                $cStart = date('Y-m-d 00:00:00',strtotime($start));
                $cEnd = date('Y-m-d 23:59:59',strtotime($end));
                db('c_customerinfo c')->join('c_customer_from f','c.id=f.cid','left')->where('c.dj_day','between',[$cStart,$cEnd])->update(array('f.c_channel_cost'=>0));
                
                $this->log(' -- 开始：'.$start.'；结束：'.$end);
                $channelCost= db('s_channel_cost')->where('cost','>','0')->where('cost_date', 'between', [$start, $end])->order('channel_id')->field('channel_id,channel_name,belong_shop_code,cost,cost_date')->select();

                // $this->log(' -- SQL：'.db()->getLastSql());
                // $this->log(' -- 花费：'.json_encode($channelCost));
                // $i = 0;
                foreach ($channelCost as $key => $value) {
                    $where['customer_channel_id'] = $value['channel_id'];
                    $where['customer_channel'] = $value['channel_name'];
                    $where['shop_code'] = $value['belong_shop_code'];
                    $cStart= date('Y-m-d 00:00:00', strtotime($value['cost_date']));
                    $cEnd  = date('Y-m-d 23:59:59', strtotime($value['cost_date']));
                    $cInfos= db('c_customerinfo')->where($where)->where('dj_day','between',[$cStart, $cEnd])->field('id')->select();
                    // $this->log(' -- customerInfo-->SQL：'.db()->getLastSql());
                    // exit;
                    $num = count($cInfos);
                    $ave = round(($value['cost']/$num), 2);
                    // $this->log('--ave--：'.$ave);
                    $saveInfo = [];
                    $inData = [];
                    foreach ($cInfos as $k => $val) {
                        // $this->log(' -- ID：'.$val['id']);
                        $res = db('c_customer_from')->where('cid',$val['id'])->value('cid');
                        // $this->log(' -- cidSql：'.db()->getLastSql());
                        // $this->log(' -- cidRes：'.$res);
                        // // 判断客资补充表里是否存在
                        if ($res) {
                            // $this->log(' -- inRes：');
                            // $temp['cid'] = $val['id'];
                            // $temp['c_channel_cost'] = $ave;
                            // array_push($saveInfo, $temp);
                            db('c_customer_from')->where('cid', $val['id'])->update(array('c_channel_cost'=>$ave));
                            // $this->log(' -- fromSql：'.db()->getLastSql());
                        }else{
                            // $this->log(' -- elseRes：');
                            $temp['cid'] = $val['id'];
                            $temp['c_channel_cost'] = $ave;
                            array_push($inData, $temp);
                        }
                    }
                    // $this->log(' -- inData：'.json_encode($inData));
                    // exit;
                    if (!empty($inData)) {
                        db('c_customer_from')->insertAll($inData);
                    }
                    // 批量更新 erp临时数据
                    // $fInfo = Model('c_customer_from');
                    // $fInfo->saveAll($saveTInfo);
                }
            }
        }
        unset($shop_codes,$accDay,$start,$end,$channelCost,$where,$cInfos,$inData);
    }

    // c_customer_order 表加一个字段 customer_number , t_c_info 加一个字段 is_deal 0：未处理；1：已处理；x：男女手机号都不存在；及重复的客资id
    // 创建临时表，temp_info(临时客资表)，temp_order(临时订单表)，temp_detail(临时明细表)，temp_contact(临时联系方式表)。查询t_c_info表，一次两千条。取出一条数据，
    // 根据 女手机号、男手机号，对比客资表， customer_tel  mate_tel 
    // 如果不存在，将该信息作为客资插入客资表，同时插入订单表，和明细表。将生成的 customer_number 更新到 t_c_info 表，同时更新is_deal状态
    //   如果存在，以女士手机号为主，将该客资的id，更新到t_c_info 表的is_deal字段；根据客资表的order_start_time，与该订单的target_time对比，更新为最近时间的订单状态，及明细
    public function log($value='')
    {
        file_put_contents(ROOT_PATH.'/runtime/log/repair.log', $value.'--》'.microtime(true).PHP_EOL, FILE_APPEND);
    }
    //--------------------- 婚纱客资转档后 导出erp订单（近一到两个月）、客资及收款表 ---------------------//
    protected  $bClass  = '费司摄影';
    protected  $bClassId= '3';
    public function repairCusOrder(){
        // 所有的订单
        $allOrder = db('z_erp_c_customerorder')
            ->field(
                'orderId','customerid','order_type','package_name','targetdate','storeconsuitant1','storeconsuitant2','total_money','payment_money','nopayment_money','supplementary_money','bargain_money','yixiaopaid_money','erxiaopaid_money','payoervedate','firstpaydate','ordernote','shop_code','shop_name','create_time','blankoutannal','is_effective','is_effectiveday'
            )->select();
        // 循环所有的订单
        foreach ($allOrder as $k => $v) {
            db()->startTrans();
            try {
                $cusOrder=db('c_customer_order')->where('order_sn',$v['orderId'])->field('id,customer_id')->find();
                // --- 修复客资数据 --- //
                $upCus['is_intostore'] = 2;
                // 有效单
                if ($v['is_effective']==1) {
                    $upCus['is_success']= 1;
                    $upCus['order_day'] = date('Y-m-d H:i:s',strtotime($v['is_effectiveday']));
                }else{
                    $upCus['is_success']= 3;
                    $upCus['order_day'] = NULL;
                }
                $upCus['order_number'] = $v['orderId'];
                $upCus['order_start_time'] = date('Y-m-d H:i:s',strtotime($v['targetdate']));
                $upCus['fact_money'] = $v['payment_money'];
                $upCus['totalpay_money'] = $v['total_money'];
                // 客资里已经有订单了  修复订单数据
                if ($cusOrder) {
                    // 更新客资
                    db('c_customerinfo')->where('id',$cusOrder['customer_id'])->update($upCus);
                    // --- 修复订单数据 --- //
                    // 作废单
                    if ($v['blankoutannal']==1) {
                        $upOrder['refund']= 2;
                    }
                    $upOrder['target_time']= date('Y-m-d H:i:s',strtotime($v['targetdate']));
                    $upOrder['create_time']= date('Y-m-d H:i:s',strtotime($v['create_time']));
                    // 有效单
                    if ($v['is_effective']==1) {
                        $upOrder['order_valid']= 2;
                        $upOrder['valid_time'] = date('Y-m-d H:i:s',strtotime($v['is_effectiveday']));
                    }else{
                        $upOrder['order_valid']= 1;
                        $upOrder['valid_time'] = NULL;
                    }
                    $upOrder['order_fact']    = $v['yixiaopaid_money'];
                    $upOrder['order_amount']  = $v['bargain_money'];
                    $upOrder['two_pin_fact']  = $v['erxiaopaid_money'];
                    $upOrder['two_pin_amount']= $v['supplementary_money'];
                    db('c_customer_order')->where('id',$cusOrder['id'])->update($upOrder);
                }
                // 客资里还没有订单  查询erp的客资手机号，在根据手机号查crm客资，并补充订单
                else{
                    $twoPhone = db('z_erp_c_customerinfo')->where('customerid',$v['customerid'])->field('mphone','wphone')->find();
                    if ($twoPhone['wphone'] && $twoPhone['mphone']) {
                        $sql = 'customer_tel='.$twoPhone['mphone'].' OR customer_tel='.$twoPhone['wphone'];
                    }else{
                        if ($twoPhone['mphone']) {
                            $sql = 'customer_tel='.$twoPhone['mphone'];
                        }
                        if ($twoPhone['wphone']) {
                            $sql = 'customer_tel='.$twoPhone['wphone'];
                        }
                    }
                    // 根据erp 订单的手机号查客资
                    $cusInfo = db('c_customerinfo')->where($sql)->field('id,customer_name,customer_channel,customer_channel_id,shop_code,shop_name')->find();
                    // echo db()->getLastSql();
                    // var_dump($cusInfo);
                    if (!$cusInfo) {
                        # code...
                    }


                }
                
                // 清空原有收款 同步erp收款记录
                db('c_order_detail')->where('order_sn',$v['orderId'])->delete();
                $payInfo = db('z_erp_c_paymentcontent')
                    ->where('orderId',$v['orderId'])
                    ->field('paymentdate,paymenttime,payment_money,suoshu')
                    ->select();
                $insertPay = [];
                foreach ($payInfo as $pk => $pv) {
                    $temp['pay_time'] = date('Y-m-d',strtotime($pv['paymentdate']));
                    $temp['create_time'] = date('Y-m-d',strtotime($pv['create_time']));
                    $temp['order_fact'] = $pv['payment_money'];
                    if ($pv['suoshu']=='前期款'||$pv['suoshu']=='前期补款') {
                        $temp['pay_type'] = 1;
                    }else{
                        $temp['pay_type'] = 2;
                    }
                    array_push($insertPay, $temp);
                    unset($temp);
                }
                db('c_order_detail')->insertAll($insertPay);
                db()->commit();
            } catch (\Exception $e) {
                db()->rollback();
                textlog();
            }
        }
    }
}