<?php
namespace Base\Service;

use Base\Facade\Request;

class PromoteCompanyService
{
    const BELONG_INSIDE = 0;
    const BELONG_OUTSIDE = 1;
    const BELONG_OUTSIDE_SP = 2;
    const BELONG_NONE = 3;

    public static $belongs = [
        0 => '内团',
        1 => '外团',
        2 => '外团-分发',
        3 => '无',
    ];

    const TYPE_NORMAL = 0;  // 默认推广公司
    const TYPE_CUSTOM = 1;  // 定制推广公司 隐藏某些功能

    public function getOutBelongs()
    {
        return [
            self::BELONG_OUTSIDE => self::$belongs[self::BELONG_OUTSIDE],
            self::BELONG_OUTSIDE_SP => self::$belongs[self::BELONG_OUTSIDE_SP],
        ];
    }

    public function getCompanies(array $ids = null, $fields = '*')
    {
        $map = [];
        if (is_null($ids)) {
            $map['_string'] = '1=1';
        } elseif (count($ids) == 0) {
            return [];
        } else {
            $map['id'] = ['in', $ids];
        }
        $rules = M('promote_company', 'tab_')->field($fields)->where($map)->select();
        return index_by_column('id', $rules);
    }

    public function getCompaniesByBelong($belong = null, $fields = '*')
    {
        $map = [];
        if (is_null($belong)) {
            $map['_string'] = '1=1';
        } else {
            $map['company_belong'] = $belong;
        }
        $rules = M('promote_company', 'tab_')->field($fields)->where($map)->select();
        return index_by_column('id', $rules);
    }

    public function checkPromotes($promotes, $exceptId = 0)
    {
        if (count($promotes) == 0) {
            return;
        }
        foreach ($promotes as $promote) {
            if (empty($promote['account'])) {
                throw new \Exception('请输入会长账号');
            }
            if (strlen($promote['account']) > 15 || strlen($promote['account']) < 6) {
                throw new \Exception('会长账号长度为6-15个字符');
            }

            if (!preg_match("/^[a-zA-Z0-9_\.]+$/", $promote['account'])) {
                throw new \Exception('会长账号只能为数字,字母和下划线');
            }
            if (!empty($promote['mobile_phone'])) {
                if (!preg_match("/^1[3456789]{1}\d{9}$/", $promote['mobile_phone'])) {
                    throw new \Exception('会长手机号格式错误');
                }
            }
            if (!empty($promote['real_name'])) {
                if (mb_strlen($promote['real_name']) < 2 || mb_strlen($promote['real_name']) > 4) {
                    throw new \Exception('会长姓名只能为2-4个字符');
                }
            }
        }

        $accounts = array_column($promotes, 'account');
        $mobiles = array_column($promotes, 'mobile_phone');

        if (count($accounts) != count(array_unique($accounts))) {
            throw new \Exception('会长含有相同账号');
        }

        foreach ($mobiles as $key => $value) {
            if ($value == '') {
                unset($mobiles[$key]);
            }
        }
        if (count($mobiles) != count(array_unique($mobiles))) {
            throw new \Exception('会长含有相同手机号');
        }
        $existPromote = M('promote', 'tab_')->field('id')->where(['account' => ['in', $accounts]])->find();
        if ($existPromote) {
            throw new \Exception('会长账号已存在');
        }
        if (count($mobiles) > 0) {
            $existPromote = M('promote', 'tab_')->field('id')->where(['mobile_phone' => ['in', $mobiles]])->find();
            if ($existPromote) {
                throw new \Exception('会长手机号已存在');
            }
        }
        $verifyingPromotes = $this->getVerifyingPromotes($exceptId);
        if ($this->isExistVerifyingPromoteAccount($accounts, $verifyingPromotes)) {
            throw new \Exception('会长账号已存在');
        }
        if ($this->isExistVerifyingPromoteAccount($mobiles, $verifyingPromotes)) {
            throw new \Exception('会长手机号已存在');
        }
    }

    public function isExistVerifyingPromoteAccount($accounts, $verifyingPromotes)
    {
        $verifyingAccounts = array_column($verifyingPromotes, 'account');
        $sameAccounts = array_intersect($accounts, $verifyingAccounts);
        return count($sameAccounts) > 0;
    }

    public function isExistVerifyingPromoteMobile($mobiles, $verifyingPromotes)
    {
        $verifyingMobiles = array_unique(array_column($verifyingPromotes, 'mobile'));
        $sameMobiles = array_intersect($mobiles, $verifyingMobiles);
        return count($sameMobiles) > 0;
    }

    public function getVerifyingPromotes($exceptId = 0)
    {
        $promotes = [];
        $verifyCompanies = M('promote_company_verify', 'tab_')->field(['company_info'])->where(['verify_status' => ['in', [0, 1]]])->getField('company_info', true);
        if ($verifyCompanies) {
            foreach ($verifyCompanies as $item) {
                $row = json_decode($item, true);
                if (isset($row['promotes'])) {
                    $promotes = array_merge($promotes, $row['promotes']);
                }
            }
        }
        return $promotes;
    }

    public function checkCompanyRelation($params)
    {
        if (empty($params['self_company_id'])) {
            throw new \Exception('请选择己方公司');
        }
    }

    public function adminAgree($application, $isAuto = false)
    {
        $adminInfo = $_SESSION['onethink_admin']['user_auth'];
        $verifyLog = json_decode($application['verify_log'], true);
        $verifyLog['admin_user'] = $isAuto ? 'AUOT' : $adminInfo["username"];
        $verifyLog['admin_time'] = date("Y-m-d H:i:s");
        $application['verify_log'] = json_encode($verifyLog);
        $application['verify_status'] = 2;
        $application["create_time"] = time();
        $companyInfo = json_decode($application['company_info'], true);
        
        $creator = M('ucenter_member', 'sys_')->field(['id', 'username'])->where(['username' => $verifyLog['create_user']])->find();

        $deposit = null;
        $bindRelation = $companyInfo['relation'];
        $promotes = $companyInfo['promotes'];
        if (isset($companyInfo['deposit'])) {
            $deposit = $companyInfo['deposit'];
            unset($companyInfo['deposit']);
        }
        unset($companyInfo['relation']);
        unset($companyInfo['promotes']);

        $companyInfo['site_config'] = json_encode($companyInfo['site_config']);

        $isNewDeposit = false;
        if($application['company_id'] == 0){
            //新增
            $isNewDeposit = true;
            $application['company_id'] = $companyInfo['id'] = M('promote_company', 'tab_')->add($companyInfo);
        }else{
            //编辑
            $oldInfo = M('promote_company', 'tab_')->field(['id', 'company_belong', 'develop_type', 'game_ids'])->where(['id' => $application['company_id']])->find();
            /** 内团/无 切换为外团 */
            if (in_array($companyInfo['company_belong'], [1, 2]) && !in_array($oldInfo['company_belong'], [1, 2])) {
                $isNewDeposit = true;
            }

            M('promote_company', 'tab_')->save($companyInfo);
            $this->changePromote($companyInfo, $oldInfo);
        }

        $this->savePromoteCompanyRelation($bindRelation, $companyInfo);
        $this->savePromotes($promotes, $companyInfo, $creator);
        if ($isNewDeposit && in_array($companyInfo['company_belong'], [1, 2])) {
            $depositService = new PresidentDepositService();
            $depositService->save($deposit, $companyInfo);
        }

        //业务逻辑
        M('PromoteCompanyVerify', 'tab_')->save($application);
        addOperationLog(['op_type'=>1, 'key' => $application['id'], 'op_name'=>'管理员审核', 'url'=>U('index')]);
    }

    protected function savePromoteCompanyRelation($bindRelation, $company)
    {
        $selfCompany = M('company_info', 'tab_')->where(['id' => $bindRelation['self_company_id']])->find();
        $where = '(first_company_type=2 and first_company_id=' . $company['id'] .
            ') or (second_company_type=2 and second_company_id=' . $company['id'] . ')';
        $relation =  M('company_relation', 'tab_')->where($where)->find();

        $data = [];
        if ($bindRelation['collaborate_way'] == 1) {
            $data['first_company_id'] = $company['id'];
            $data['first_company_name'] = $company['company_name'];
            $data['first_company_type'] = 2;
            $data['second_company_id'] = $selfCompany['id'];
            $data['second_company_name'] = $selfCompany['partner'];
            $data['second_company_type'] = 0;
        } else {
            $data['first_company_id'] = $selfCompany['id'];
            $data['first_company_name'] = $selfCompany['partner'];
            $data['first_company_type'] = 0;
            $data['second_company_id'] = $company['id'];
            $data['second_company_name'] = $company['company_name'];
            $data['second_company_type'] = 2;
        }

        $data['settlement_type'] = $bindRelation['settlement_type'];
        $data['invoice_type'] = $bindRelation['invoice_type'];
        $data['collection'] = $bindRelation['collection'];
        $data['is_payment'] = $bindRelation['is_payment'];
        $data['invoice_content'] = $bindRelation['invoice_content'];
        if ($relation) {
            M('company_relation', 'tab_')->where(['id' => $relation['id']])->save($data);
        } else {
            M('company_relation', 'tab_')->add($data);
        }
    }

    protected function changePromote($companyInfo, $oldInfo)
    {
        $isChangeBelong = false;
        $isChangeRelation =false;

        if(empty($companyInfo['id'])){
            return;
        }

        $companyId = $companyInfo['id'];
        // $oldInfo = M('promote_company', 'tab_')->field('company_belong,develop_type,game_ids')->where(['id' => $companyId])->find();

        if(isset($companyInfo['company_belong']) && ($oldInfo['company_belong'] != $companyInfo['company_belong'])){
            $isChangeBelong = true;
        }

        if(isset($companyInfo['develop_type']) && ($oldInfo['develop_type'] != $companyInfo['develop_type'])){
            $isChangeRelation = true;
        }
        //处理底下所有会长的公会属性
        if($isChangeBelong ||  $isChangeRelation ) {
            
            $data = array(
                'company_belong' => $companyInfo['company_belong'],
                'company_relation' => $companyInfo['develop_type']
            );
            M('promote', 'tab_')->where(['company_id' => $companyId])->save($data);

            // 权限跟随
            if($isChangeBelong){

                $subPromoteIds = M('promote', 'tab_')->where(['level' => 1, 'company_id' => $companyId])->getField('id', true);
                if ($companyInfo['company_belong'] == 1 || $companyInfo['company_belong'] == 2) {
                    A("Market","Event")->pushPresident($subPromoteIds);
                } else {
                    A("Market","Event")->removePresident($subPromoteIds);
                }
                resetUserAuth();
            }
        }
    }

    private function savePromotes($records, $company, $creator)
    {
        $status = 1;
        /* if (C('PROMOTE_AUTO_AUDIT') == 1) {
            $status = 1;
        } */
        $promoteService = new PromoteService();
        foreach ($records as $record) {
            $promoteService->addPromote([
                'account' => $record['account'],
                'password' => $record['password'],
                'real_name' => $record['real_name'],
                'status' => $status,
                'email' => $record['email'],
                'mobile_phone' => $record['mobile_phone'],
                'can_view_recharge' => $record['can_view_recharge'],
                'company_id' => $company['id'],
                'company_belong' => $company['company_belong'],
                'company_relation' => $company['develop_type'],
                'admin_id' => $creator ? $creator['id'] : 0,
            ]);
        }
    }

    public function marketAgree($application, $isAuto = false)
    {
        $adminInfo = $_SESSION['onethink_admin']['user_auth'];
        $application['verify_log'] = json_decode($application['verify_log'],true);
        $application['verify_log']['market_user']= $isAuto ? 'AUOT' : $adminInfo["username"];
        $application['verify_log']['market_time'] = date("Y-m-d H:i:s");
        $application['verify_log'] = json_encode($application['verify_log']);
        $application['verify_status'] = 1;
        $application["create_time"] = time();
        M('promote_company_verify', 'tab_')->where(['id' => $application['id']])->save($application);
        addOperationLog(['op_type'=>1, 'key'=> $application['id'], "op_name"=>"市场部审核", 'url'=>U('index')]);
        return $application;
    }
}