<?php

namespace Admin\Controller;

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

/**
 * 会长押金管理
 */
class PresidentDepositController extends ThinkController
{
    public function records()
    {
        $page = I('p', 1);
        $row = I('row', 10);
        $companyType = I('company_type');
        $payType = I('pay_type');
        $status = I('status');
        $companyId = I('company_id', 0);

        $where = [
            '_string' => '1=1',
            'company_belong' => ['in', [1, 2]]
        ];
        if ($companyId != 0) {
            $where['id'] = $companyId;
        }
        if ($companyType !== '') {
            $where['_string'] .= ' and company_belong=' . $companyType;
        }

        $depositWhere = [];
        $depositStrWhere = '1=1';

        if ($status !== '') {
            if ($status == '-1') {
                $companyIds = M('president_deposit', 'tab_')->getField('company_id', true);
                if (count($companyIds) > 0) {
                    $depositStrWhere .= ' and company_id not in (' . implode(',', $companyIds) . ')';
                }
            } else {
                $depositWhere['status'] = $status;
            }
        }

        if(I('amount_start', '') != '') {
            $depositStrWhere .= ' and amount >= ' . I('amount_start', '');
        }

        if (I('amount_end', '') != '') {
            $depositStrWhere .= ' and amount <= ' . I('amount_end', '');
        }

        if (I('pay_confirm_time_start', '') != '') {
            $depositStrWhere .= ' and pay_confirm_time>=' . strtotime(I('pay_confirm_time_start') . ' 00:00:00');
        }
        if (I('pay_confirm_time_end', '') != '') {
            $depositStrWhere .= ' and pay_confirm_time<=' . strtotime(I('pay_confirm_time_end') . ' 23:59:59');
        }

        if (I('refund_time_start', '') != '') {
            $depositStrWhere .= ' and refund_time>=' . strtotime(I('refund_time_start') . ' 00:00:00');
        }
        if (I('refund_time_end', '') != '') {
            $depositStrWhere .= ' and refund_time<=' . strtotime(I('refund_time_end') . ' 23:59:59');
        }

        if (I('pay_accept_time_start', '') != '') {
            $depositStrWhere .= ' and pay_accept_time>=' . strtotime(I('pay_accept_time_start') . ' 00:00:00');
        }
        if (I('pay_accept_time_end', '') != '') {
            $depositStrWhere .= ' and pay_accept_time<=' . strtotime(I('pay_accept_time_end') . ' 23:59:59');
        }

        $depositWhere['_string'] = $depositStrWhere;
        if ($payType !== '') {
            $depositWhere['pay_type'] = $payType;
        }

        $subSql = M('president_deposit', 'tab_')->field('company_id')->where($depositWhere)->select(false);
        $where['_string'] .= ' and id in (' . $subSql . ')';

        $query = M('promote_company', 'tab_');

        if (!empty(I('admin_id', 0))) {
            $query->where(['uid' => I('admin_id', 0)]);
        }

        $query = $query->where($where);

        $count = 0;
        $totalQuery = clone $query;
        $companies = [];
        if (I('export', 0) == 1 || $row == 'all') {
            $companies = $query->select();
            $count = count($companies);
        } else {
            $countQuery = clone $query;
            $companies = $query->page($page, $row)->select();
            $count = $countQuery->count();
        }

        // 汇总金额
        if (count($companies) > 0 || (isset($count) && $count > 0)) {
            $total = M('president_deposit', 'tab_')
                ->field('sum(amount) as totalAmount, sum(if(status = 1, amount, 0)) as confirmedAmount, sum(if(status = 2, amount, 0)) as refundedAmount')
                ->where(['company_id'=>['in', $totalQuery->getField('id', true)]])
                ->find();
            $total = [
                'totalamount' => $total['totalamount'] ?? 0, 'confirmedamount' => $total['confirmedamount'] ?? 0, 'refundedamount' => $total['refundedamount'] ?? 0
            ];
        } else {
            $total = [
                'totalamount' => 0, 'confirmedamount' => 0, 'refundedamount' => 0
            ];
        }
        
        $relationQuery = M('president_deposit', 'tab_');
        $companies = $this->mergeOneReletions('presidentDeposit', $companies, $relationQuery, 'id', 'company_id');

        $companyTypes = [
            1 => '外团',
            2 => '外团-分发联盟',
        ];
        $payWays = PresidentDepositService::$payWays;
        $payTypes = PresidentDepositService::$payTypes;
        $statusList = PresidentDepositService::$statusList;

        $records = [];
        if (count($companies) > 0) {
            foreach ($companies as $company) {
                $record = [
                    'id' => $company['id'],
                    'company_name' => $company['company_name'],
                    'company_belong_text' => $companyTypes[$company['company_belong']],
                ];
                if ($company['presidentDeposit']) {
                    $presidentDeposit = $company['presidentDeposit'];
                    if ($presidentDeposit['pay_type'] == PresidentDepositService::PAY_TYPE_NONE) {
                        $record['payer'] = '--';
                        $record['pay_account'] = '--';
                        $record['amount'] = '无';
                    } else {
                        $record['payer'] = $presidentDeposit['payer'];
                        $record['pay_account'] = $presidentDeposit['pay_account'];
                        $record['amount'] = $presidentDeposit['amount'];
                    }
                    $record['pay_type_text'] = $payTypes[$presidentDeposit['pay_type']];
                    $record['pay_way_text'] = $payWays[$presidentDeposit['pay_way']] ?? '--';
                    $record['create_time'] = $presidentDeposit['create_time'] == 0 ? '--' : date('Y-m-d H:i:s', $presidentDeposit['create_time']);
                    $record['verify_time'] = $company['create_time'] != 0 ? date('Y-m-d H:i:s', $company['create_time']) : '--';
                    $record['pay_confirm_time'] = $presidentDeposit['pay_confirm_time'] == 0 ? '--' : date('Y-m-d', $presidentDeposit['pay_confirm_time']);
                    $record['refund_time'] = $presidentDeposit['refund_time'] == 0 ? '--' : date('Y-m-d', $presidentDeposit['refund_time']);
                    $record['pay_accept_time'] = $presidentDeposit['pay_accept_time'] == 0 ? '--' : date('Y-m-d', $presidentDeposit['pay_accept_time']);
                    $record['status_text'] = $statusList[$presidentDeposit['status']];
                    $record['has_record'] = true;
                    $record['status'] = $presidentDeposit['status'];
                    $record['pay_type'] = $presidentDeposit['pay_type'];
                } else {
                    $record['payer'] = '--';
                    $record['pay_account'] = '--';
                    $record['amount'] = '--';
                    $record['pay_type_text'] = '--';
                    $record['pay_way_text'] = '--';
                    $record['create_time'] = '--';
                    $record['verify_time'] = '--';
                    $record['pay_confirm_time'] = '--';
                    $record['refund_time'] = '--';
                    $record['pay_accept_time'] = '--';
                    $record['status_text'] = '市场待确认';
                    $record['has_record'] = false;
                    $record['status'] = 0;
                    $record['pay_type'] = 0;
                }
                $records[] = $record;
            }
            if (I('export', 0) == 1) {
                $field = [
                    'company_name' => '所属推广公司',
                    'account' => '会长账号',
                    'company_belong_text' => '工会类型',
                    'payer' => '退押金账户名',
                    'pay_way_text' => '付款方式',
                    'pay_account' => '退押金账号',
                    'pay_type_text' => '押金类型',
                    'create_time' => '审批时间',
                    'amount' => '押金金额',
                    'verify_time' => '会长申请时间',
                    'status_text' => '押金状态',
                    'pay_confirm_time' => '押金确认时间',
                    'refund_time' => '押金退款时间',
                    'pay_accept_time' => '押金收到时间',
                ];

                addOperationLog(['op_type'=>3,'key'=>getNowDate(),'op_name'=>'导出会长押金记录','url'=>U('PresidentDeposit/records'),'menu'=>'推广员-结算管理-奖罚记录管理-导出会长押金记录']);

                data2csv($records, '会长押金记录', $field);
                exit;
            }
        }
        $this->checkListOrCountAuthRestMap($map,[]);
        $total['unconfirmedamount'] = $total['totalamount'] - $total['confirmedamount'] - $total['refundedamount'];
        $page = set_pagination($count, $row == 'all' ? 99999999 : $row);

        $allCompanies = M('promote_company', 'tab_')->field(['id', 'company_name'])->where(['company_belong' => ['in', [1, 2]]])->select();

        if($page) {
            $this->assign('_page', $page);
        }
        $this->assign('allCompanies', $allCompanies);
        $this->assign('total', $total);
        $this->assign('payWays', $payWays);
        $this->assign('payTypes', $payTypes);
        $this->assign('companyTypes', $companyTypes);
        $this->assign('statusList', $statusList);
        $this->assign('records', $records);
        $this->display();
    }

    private function mergeOneReletions($name, $records, $relationQuery, $selfColumn, $relationColumn = 'id')
    {
        $values = array_column($records, $selfColumn);
        if (count($values) == 0) {
            return [];
        }
        $rows = $relationQuery->where([$relationColumn => ['in', $values]])->select();
        foreach ($records as &$record) {
            $record[$name] = null;
        }
        foreach ($records as &$record) {
            foreach ($rows as $row) {
                if ($record[$selfColumn] == $row[$relationColumn]) {
                    $record[$name] = $row;
                }
            }
        }
        return $records;
    }

    public function edit()
    {
        $this->meta_title = '编辑会长押金';
        $id = I('id', 0);
        $company = M('promote_company', 'tab_')->field(['company_name', 'id'])->where(['id' => $id])->find();
        $record = M('president_deposit', 'tab_')->where(['company_id' => $id])->find();
        $this->assign('payWays', PresidentDepositService::$payWays);
        $this->assign('payTypes', PresidentDepositService::$payTypes);
        $this->assign('company', $company);
        $this->assign('record', $record);
        $this->display('form');
    }

    public function show()
    {
        $this->meta_title = '查看会长押金';
        $id = I('id', 0);
        $company = M('promote_company', 'tab_')->field(['company_name', 'id'])->where(['id' => $id])->find();
        $record = M('president_deposit', 'tab_')->where(['company_id' => $id])->find();
        $this->assign('payWays', PresidentDepositService::$payWays);
        $this->assign('payTypes', PresidentDepositService::$payTypes);
        $this->assign('company', $company);
        $this->assign('record', $record);
        $this->display('show');
    }

    public function save()
    {
        $params = I('post.');
        try {
            $record = M('president_deposit', 'tab_')->where(['company_id' => $id])->find();
            $service = new PresidentDepositService();
            $service->save($params);
            $this->success('保存成功');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function delete()
    {
        if (isMarketAdmin()) {
            $this->ajaxReturn([
                'status' => 0,
                'message' => '无法操作记录'
            ]);
        }
        $promoteId = I('id', 0);
        M('president_deposit', 'tab_')->where(['promote_id' => $promoteId])->delete();

        addOperationLog(['op_type'=>2,'key'=>$promoteId,'op_name'=>'删除会长押金记录','url'=>U('PresidentDeposit/records',['id'=>$promoteId]),'menu'=>'推广员-结算单管理-奖罚记录管理-删除会长押金记录']);

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

    public function noDeposit()
    {
        $id = I('id', 0);
        $company = M('promote_company', 'tab_')->where(['id' => $id])->find();
        if (is_null($company)) {
            $this->ajaxReturn([
                'status' => 0,
                'message' => '推广公司不存在'
            ]);
        }
        try {
            $record = M('president_deposit', 'tab_')->where(['company_id' => $id])->find();
            $service = new PresidentDepositService();
            $service->handleNoDeposit($company, $record);
            $this->ajaxReturn([
                'status' => 1,
                'message' => '操作成功'
            ]);
        } catch (\Exception $e) {
            $this->ajaxReturn([
                'status' => 0,
                'message' => $e->getMessage()
            ]);
        }
    }

    public function refund()
    {
        $ids = I('ids', []);
        try {
            $service = new PresidentDepositService();
            $service->batchRefund($ids);
            $this->ajaxReturn([
                'status' => 1,
                'message' => '操作成功'
            ]);
        } catch (\Exception $e) {
            $this->ajaxReturn([
                'status' => 0,
                'message' => $e->getMessage()
            ]);
        }
    }

    public function payConfirm()
    {
        $ids = I('ids', []);
        $acceptTime = I('accept_time', date('Y-m-d'));
        try {
            $service = new PresidentDepositService();
            $service->batchPayConfirm($ids, $acceptTime);
            $this->ajaxReturn([
                'status' => 1,
                'message' => '操作成功'
            ]);
        } catch (\Exception $e) {
            $this->ajaxReturn([
                'status' => 0,
                'message' => $e->getMessage()
            ]);
        }
    }
}