<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020/5/30
 *
 *
 */

namespace app\common\repositories\merchant\order;

use app\common\dao\merchant\order\OrderGzcDao;
use app\common\model\merchant\order\OrderGzc;
use app\common\repositories\BaseRepository;
use app\traits\GzcApiRequest;
use Carbon\Carbon;
use crmeb\services\SpreadsheetExcelService;
use FormBuilder\Factory\Elm;
use think\facade\Db;
use think\facade\Log;
use think\facade\Route;

/**
 * Class OrderGzcRepository
 * @package app\common\repositories\merchant\order
 * @author: php迷途小书童
 * @created: 2021/3/20 10:25
 */
class OrderGzcRepository extends BaseRepository
{
    use GzcApiRequest;

    /**
     * OrderGzcDao constructor.
     * @param OrderGzcDao $dao
     */
    public function __construct(OrderGzcDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @return array
     * @author php迷途小书童
     * @created 2021/1/16 10:41
     */
    public function getList(array $where, $page, $limit)
    {
        $query = $this->dao->search($where);
        // 导出
        $is_excel = request()->param('is_excel', 0);
        if ($is_excel == 1) {
            $data = $query->with(['user', 'bill'])->select()->toArray();

            $arr = [];
            if (!empty($data)) {
                $orderTypeMap = [];
                $orderDetailMap = [];
                $orderMap = [
                    0 => ['table' => 'rrx_store_order', 'name' => '平台订单', 'pk' => 'order_id', 'field' => 'order_id, total_price AS order_money, pay_price AS pay_money, con_pri AS commission, mer_id'],
                    1 => ['table' => 'rrx_order_pdd', 'name' => '拼多多', 'pk' => 'order_pdd_id', 'field' => 'order_pdd_id AS order_id, order_money, pay_money, commission'],
                    2 => ['table' => 'rrx_order_vip', 'name' => '唯品会', 'pk' => 'order_vip_id', 'field' => 'order_vip_id AS order_id, pay_money AS order_money, pay_money, commission'],
                    3 => ['table' => 'rrx_order_su', 'name' => '苏宁', 'pk' => 'order_su_id', 'field' => 'order_su_id AS order_id, total_amount AS order_money, pay_amount AS pay_money, commission'],
                    5 => ['table' => 'rrx_order_tb', 'name' => '淘宝', 'pk' => 'order_tb_id', 'field' => 'order_tb_id AS order_id, alipay_total_price AS order_money, alipay_total_price AS pay_money, commission'],
                    6 => ['table' => 'rrx_order_jd', 'name' => '京东', 'pk' => 'order_jd_id', 'field' => 'order_jd_id AS order_id, pay_money AS order_money, pay_money AS pay_money, commission'],
                    9 => ['table' => 'rrx_order_huafei', 'name' => '话费', 'pk' => 'order_huafei_id', 'field' => 'order_huafei_id AS order_id, pay_money AS order_money, pay_money AS pay_money, commission'],
                    10 => ['table' => 'rrx_order_merchant', 'name' => '线下扫码', 'pk' => 'id', 'field' => 'id AS order_id, money AS order_money, money AS pay_money, available AS commission']
                ];

                foreach ($data as $gzcData) {
                    if (!empty($gzcData['link_id']) && !empty($gzcData['bill'])) {
                        $orderTypeMap[$gzcData['bill']['type_shop']][$gzcData['bill']['link_id']][] = $gzcData['id'];

                    }
                }

                if (!empty($orderTypeMap)) {
                    foreach ($orderTypeMap as $orderType => $map) {
                        if (isset($orderMap[$orderType])) {
                            $config = $orderMap[$orderType];
                            $result = Db::table($config['table'])
                                ->whereIn($config['pk'], array_keys($map))
                                ->field($config['field'])
                                ->select()
                                ->toArray();
                            if (!empty($result)) {
                                foreach ($result as $orderData) {
                                    foreach ($map[$orderData['order_id']] as $gzcId) {
                                        if (0 === (int)$orderType && !empty($orderData['mer_id'] ?? '')) {
                                            if ($orderData['mer_id'] == 496) {
                                                $orderData['commission'] = '';
                                                $orderData['source'] = '会员专区';
                                            } else if ($orderData['mer_id'] == 439) {
                                                $orderData['source'] = '精彩生活区';
                                            } else if ($orderData['mer_id'] == 491) {
                                                $orderData['commission'] = '';
                                                $orderData['source'] = '复购区';
                                            } else {
                                                $orderData['source'] = '商贸区';
                                            }
                                        } else {
                                            $orderData['source'] = $orderMap[$orderType]['name'];
                                        }
                                        $orderDetailMap[$gzcId] = $orderData;
                                    }
                                }
                            }
                        }
                    }
                }

                foreach ($data as $item) {
                    $arr[] = [
                        $item['id'],
                        $item['platform_no'],
                        $item['user']['nickname'],
                        $item['user']['account'],
                        $item['user_name'],
                        $item['mobile'],
                        $item['user_card'],
                        $item['bank_name'],
                        $item['branch_name'],
                        $item['bank_account'],
                        $item['bank_no'],
                        $item['alipay_account'],
                        $item['alipay_no'],
                        $item['wxpay_account'],
                        $item['wxpay_no'],
                        $orderDetailMap[$item['id']]['source'] ?? '',
                        $orderDetailMap[$item['id']]['order_money'] ?? '',
                        $orderDetailMap[$item['id']]['commission'] ?? '',
                        $item['out_trade_no'],
                        $item['pension'],
                        $item['gzc'] == 1 ? '已发起' : '待发起',
                        $item['gzc_deposit_no'],
                        $item['gzc_confirm_result'],
                        $item['create_time'],
                        $item['update_time']
                    ];
                }
            }
            return $this->getStatisticsExcel([
                'ID', '平台申请单号', '用户昵称', '用户账号', '实名认证姓名', '实名认证电话', '实名认证证件号', '银行名称', '银行名称', '开户账号', '转账流水号', '支付宝账号', '支付宝流水号', '微信账号', '微信流水号', '订单来源', '订单金额', '订单利润', '关联订单', '养老金', '处理状态', '公证处入账编号', '公证处入账结果', '创建时间', '更新时间'
            ], $arr, '公证处入账明细');
        }

        $query1 = $this->dao->search($where);
        $query2 = $this->dao->search($where);
        $field1 = $query1->field('sum(pension) as count3, count(*) as count1')->where('gzc', 0)->find();
        $field2 = $query2->field('sum(pension) as count4, count(*) as count2')->where('gzc', 1)->find();
        $count = $query->count();
        $list = $query->with('user')->page($page, $limit)->order('id', 'desc')->select();
        $stat = [
            [
                'className' => 'el-icon-s-order',
                'count'     => $field1['count1'],
                'field'     => 'N',
                'name'      => '待发起'
            ],
            [
                'className' => 'el-icon-s-order',
                'count'     => $field2['count2'],
                'field'     => 'N',
                'name'      => '已发起'
            ],
            [
                'className' => 'el-icon-s-order',
                'count'     => $field1['count3'],
                'field'     => 'N',
                'name'      => '待打款金额'
            ],
            [
                'className' => 'el-icon-s-order',
                'count'     => $field2['count4'],
                'field'     => 'N',
                'name'      => '已打款金额'
            ]
        ];
        return compact('count', 'list', 'stat', 'where');
    }

    /**
     * 获取统计导出
     */
    public function getStatisticsExcel($header,$arr,$title)
    {
        $filename = $title.'_'.date('YmdHis').'_'.rand(10000,99999);
        $name = $filename;
        $info = '生成时间:' . date('Y-m-d H:i:s',time());
        $suffix='xlsx';
        $path='extract';
        unset($_instance);

        $_instance = SpreadsheetExcelService::instance_xin();

        $_path =$_instance
            ->createOrActive()
            ->setExcelHeader($header)
            ->setExcelTile($title, $name, $info)
            ->setExcelContent($arr)
            ->excelSave($filename, $suffix, $path);

        $domain = request()->domain();
        $data= [
            'name' => $filename.'.'.$suffix,
            'status' => 1,
            'path' => $domain.'/'.$_path
        ];

        return $data;
    }

    public function inForm()
    {
        $info1 = OrderGzc::getInstance()->where('account_type', 1)->where('pension', '>', 0)->find();
        $info2 = OrderGzc::getInstance()->where('account_type', 2)->where('pension', '>', 0)->find();
        $info3 = OrderGzc::getInstance()->where('account_type', 3)->where('pension', '>', 0)->find();
        $form = Elm::createForm(Route::buildUrl('systemMerchantGzcIn')->build());
        $form->setRule([
            Elm::radio('account_type', '账号类型', $info['account_type'] ?? 1)
                ->setOptions([
                    ['value' => 1, 'label' => '银行卡'],
                    ['value' => 2, 'label' => '支付宝'],
                    ['value' => 3, 'label' => '微信'],
                ]),
            Elm::input('bank_name', '开户银行名称', $info1['bank_name'] ?? ''),
            Elm::input('branch_name', '开户支行名称', $info1['branch_name'] ?? ''),
            Elm::input('bank_account', '开户银行账号', $info1['bank_account'] ?? ''),
            Elm::input('bank_no', '银行转账流水号'),
            Elm::input('alipay_account', '支付宝账号', $info2['alipay_account'] ?? ''),
            Elm::input('alipay_no', '支付宝流水号'),
            Elm::input('wxpay_account', '微信账号', $info3['wxpay_account'] ?? ''),
            Elm::input('wxpay_no', '微信流水号'),
            Elm::dateTime('deposit_dt', '入账时间', Carbon::now()),
        ]);
        return $form->setTitle('发起入账，不同类型，填写不同信息，点击确定即为发起入账');
    }

    public function editForm($id)
    {
        $info = $this->dao->get($id);
        $form = Elm::createForm(Route::buildUrl('systemMerchantGzcEditFormPost')->build());
        $form->setRule([
            Elm::input('id', '记录ID', '')->disabled(true),
            Elm::input('user_name', '实名姓名'),
            Elm::input('mobile', '实名手机号'),
            Elm::input('user_card', '实名证件号'),
            Elm::radio('account_type', '账号类型')
                ->setOptions([
                    ['value' => 1, 'label' => '银行卡'],
                    ['value' => 2, 'label' => '支付宝'],
                    ['value' => 3, 'label' => '微信'],
                ]),
            Elm::input('bank_name', '开户银行名称'),
            Elm::input('branch_name', '开户支行名称'),
            Elm::input('bank_account', '开户银行账号'),
            Elm::input('bank_no', '银行转账流水号'),
            Elm::input('alipay_account', '支付宝账号'),
            Elm::input('alipay_no', '支付宝流水号'),
            Elm::input('wxpay_account', '微信账号'),
            Elm::input('wxpay_no', '微信流水号'),
            Elm::dateTime('deposit_dt', '入账时间'),
        ]);
        return $form->setTitle('编辑信息')->formData($info->toArray());
    }

    /**
     * 组装数据
     * author: php迷途小书童
     * created: 2021/3/20 11:26
     */
    public function buildGzc($log, $params)
    {
        try {
            $depositInfo = [
                'conName'     => $log['user_name'],//消费者姓名
                'conTel'      => $log['mobile'],//消费者电话
                'conCertType' => 1,//消费者证件类型
                'conCertNo'   => $log['user_card'],//消费者证件号
                'conIsAuth'   => 1,//消费者在平台是否已实名
                'amount'      => bcmul($log['pension'], 100),//消费者存入的消费养老金额
                'depositDt'   => $params['deposit_dt'],//入账时间
            ];
            switch ($log['account_type']) {
                case 1:
                    $depositInfo['bankName'] = $params['bank_name'];
                    $depositInfo['branchName'] = $params['branch_name'];
                    $depositInfo['bankAccount'] = $params['bank_account'];
                    $depositInfo['bankPaymentFlow'] = $params['bank_no'];
                    $depositInfo['accountType'] = 1;
                    break;
                case 2:
                    $depositInfo['alipayPaymentAccount'] = $params['alipay_account'];
                    $depositInfo['alipayPaymentFlow'] = $params['alipay_no'];
                    $depositInfo['accountType'] = 2;
                    break;
                case 3:
                    $depositInfo['wechatPaymentAccount'] = $params['wxpay_account'];
                    $depositInfo['wechatPaymentFlow'] = $params['wxpay_no'];
                    $depositInfo['accountType'] = 3;
                    break;
            }
            return $depositInfo;
        } catch (\Throwable $e) {
            Log::info('用户养老金组装数据' . $e->getMessage());
            return ['code' => 500, 'msg' => $e->getMessage()];
        }
    }


    public function register($mobile)
    {
        $thirdKey = "xingfubao";
        $thirdsignKey = "xfb@86868.";
        $time = time();

        $data = [
            'phone'  => $mobile,
            'spread' => ''
        ];

        ksort($data);
        $params = '';
        foreach ($data as $key => $value) {
            $params .= '&' . $key . '=' . $value;
        }
        $params = ltrim($params, '&');
        $sign = strtoupper(md5($params . '&key=' . $thirdKey . '&signKey=' . $thirdsignKey . '&timestamp=' . $time));
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL            => "http://pcpc.bjtdba.com/api/third/register",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => "",
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => "POST",
            CURLOPT_POSTFIELDS     => $data,
            CURLOPT_HTTPHEADER     => [
                "key: $thirdKey",
                "sign: $sign",
                "timestamp: $time"
            ],
        ]);

        $response = curl_exec($curl);

        curl_close($curl);

        $response = json_decode($response, true);
        return $response;
    }




    public function certification($uid, $mobile, $user_name, $user_card, $card_positive, $card_reverse,$cardType,$birthday,$gender,$age)
    {
        $thirdKey = "xingfubao";
        $thirdsignKey = "xfb@86868.";
        $time = time();

        if ($cardType == 1) {
            $data = [
                'uid'  => $uid,
                'mobile' => $mobile,
                'user_name' => $user_name,
                'user_card' => $user_card,
                'card_positive'=> $card_positive,
                'card_reverse'=> $card_reverse,
            ];
        }else{
            $concertType = 0;
            if ($cardType == 2) {
                $concertType = 10;
            }
            if ($cardType == 3) {
                $concertType = 11;
            }
            $data = [
                'uid'  => $uid,
                'mobile' => $mobile,
                'user_name' => $user_name,
                'user_card' => $user_card,
                'card_positive'=> $card_positive,
                'card_reverse'=> $card_reverse,
                'conCertType' => strval($concertType),
                'birthday' => strval($birthday),
                'conSex' => strval($gender),
                'age' => intval($age)
            ];
        }

        ksort($data);
        $params = '';
        foreach ($data as $key => $value) {
            $params .= '&' . $key . '=' . $value;
        }
        $params = ltrim($params, '&');
        $sign = strtoupper(md5($params . '&key=' . $thirdKey . '&signKey=' . $thirdsignKey . '&timestamp=' . $time));
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL            => "http://pcpc.bjtdba.com/api/third/certification",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => "",
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => "POST",
            CURLOPT_POSTFIELDS     => $data,
            CURLOPT_HTTPHEADER     => [
                "key: $thirdKey",
                "sign: $sign",
                "timestamp: $time"
            ],
        ]);

        $response = curl_exec($curl);

        curl_close($curl);

        $response = json_decode($response, true);
        return $response;
    }



    public function gzc($uid, $pension)
    {
        $thirdKey = "xingfubao";
        $thirdsignKey = "xfb@86868.";
        $time = time();

        $data = [
            "uid"     => $uid,
            "pension" => $pension,
        ];


        ksort($data);
        $params = '';
        foreach ($data as $key => $value) {
            $params .= '&' . $key . '=' . $value;
        }
        $params = ltrim($params, '&');
        $sign = strtoupper(md5($params . '&key=' . $thirdKey . '&signKey=' . $thirdsignKey . '&timestamp=' . $time));
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL            => "http://pcpc.bjtdba.com/api/third/gzc",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => "",
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => "POST",
            CURLOPT_POSTFIELDS     => $data,
            CURLOPT_HTTPHEADER     => [
                "key: $thirdKey",
                "sign: $sign",
                "timestamp: $time"
            ],
        ]);

        $response = curl_exec($curl);

        curl_close($curl);

        $response = json_decode($response, true);
        return $response;
    }
}
