<?php

namespace Admin\Controller;

use User\Api\UserApi as UserApi;
use Base\Service\PresidentDepositService;
use Base\Service\PromoteCompanyService;

/**
 * 推广限制
 */
class PromoteLimitRuleController extends ThinkController
{
    public function records()
    {
        $page = I('p', 1);
        $row = I('row', 10);
        $companyId = I('company_id', 0);
        $promoteId = I('promote_id', 0);

        $conditions = [];
        $promoteIds = [];
        if ($promoteId !== 0) {
            $promoteIds = [$promoteId];
        }
        if ($companyId !== 0) {
            $companyPromoteIds = M('promote', 'tab_')->field(['id'])->where(['company_id' => $companyId, 'level' => 1])->getField('id', true);
            if (count($companyPromoteIds) > 0) {
                $promoteIds = count($promoteIds) ? array_intersect($companyPromoteIds, $promoteIds) : $companyPromoteIds;
                $promoteIds[] = 0;
            } else {
                $promoteIds = [0];
            }
        }
        if (count($promoteIds)) {
            $conditions['promote_id'] = ['in', $promoteIds];
        }
        $query = M('promote_limit_rules', 'tab_')->where($conditions);

        $countQuery = clone $query;
        $rules = $query->page($page, $row)->select();
        $count = $countQuery->count();

        $recordPromotes = [];
        $recordCompanys = [];
        if (count($rules) > 0) {
            $recordPromotes = M('promote', 'tab_')->field(['id', 'account', 'company_id'])->where(['id' => ['in', array_column($rules, 'promote_id')]])->select();
            $recordCompanyIds = array_column($recordPromotes, 'company_id');
            if (count($recordCompanyIds) > 0) {
                $recordCompanys = M('promote_company', 'tab_')->field(['id', 'company_name', 'company_belong'])->where(['id' => ['in', $recordCompanyIds]])->select();
            }
            $recordPromotes = index_by_column('id', $recordPromotes);
            $recordCompanys = index_by_column('id', $recordCompanys);
        }

        
        $companyTypes = PromoteCompanyService::$belongs;

        $records = [];
        foreach ($rules as $rule) {
            $records[] = [
                'id' => $rule['id'],
                'promote_account' => $recordPromotes[$rule['promote_id']]['account'],
                'company_name' => $recordCompanys[$recordPromotes[$rule['promote_id']]['company_id']]['company_name'],
                'company_belong' => $companyTypes[$recordCompanys[$recordPromotes[$rule['promote_id']]['company_id']]['company_belong']],
                'limit_rule' => $this->getDisplayRule($rule),
            ];
        }
        $companys = M('promote_company', 'tab_')->field(['id', 'company_name'])->select();

        $page = set_pagination($count, $row);
        if($page) {
            $this->assign('_page', $page);
        }
        $this->assign('records', $records);
        $this->assign('companys', $companys);
        $this->display();
    }

    private function getDisplayRule($rule)
    {
        if ($rule['started_at'] === null && $rule['ended_at'] === null) {
            return '永久';
        } elseif ($rule['started_at'] === null && $rule['ended_at'] !== null) {
            return  '从前 至 '.$rule['ended_at'];
        } elseif ($rule['started_at'] !== null && $rule['ended_at'] === null) {
            return $rule['started_at'] . ' 至 永久';
        } else {
            return  $rule['started_at'] . ' ~ ' . $rule['ended_at'];
        }
    }

    public function edit()
    {
        $this->meta_title = '编辑推广限制';
        $id = I('id', 0);
        $companys = M('promote_company', 'tab_')->field(['id', 'company_name'])->select();
        $record = M('promote_limit_rules', 'tab_')->where(['id' => $id])->find();
        $promote = null;
        $company = null;
        if ($record) {
            $promote = M('promote', 'tab_')->where(['id' => $record['promote_id']])->field(['id', 'company_id', 'account'])->find();
            $company = M('promote_company', 'tab_')->where(['id' => $promote['company_id']])->field(['id', 'company_name'])->find();
        }
        $this->assign('promote', $promote);
        $this->assign('company', $company);
        $this->assign('companys', $companys);
        $this->assign('record', $record);
        $this->display('form');
    }

    public function save()
    {
        $id = I('id', 0);
        $promoteId = I('promote_id', 0);
        $startedAt = I('started_at', '');
        $endedAt = I('ended_at', '');

        $startedAt = $startedAt === '' ? null : $startedAt;
        $endedAt = $endedAt === '' ? null : $endedAt;

        if ($startedAt && $endedAt && strtotime($startedAt) > strtotime($endedAt)) {
            return $this->error('开始时间不能大于结束时间');
        }

        $record = null;
        if ($id > 0) {
            $record = M('promote_limit_rules', 'tab_')->where(['id' => $id])->find();
            if (!$record) {
                return $this->error('修改记录不存在');
            }
        } else {
            if (empty($promoteId)) {
                return $this->error('请选择会长');
            }
            $promoteRecord = M('promote_limit_rules', 'tab_')->where(['promote_id' => $promoteId])->find();
            if ($promoteRecord) {
                return $this->error('该会长已经设定限制规则,请前往更新');
            }
        }

        if ($record) {
            $data = [];
            $data['started_at'] = $startedAt;
            $data['ended_at'] = $endedAt;
            $data['update_time'] = time();
            M('promote_limit_rules', 'tab_')->where(['id' => $id])->save($data);
            addOperationLog([
                'op_type' => 1,
                'key'=> $promoteId . '/' . $startedAt . '/' . $endedAt,
                'op_name' => '修改推广限制',
                'url' => U('PresidentDeposit/edit', ['id'=>$id]), 'menu'=>'推广员-推广员管理-推广限制-修改推广限制'
            ]);
        } else {
            $data = [];
            $data['promote_id'] = $promoteId;
            $data['started_at'] = $startedAt;
            $data['ended_at'] = $endedAt;
            $data['create_time'] = time();
            $data['update_time'] = time();
            M('promote_limit_rules', 'tab_')->add($data);
            addOperationLog([
                'op_type' => 0,
                'key'=> $promoteId . '/' . $startedAt . '/' . $endedAt,
                'op_name' => '新增推广限制',
                'url' => U('PresidentDeposit/edit', ['promote_id'=>$promoteId]), 'menu'=>'推广员-推广员管理-推广限制-新增推广限制'
            ]);
        }

        return $this->success('保存成功', U('records'));
    }

    public function delete()
    {
        $id = I('id', 0);
        M('promote_limit_rules', 'tab_')->where(['id' => $id])->delete();

        addOperationLog([
            'op_type' => 2,
            'key' => $id,
            'op_name' => '删除会长推广限制',
            'url' => U('PresidentDeposit/delete', ['id' => $id]),
            'menu' => '推广员-推广员管理-推广限制-删除推广限制'
        ]);

        $this->ajaxReturn([
            'status' => 1,
            'message' => '删除成功'
        ]);
    }

    public function batchDelete()
    {
        $ids = I('ids', []);
        if (count($ids) == 0) {
            $this->ajaxReturn([
                'status' => 0,
                'message' => '无选中项'
            ]);
        }
        M('promote_limit_rules', 'tab_')->where(['id' => ['in', $ids]])->delete();

        addOperationLog([
            'op_type' => 2,
            'key' => implode(',', $ids),
            'op_name' => '批量删除会长推广限制',
            'url' => U('PresidentDeposit/batchDelete', ['ids' => implode(',', $ids)]),
            'menu' => '推广员-推广员管理-推广限制-批量删除推广限制'
        ]);

        $this->ajaxReturn([
            'status' => 1,
            'message' => '删除成功'
        ]);
    }

    public function getPromotesByCompany()
    {
        $companyId = I('company_id', 0);
        $promotes = M('promote', 'tab_')->field(['id', 'account'])->where(['level' => 1, 'company_id' => $companyId])->select();

        $this->ajaxReturn([
            'status' => 1,
            'message' => '获取成功',
            'data' => [
                'promotes' => $promotes
            ]
        ]);
    }
}