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

class Erp extends Controller{


    // ------------- 儿童排控 (选片、摄影) 开始 --------------

    //获取某个列表上方下方 排控统计数量
    public function reloadTableNum($photodate,$shop_code){

        //获取总排控数 已排控 可排控
        $res = $this->getPcNum($photodate,$shop_code);

        //已排程 摄影师 摄影助理 化妆师数量
        //摄影师
        $syer = db('c_customerphoto')
            ->where('shop_code',$shop_code)
            ->where('photodate',$photodate)
            ->field('cameraman AS staffname,COUNT(1) AS num')
            ->group('cameraman')
            ->select();

        foreach($syer as $syKey => $syVal){
            if(empty($syVal['staffname']))  unset($syer[$syKey]);
        }

        $res['syer'] = $syer;

        // 摄影助理
        $syzler = db('c_customerphoto')
            ->where('shop_code',$shop_code)
            ->where('photodate',$photodate)
            ->field('photoassistant AS staffname,COUNT(1) AS num')
            ->group('photoassistant')
            ->select();

        foreach($syzler as $zlKey => $zlVal){
            if(empty($zlVal['staffname']))  unset($syzler[$zlKey]);
        }
        $res['syzler'] = $syzler;

        //化妆师
        $hzer = db('c_customerphoto')
            ->where('shop_code',$shop_code)
            ->where('photodate',$photodate)
            ->field('dresser AS staffname,COUNT(1) AS num')
            ->group('dresser')
            ->select();

        foreach($hzer as $hzKey => $hzVal){
            if(empty($hzVal['staffname']))  unset($hzer[$hzKey]);
        }
        $res['hzer'] = $hzer;

        unset($syer,$syzler,$hzer);

        return $res;

    }

    /*
     * 获取可排控数量
     * $shop_code   店面识别码
     * $photodate   时间
     */
    public function getPcNum($photodate,$shop_code){
        // 查设定 (可排程)
        $pc_set = db('s_pcdefault_monthset')
            ->where('pctype', 0) // 0:拍照排程;1:选片排程
            ->where('shop_code', $shop_code)
            ->where('pcday',$photodate)
            ->field('pcday,sum(timecount) num')
            ->find();

        $res['day'] = $photodate;
        $res['allPc'] = $pc_set['num'];
        unset($pc_set);

        // 查排程 已排程
        $pc_list = db('c_customerphoto')
            ->where('shop_code', $shop_code)
            ->where('photodate',$photodate)
            ->field('photodate,count(orderId) as num')
            ->find();

        $res['yPc'] = $pc_list['num'];
        $res['nPc'] = $res['allPc'] - $res['yPc'];
        unset($pc_list);
        return $res;
    }


    /*
     *  获取每一天的排程
     *  $shop_code    店面识别码
     *  $photodate          日期（例:20181114）
     */
    public function getPcListDay($photodate,$shop_code){


        $pc_set = db('s_pcdefault_monthset')
            ->where('pctype', 0) // 0:拍照排程;1:选片排程
            ->where('shop_code', $shop_code)
            ->where('pcday',$photodate)
            ->column('pcday,pctime,timecount,area','id');

        //根据排程设定 得到的空数据
        $setData = [];
        $num = 1;
        foreach($pc_set as $key => $value){

            for($i = 0; $i < $value['timecount']; $i++){
                $setData[] = [
                    'setId'   => $num,
                    'setTime' => $value['pctime'],
                    'setArea' => $value['area'],
                    'is_use'  => 2
                ];

                $num ++;
            }
        }

        unset($pc_set);

        //已排程数据
        $pc_list = db('c_customerphoto')->alias('p')
            ->join('c_customerinfo c','c.customerid = p.customerid', 'left')
            ->join('c_customerorder o','o.customerid = c.customerid', 'left')
            ->where('p.shop_code', $shop_code)
            ->where('p.photodate',$photodate)
            ->field('p.id,c.customerid,c.mname,c.wname,c.bbname,c.wphone,c.mphone,c.cssname,c.area,o.orderId,o.targetdate,o.consumption_type,o.acceptor_address,o.total_money,o.payment_money,o.nopayment_money,o.ordertopic,o.dresstheme,o.ordernote,p.currentfc,p.phototype,p.photodate,p.phototime,p.photostate,p.cameraman,p.photoassistant,p.lighting_engineer,p.designer,p.mentor_a,p.mentor_b,p.dresser,p.photonote,p.photobase,p.id,p.id as photoid,p.shop_code,p.jiaji,p.huazhuangzhuli,p.communication_date,p.communicationtime,p.communication_state,p.communication_man,p.secretaireman,p.shop_name,p.shop_code')
            ->order('p.photodate')
            ->select();

        $set_list = $setData;
        foreach($pc_list as $key => $val){

            $status = 5;
            $keyNum = 'no';
            foreach($set_list as $k => $v){


                if(!empty($v['setTime']) && $v['setArea']!='全部' && $val['phototime']==$v['setTime'] && $val['area']==$v['setArea']){

                    if($status > 1 && $v['is_use'] == 2){
                        $status = 1;
                        $pc_list[$key]['setId'] = $v['setId'];
                        $set_list[$k]['is_use'] = 1;

                        //将之前匹配数据修改回未使用状态
                        if($keyNum !='no'){
                            $set_list[$keyNum]['is_use'] = 2;
                        }

                        //更改当前规则key
                        $keyNum = $k;

                    }

                }elseif(!empty($v['setTime']) && $v['setArea'] == '全部'){

                    $setPcTime = $v['setTime'];
                    $setArea = $val['area'];

                    if($val['phototime'] == $setPcTime && $val['area'] == $setArea){
                        if($status > 2 && $v['is_use'] == 2){
                            $status = 2;
                            $pc_list[$key]['setId'] = $v['setId'];
                            $set_list[$k]['is_use'] = 1;

                            //将之前匹配数据修改回未使用状态 更改当前规则key
                            if($keyNum !='no'){
                                $set_list[$keyNum]['is_use'] = 2;
                            }
                            //更改当前规则key
                            $keyNum = $k;
                        }
                    }

                }elseif(empty($v['setTime']) && $v['setArea'] != '全部'){

                    $setPcTime = $val['phototime'];
                    $setArea = $v['setArea'];

                    if($val['phototime'] == $setPcTime && $val['area'] == $setArea){

                        if($status > 2 && $v['is_use'] == 2){
                            $status = 2;
                            $pc_list[$key]['setId'] = $v['setId'];
                            $set_list[$k]['is_use'] = 1;

                            //将之前匹配数据修改回未使用状态 更改当前规则key
                            if($keyNum !='no'){
                                $set_list[$keyNum]['is_use'] = 2;
                            }
                            //更改当前规则key
                            $keyNum = $k;
                        }
                    }
                }elseif(empty($v['setTime']) && $v['setArea'] == '全部'){

                    if($status > 3 && $v['is_use'] == 2){

                        $status = 3;
                        $pc_list[$key]['setId'] = $v['setId'];
                        $set_list[$k]['is_use'] = 1;

                        //将之前匹配数据修改回未使用状态 更改当前规则key
                        if($keyNum !='no'){
                            $set_list[$keyNum]['is_use'] = 2;
                        }
                        //更改当前规则key
                        $keyNum = $k;
                    }
                }

                unset($setPcTime,$setArea);
            }

        }

        foreach($setData as $k1 => $v1){

            foreach($pc_list as $k2 => $v2){
                if($v2['setId'] == $v1['setId']){
                    $setData[$k1] = $v2;
                    $setData[$k1]['setTime'] = $v1['setTime'];
                    $setData[$k1]['setArea'] = $v1['setArea'];
                    unset($pc_list[$k2]);
                }
            }
        }

        $all_list = array_merge($setData,$pc_list);
        return $all_list;

    }


    // -------------------------------------------- 儿童排控 (选片、摄影) 结束 -------------------------------------------- //
    /**
     * 6+1版 crm转网付订单 直接写erp数据库
     * 
     * @param string  OrderId  订单编号
     * @param string  
     * @param string  
     *
     * @return 
     */
    public function createOrder($param){
        $countOid = db('c_customerorder')->where('orderId',$param['OrderId'])->count();
        if ($countOid || !$param['OrderId']) {
            $erp = new erpInterface();
            $createOrderId['ShopSn'] = $param['ShopSn'];
            $createOrderId['StaffSN'] = $param['StaffSN'];
            $createOrderId['Consumption_type'] = $param['Consumption_type'];
            $param['OrderId'] = $erp->getOrderSn($createOrderId);
            if(!$param['OrderId']){
                return array('code'=>700, 'msg'=>'订单号获取失败。','data'=>'');
            }
        }
        
        $dttime  = date('Y-m-d H:i:s');
        $strGUID = strtolower(trim(trim(getGuid(),'{'),'}'));
        $BindOldCard = false;
        $vippercents = "10";
        $cardid  = $param['Wphone'];
        $viptype = "储值卡";
        // region 获取VIP信息
        $dt_c_vipcardinfo = db('c_vipcardinfo')->where('cardid',$cardid)->field('cardid,cardtype,percents')->find();

        if (count($dt_c_vipcardinfo)>0) {
            $BindOldCard = true;
            $vippercents = $dt_c_vipcardinfo['percents'];
            $viptype     = $dt_c_vipcardinfo['cardtype'];
        }
        // endregion
        
        $sindex = $param['OrderId'];
        // region 获取母单单号
        $dt_c_customerorder = db('c_customerinfo')->alias('c')
            ->join('c_customerorder o','o.customerid=c.customerid')
            ->where('wphone','not null')->where('wphone','<>','')
            ->where('wphone',$param['Wphone'])
            ->field('distinct sindex,orderId,wname,bbname')
            ->select();
        if (count($dt_c_customerorder)>0) {
            $sindex = $dt_c_customerorder[0]["sindex"];
        }
        // endregion

        // 客户资料表 c_customerinfo
        $cData['customer_channel']   = $param['Customer_channel'];
        if(!$cData['customer_channel']){
            return array('code'=>301, 'msg'=>'开单失败，没有渠道信息，无法转单','data'=>'','error'=>'没有渠道信息，无法转单');
        }
        $cData['customer_from'] = 'CRM';
        // $cData['customer_from_index']= $param['Customer_from_index'];
        $cData['customerid'] = $strGUID;
        $cData['email']      = $param['Email'];
        $cData['cssname']    = $param['Cssname'];
        $cData['area']       = $param['Area'];
        $cData['weddingdate']= $param['Weddingdate'];
        $cData['wname']      = $param['Wname'];
        $cData['wphone']     = $param['Wphone'];
        $cData['mname']      = $param['Mname'];
        $cData['mphone']     = $param['Mphone'];
        $cData['mwechat']    = $param['Mwechat'];
        $cData['wwechat']    = $param['Wwechat'];
        $cData['shop_code']  = $param['Shop_code'];
        $cData['shop_name']  = $param['Shop_name'];
        $cData['create_time']= $dttime;
        $cData['vipnum']     = $cardid;
        $cData['viptype']    = $viptype;
        $cData['vippercents']= $vippercents;
        $cData['brandid']    = $param['Brandid'];
        $cData['wbirthdate'] = $param['Wbirthdate'] ? date('Ymd', strtotime($param['Wbirthdate'])) : '';
        $cData['mbirthdate'] = $param['Mbirthdate'] ? date('Ymd', strtotime($param['Mbirthdate'])) : '';
        $cData['bbname']     = $param['Bbname'];
        $cData['bbsex']      = $param['Bbsex'];
        $cData['bbithdate']  = $param['Bbithdate'];
        $cData['bb_hospital']= $param['Bb_hospital'];
        $cData['yc_day']     = $param['Yc_day'] ? date('Ymd', strtotime($param['Yc_day'])) : '';
        $cData['address_sheng']= $param['Address_sheng'];
        $cData['address_shi']= $param['Address_shi'];
        $cData['address_qu'] = $param['Address_qu'];
        $cData['address']    = $param['Address'];
        // 订单表数据 c_customerorder
        $selkey = $param['OrderId'].','.$param['Bbname'].','.$param['Wname'].','.$param['Wphone'].','.$param['Mname'].','.$param['Mphone'];
        $orderData['jiandangren'] = $param['Jiandangren'];
        $orderData['selkey']      = $selkey;
        $orderData['acceptor_address']= $param['Acceptor_address'];
        $param['Yxpackage_price'] = $param['Yxpackage_price']?$param['Yxpackage_price']:0;
        if($param['order_method'] == '上门拍订单-改'){
            $orderData['package_name']    = $param['Yxpackage_name'];
            $orderData['bargain_money']   = $param['Yxpackage_price'];
            $orderData['nopayment_money'] = $param['Yxpackage_price'];
            $orderData['yxpackage_name']  = $param['Yxpackage_name'];
            $orderData['yxpackage_price'] = $param['Yxpackage_price'];
        }else{
            $orderData['yxpackage_name']  = $param['Yxpackage_name'];
            $orderData['yxpackage_price'] = $param['Yxpackage_price'];
        }
        $orderData['total_money'] = $param['Yxpackage_price'];
        $orderData['orderyouxiao'] = $param['orderyouxiao'];
        $orderData['orderyouxiaodate'] = $param['orderyouxiaodate'];
        $orderData['orderId']         = $param['OrderId'];
        $orderData['customerid']      = $strGUID;
        $orderData['targetdate']      = $param['Targetdate'];
        $orderData['storeconsuitant1']= $param['Storeconsuitant1'];
        $orderData['storeconsuitant2']= $param['Storeconsuitant2'];
        $orderData['consumption_type']= $param['Consumption_type'];
        $orderData['shop_order_name'] = $param['Shop_name'];
        $orderData['shop_code']       = $param['Shop_code'];
        $orderData['shop_name']       = $param['Shop_name'];
        $orderData['create_time']     = $dttime;
        $orderData['ordernote']       = $param['Ordernote'];
        $orderData['sindex']          = $sindex;
        $orderData['reservelock']     = $param['Reservelock'] ? $param['Reservelock'] : 0;
        if ( isColumnExist( array('table'=>'c_customerorder','column'=>'crm_customer_id') ) ) {
            $orderData['crm_customer_id'] = $param['crm_customer_id'];
        }
        $orderData['crm_customer_number'] = $param['Customer_from_index'];
        $orderData['crm_c_unique']    = $param['crm_c_unique'];
        $orderData['crm_order_type']  = '1';
        $orderData['give_photo_num']  = $param['give_photo_num'];
        $orderData['crm_visit_id']    = $param['crm_visit_id'];
        if ($param['topiclist']) {
            $orderData['indoordresscount']= 1;
        }
        if ( isColumnExist( array('table'=>'c_customerorder','column'=>'tuiguangstaff') ) ) {
            $orderData['tuiguangstaff'] = $param['tuiguangstaff'];
        }
        if ( isColumnExist( array('table'=>'c_customerorder','column'=>'wangfutype') ) ) {
            if ($param['wangfutype']) {
                $orderData['wangfutype'] = $param['wangfutype'];
            }
        }
        if($param['order_method'] == '上门拍订单-改'){
            // 消费项目表  c_consumptioncontent
            if ($param['package_type']=='cz') {// 成长套系
                $consuData[0]['create_time'] = $dttime;
                $consuData[0]['orderId'] = $param['OrderId'];
                $consuData[0]['customerid'] = $strGUID;
                $consuData[0]['sorting'] = '-1';
                $consuData[0]['categories'] = '成长套系';
                $consuData[0]['consumption_name'] = $param['Yxpackage_name'];
                $consuData[0]['amount'] = 1;
                $consuData[0]['remarks'] = '';
                $consuData[0]['transfer_certificate'] = 0;
                $consuData[0]['item_pagecount'] = 0;
                $consuData[0]['item_sheetscount'] = 0;
                $consuData[0]['size'] = '';
                $consuData[0]['price'] = $param['Yxpackage_price'];
                $consuData[0]['cost'] = 0;
                $consuData[0]['total'] = $param['Yxpackage_price'];
                $consuData[0]['shop_code'] = $param['Shop_code'];
                $consuData[0]['shop_name'] = $param['Shop_name'];
                $consuData[0]['issources'] = 0;
                $consuData[0]['servicenumber'] = 0;
                $consuData[0]['tx'] = '';
                $consuData[0]['cztx'] = $param['Yxpackage_name'];
                $consuData[0]['yejiprice'] = 0;
                $consuData[0]['yuanjiaprice'] = $param['Yxpackage_price'];
                $consuData[0]['yspcount'] = 0;
                $consuData[0]['issp'] = 0;
                $consuData[0]['istxitem'] = 1;
                $consuData[0]['ckssubtypes'] = '成长套系';
                $consuData[0]['ordertype'] = '摄影';
                $consuData[0]['txconmoney'] = 0;

                $czPackDetail = db('s_czpackagedetailset')
                    ->where('czpackage_name', $param['Yxpackage_name'])
                    ->order('servicenumber asc')
                    ->select();
                $packageName = '';
                $sorting = 0;
                foreach ($czPackDetail as $key => $value) {
                    $temp['create_time'] = $dttime;
                    $temp['orderId'] = $param['OrderId'];
                    $temp['customerid'] = $strGUID;
                    $temp['sorting'] = 0;
                    $sorting++;
                    $temp['categories'] = '套系';
                    $temp['consumption_name'] = $value['package_name'];
                    $temp['amount'] = 1;
                    $temp['remarks'] = $value['pack_remark'];
                    $temp['transfer_certificate'] = 0;
                    $temp['item_pagecount'] = 0;
                    $temp['item_sheetscount'] = 0;
                    $temp['size'] = '';
                    $temp['price'] = 0;
                    // $temp['price'] = $param['Yxpackage_price'];
                    $temp['cost'] = 0;
                    $temp['total'] = 0;
                    // $temp['total'] = $param['Yxpackage_price'];
                    $temp['shop_code'] = $param['Shop_code'];
                    $temp['shop_name'] = $param['Shop_name'];
                    $temp['issources'] = 0;
                    $temp['servicenumber'] = $value['servicenumber'];
                    $temp['tx'] = $value['package_name'];
                    $temp['cztx'] = $param['Yxpackage_name'];
                    $temp['yejiprice'] = $value['package_price'];
                    $temp['yuanjiaprice'] = $value['package_price'];
                    $temp['yspcount'] = 0;
                    $temp['issp'] = 0;
                    $temp['istxitem'] = 1;
                    $temp['ckssubtypes'] = '套系';
                    $temp['ordertype'] = '摄影';
                    $temp['txconmoney'] = 0;
                    array_push($consuData, $temp);
                    unset($temp);
                    $packDetail = db('s_package_portfolio')->alias('p')
                        ->join('s_consumptionitem c','p.Item_name=c.item_name','left')
                        ->where('p.package_name',$value['package_name'])
                        ->order('p.sequence asc')
                        ->select();
                    foreach ($packDetail as $k => $v) {
                        $temp['create_time'] = $dttime;
                        $temp['orderId'] = $param['OrderId'];
                        $temp['customerid'] = $strGUID;
                        $temp['sorting'] = $sorting;
                        $sorting++;
                        $temp['categories'] = $v['category'];
                        $temp['consumption_name'] = $v['Item_name'];
                        $temp['amount'] = $v['amount'];
                        $temp['remarks'] = '';
                        $temp['transfer_certificate'] = $v['isconversion'] ? $v['isconversion'] : 0;//?是否转出件
                        $temp['item_pagecount'] = $v['item_pagecount'] ? $v['item_pagecount'] : 0;//?P数
                        $temp['item_sheetscount'] = $v['item_sheetscount'];
                        $temp['size'] = '';
                        $temp['price'] = 0;
                        $temp['cost'] = $v['item_costs'] ? $v['item_costs'] : 0;//?成本
                        $temp['total'] = 0;
                        $temp['shop_code'] = $param['Shop_code'];
                        $temp['shop_name'] = $param['Shop_name'];
                        $temp['issources'] = 0;
                        $temp['servicenumber'] = $value['servicenumber'];
                        $temp['tx'] = $value['package_name'];
                        $temp['cztx'] = $param['Yxpackage_name'];
                        $temp['yejiprice'] = 0;
                        $temp['yuanjiaprice'] = $v['item_price'] ? $v['item_price'] : 0;//?原价
                        $temp['yspcount'] = $v['item_pagecount'] ? $v['item_pagecount'] : 0;//?P数
                        $temp['issp'] = $v['issp'] ? $v['issp'] : 0;//?参与选片
                        $temp['istxitem'] = 1;
                        $temp['ckssubtypes'] = $v['ckssubtype'];
                        $temp['ordertype'] = '摄影';
                        $temp['txconmoney'] = $v['txmoney'];
                        array_push($consuData, $temp);
                        unset($temp);
                    }
                }
            }
            else if ($param['package_type']=='tx') {// 普通套系
                $packInfo = db('s_packageset')
                    ->where('package_name',$param['Yxpackage_name'])
                    ->find();
                $consuData[0]['create_time'] = $dttime;
                $consuData[0]['orderId'] = $param['OrderId'];
                $consuData[0]['customerid'] = $strGUID;
                $consuData[0]['sorting'] = '0';
                $consuData[0]['categories'] = '套系';
                $consuData[0]['consumption_name'] = $param['Yxpackage_name'];
                $consuData[0]['amount'] = 1;
                $consuData[0]['remarks'] = $packInfo['pack_remark'];
                $consuData[0]['transfer_certificate'] = 0;
                $consuData[0]['item_pagecount'] = 0;
                $consuData[0]['item_sheetscount'] = 0;
                $consuData[0]['size'] = '';
                $consuData[0]['price'] = $param['Yxpackage_price'];
                $consuData[0]['cost'] = 0;
                $consuData[0]['total'] = $param['Yxpackage_price'];
                $consuData[0]['shop_code'] = $param['Shop_code'];
                $consuData[0]['shop_name'] = $param['Shop_name'];
                $consuData[0]['issources'] = 0;
                $consuData[0]['servicenumber'] = 1;
                $consuData[0]['tx'] = $param['Yxpackage_name'];
                $consuData[0]['cztx'] = '';
                $consuData[0]['yejiprice'] = $param['Yxpackage_price'];
                $consuData[0]['yuanjiaprice'] = $param['Yxpackage_price'];
                $consuData[0]['yspcount'] = 0;
                $consuData[0]['issp'] = 0;
                $consuData[0]['istxitem'] = 1;
                $consuData[0]['ckssubtypes'] = '套系';
                $consuData[0]['ordertype'] = $packInfo['txtype'];
                $consuData[0]['txconmoney'] = 0;
                // s_packageset
                $packDetail = db('s_package_portfolio')->alias('p')
                    ->join('s_consumptionitem c','p.Item_name=c.item_name','left')
                    ->where('p.package_name',$param['Yxpackage_name'])
                    ->order('p.sequence asc')
                    ->select();
                // echo db()->getLastSql();die;
                if ($packDetail) {
                    $sorting = 1;
                    foreach ($packDetail as $k => $v) {
                        $temp['create_time'] = $dttime;
                        $temp['orderId'] = $param['OrderId'];
                        $temp['customerid'] = $strGUID;
                        $temp['sorting'] = $sorting;
                        $sorting++;
                        $temp['categories'] = $v['category'];
                        $temp['consumption_name'] = $v['Item_name'];
                        $temp['amount'] = $v['amount'];
                        $temp['remarks'] = '';
                        $temp['transfer_certificate'] = $v['isconversion'] ? $v['isconversion'] : 0;//?是否转出件
                        $temp['item_pagecount'] = $v['item_pagecount'] ? $v['item_pagecount'] : 0;//?P数
                        $temp['item_sheetscount'] = $v['item_sheetscount'];
                        $temp['size'] = '';
                        $temp['price'] = 0;
                        $temp['cost'] = $v['item_costs'] ? $v['item_costs'] : 0;//?成本
                        $temp['total'] = 0;
                        $temp['shop_code'] = $param['Shop_code'];
                        $temp['shop_name'] = $param['Shop_name'];
                        $temp['issources'] = 0;
                        $temp['servicenumber'] = 1;
                        // $temp['servicenumber'] = $value['servicenumber'];
                        $temp['tx'] = $value['package_name'];
                        $temp['cztx'] = $param['Yxpackage_name'];
                        $temp['yejiprice'] = 0;
                        $temp['yuanjiaprice'] = $v['item_price'] ? $v['item_price'] : 0;//?原价
                        $temp['yspcount'] = $v['item_pagecount'] ? $v['item_pagecount'] : 0;//?P数
                        $temp['issp'] = $v['issp'] ? $v['issp'] : 0;//?参与选片
                        $temp['istxitem'] = 1;
                        $temp['ckssubtypes'] = $v['ckssubtype'];
                        $temp['ordertype'] = '摄影';
                        $temp['txconmoney'] = $v['txmoney'];
                        array_push($consuData, $temp);
                        unset($temp);
                    }
                }   
            }
        }
        
        // 服次表 c_customerorder_servicefc
        $fcData['customerid']= $strGUID;
        $fcData['orderId']   = $param['OrderId'];
        $fcData['currentfc'] = 1;
        $fcData['allfc']     = 1;
        $fcData['islastfc']  = 1;
        if ($param['topiclist']) {
            $fcData['kaidanzhuti']= $param['topiclist'];
        }
        // 拍照表 c_customerphoto
        $photoData['currentfc']  = '1';
        $photoData['phototype']  = '拍照';
        $photoData['photostate'] = '5';
        $photoData['orderId']    = $param['OrderId'];
        $photoData['customerid'] = $strGUID;
        $photoData['fuwutype'] = $cData['area'];
        $photoData['phototime']  = '';
        $photoData['shop_code']  = $param['photo_shop_code'] ? $param['photo_shop_code'] : $param['Shop_code'];
        $photoData['shop_name']  = $param['photo_shop_name'] ? $param['photo_shop_name'] : $param['Shop_name'];
        $photoData['create_time']= $dttime;
        $photoData['setkey']     = $param['Shop_order_code'];
        $photoData['islast']     = '1';
        $photoData['photonote']  = $param['Ordernote'];
        $photoData['cameraman']  = $param['Cameraman'];
        $photoData['mentor_a']   = $param['mentor_a'];
        if ($param['topiclist']) {
            $photoData['topiclist']= $param['topiclist'];
        }
        if($param['autophoto'] == 1){
            $photoData['photodate']  = date('Ymd');
            $photoData['paikongstaff']  = $param['pc_opt_staff_name'];
            $photoData['paikongtime']  = $param['pc_opt_time'];
            $photoData['paikongshop_code']  = $param['pc_opt_shop_code'];
            $photoData['paikongshop_name']  = $param['pc_opt_shop_name'];
            $photoData['photonote']  = 'CRM上门拍转单自动排程';
        }else{
            $photoData['photodate'] = '';
        }
        // 选片表 c_customersp
        $spData['currentfc'] = '1';
        $spData['orderId']   = $param['OrderId'];
        $spData['customerid']= $strGUID;
        $spData['sptstate']  = '5';
        $spData['islast']    = '1';
        if($param['autosp'] == 1){
            $spData['selectday'] = date('Ymd');
        }
        $spData['shop_code'] = $param['photo_shop_code'] ? $param['photo_shop_code'] : $param['Shop_code'];
        $spData['shop_name'] = $param['photo_shop_name'] ? $param['photo_shop_name'] : $param['Shop_name'];
        // vip表 c_vipcardinfo
        if (!$BindOldCard) {
            $vipData['cardid']      = $param['Wphone'];
            $vipData['forcardstaff']= $param['Jiandangren'];
            $vipData['cardtype']    = '储值卡';
            $vipData['cardtime']    = date('Ymd',strtotime($dttime));
            $vipData['givetime']    = date('Ymd',strtotime($dttime));
            $vipData['cardpwd']     = substr($param['Wphone'], -6);// 手机号后六位
            $vipData['cardmoney']    = '0';
            $vipData['start_validity']='';
            $vipData['end_validity']= '';
            $vipData['percents']    = '10';
            $vipData['cardstate']   = '2';
            $vipData['shop_code']   = $param['Shop_code'];
            $vipData['shop_name']   = $param['Shop_name'];
            $vipData['orderId']     = $param['OrderId'];
            $vipData['ismothercard']= '1';
            $vipData['mothercard']  = $param['Wphone'];
            $vipData['PaySource']   = '0';
            $vipData['IntroSource'] = '0';
            $vipData['PlusSource']  = '0';
            $vipData['PayIntro']    = '0';
            $vipData['customerid']  = $strGUID;
        }
        // 收款表 c_paymentcontent
        $collectmoneynumber = "";
        $paycodenumber = "";
        $resource = 0;
        if ($param['Paymentmoney']) {
            $orderData['yixiaoshishou']  = $param['Paymentmoney'];
            $orderData['payment_money']  = $param['Paymentmoney'];
            $orderData['nopayment_money']= $orderData['bargain_money']-$param['Paymentmoney'];
            $orderData['payoervedate']   = date('Ymd', strtotime($dttime));
            $orderData['isvalid']  = '1';
            $orderData['validdate']= date('Ymd', strtotime($dttime));

            if (!$viptype) {
                $resParam['paymentmoney']= $param['Paymentmoney'];
                $resParam['viptype']     = $viptype;
                $resParam['shop_code']   = $param['Shop_code'];
                $resource = $this->getResource($resParam);
            }
            
            $paycodenumber = $this->getPayCodeNumber();
            $collectmoneynumber = $this->collectmoneynumber();

            $dt_paytype = db('c_paymenttype')
                ->where('typename', $param['Paytype'])
                ->field('typecode,typename,iscanuse,shop_code')
                ->find();
            
            $payData['orderId']    = $param['OrderId'];
            $payData['customerid'] = $strGUID;
            $payData['payclass']   = '0';
            $payData['paytype']    = $param['Paytype'];
            $payData['paymentdate']= date('Ymd',strtotime($dttime));
            $payData['paymenttime']= date('Hi',strtotime($dttime));
            $payData['payment_money']=$param['Paymentmoney'];
            $payData['cashierman'] = $param['Jiandangren'];
            $payData['fundname']   = '前期包套';
            $payData['collectmoneynumber']=$collectmoneynumber;
            $payData['vipcardid']  = '';
            $payData['viptype']    = '';
            $payData['ourselfresource']= $resource;
            $payData['othersource']= '0';
            $payData['acceptor_address']=$param['Acceptor_address'];
            $payData['remarks']    = '';
            $payData['isaudit']    = '0';
            $payData['shop_code']  = $param['Shop_code'];
            $payData['shop_name']  = $param['Shop_name'];
            $payData['create_time']= $dttime;
            $payData['isshow']     = '';
            $payData['vipuser_id'] = '0';
            $payData['wechat_payment']='';
            $payData['wechat_payment_mcid']='0';
            $payData['viprechargecard']='';
            $payData['viprechargemoney']='0';
            $payData['suoshu']       = '前期款';
            $payData['shoukuantype'] = '0';
            $payData['paycodenumber']= $paycodenumber;
            $payData['isshishou']    = $dt_paytype['typecode'];
            $payData['currentfc']    = '1';
            $payData['paymentcode']  = $param['duikuanma'];
        }
        db()->startTrans();
        try {
            db('c_customerinfo')->insert($cData);
            db('c_customerorder')->insert($orderData);
            if($param['order_method'] == '上门拍订单-改'){
                db('c_consumptioncontent')->insertAll($consuData);
            }
            db('c_customerorder_servicefc')->insert($fcData);
            db('c_customerphoto')->insert($photoData);
            db('c_customersp')->insert($spData);
            if (!$BindOldCard) {
                db('c_vipcardinfo')->insert($vipData);
            }
            if ($param['Paymentmoney']) {
                db('c_paymentcontent')->insert($payData);
            }
            db()->commit();
            return array('code'=>200, 'msg'=>'开单成功','data'=>'','orderId'=>$param['OrderId']);
        } catch (\Exception $e) {
            db()->rollback();
            return array('code'=>300, 'msg'=>'开单失败','data'=>'','error'=>$e->getMessage());
        }
    }
    // erp 方法
    public function getPayCodeNumber(){
        return 'P'.date('YmdHis').rand(1000,9999);
    }
    // erp 方法
    public function collectmoneynumber($param){
        $dtVno = db('c_paymentcontent')
            ->where('left(collectmoneynumber,8)', date('Ymd'))
            ->field('collectmoneynumber')
            ->order('collectmoneynumber desc')
            ->find();

        if ($dtVno['collectmoneynumber']) {
            $unmber = date('Ymd').'001';
        }else{
            $unmber = $dtVno['collectmoneynumber']+1;
        }
        return $unmber;
    }
    // erp 方法
    public function getResource($param){
        $xfjf = 0;
        $dt = db('s_vipdiscount')
            ->where('discount_name', $param['viptype'])
            ->field('discount_name,isjifen,jfmoney,jfvalue,isjsjifen,jsmoney,jsvalue')
            ->find();
        if (count($dt)>0) {
            if (isset($dt['isjifen'])) {
                if ($dt['isjifen']==1 && $dt['jfmoney']!=0) {
                    $xfjf = $dt['jfvalue'] * ($param['paymentmoney']/$dt['jfmoney']);
                }
            }
        }
        return $xfjf;
    }

    // 
    public function isAddPackage($param){
        $b = array('code' => 200, 'msg'=>'');
        if(strpos($param['package_name'], '体验') === false){ 
            return $b;
        }
        $count = db('c_customerinfo')->alias('c')
            ->join('c_customerorder o', 'c.customerid=o.customerid', 'left')
            ->where('c.wphone', $param['wphone'])
            ->count();
        if ($count==0) {
            return $b;
        }

        $dt = db('c_customerinfo')->alias('c')
            ->join('c_customerorder b', 'c.customerid=b.customerid')
            ->join('c_consumptioncontent con', "b.orderId=con.orderId and (con.sorting='0' or con.sorting='-1')")
            ->where('c.wphone',$param['wphone'])->where('b.allfinishfate','<>','')
            // ->where('c.customerid', '<>', $param['customerid'])
            ->where('consumption_name', 'like', '%体验%')
            ->select();
        if (count($dt)==0) {
            return $b;
        }
        // $param['package_name']
        $drs = [];
        foreach ($dt as $key => $value) {
            if ($value['consumption_name'] == $param['package_name']) {
                $drs[] = $value;
            }
        }

        if (count($drs)>0) {
            $b = array('code'=>100,'msg'=>'当前客人已添加过体验套系，添加订单'.$drs[0]['orderId']);
        }
        return $b;
    }

    public function getCustomerOrdersCount($customerNumber,$consultationType=''){

        
        $zfSql = ' p.photodate="" OR p.photodate is null ';
        $order = db('c_customerorder')->alias('o')
            ->where('o.crm_order_type',1)
            ->where('o.blankoutannal',0)
            ->where('crm_customer_number',$customerNumber);
        if($consultationType){
            $order->where('o.consumption_type',$consultationType);
        }
        /*
        $o = $order->count();
        if(!$o){
            return 0;//没订单
        }
        */
        $oc = $order->join('c_paymentcontent c','c.orderid=o.orderid','left')->where(' c.id is null ') ->count();
        // echo db()->getLastSql();
        /*
            ->join('c_customerphoto p','p.orderid=o.orderid','left')
            ->join('c_paymentcontent c','c.orderid=o.orderid','left')
            ->where('crm_customer_number',$customerNumber)
            ->where('c.id', 'null')->where($zfSql);
            */
        // $orderIds = $zfOrder->column('o.orderId');
        // $res = 0;//0没有订单，1有未收款的订单，2有收费套系，也收款了
        
        if($oc >0){
            return ['nopay'=>1];
        }else{
            return [];
        }
    }

}
