<?php

namespace Admin\Controller;

use User\Api\UserApi as UserApi;
use Think\Model;

/**
 * 支付/付款商户
 */
class TransferMerchantController extends ThinkController
{
    public $TransferMerchant;
    public function __construct()
    {
        $this->TransferMerchant = D("TransferMerchant");
        parent::__construct();
    }
    public function lists()
    {
        $this->assign('statementPaymentInfo', $this->TransferMerchant->getStatementPaymentInfo());
        $this->assign('underPaymentInfo', $this->TransferMerchant->getUnderPaymentInfo());
        $this->display();
    }

    public function edit()
    {
        $ways = I('ways', 0);
        if ($ways == 0) {
            $this->error('参数错误');
        }
        $info = [];
        if($ways == 1){
            $info = $this->TransferMerchant->getStatementPaymentInfo();
        }elseif($ways == 2){
            $info = $this->TransferMerchant->getUnderPaymentInfo();
        }else {
            $this->error('参数错误');
        }

        $allaccount = $this->TransferMerchant->getField("id,account,name,main_name,is_free,config");
        foreach ($allaccount as $key => &$val) {
            $config = json_decode($val["config"],true);
            foreach ($config as $k => $v) {
                $val[$k] = $v;
            }
            unset($val["config"]);
            $val['is_free_str'] = $this->TransferMerchant::IS_FREE_STR[$val['is_free']];
        }

        $way_str = $this->TransferMerchant::WAY_STR[$ways];
        $this->meta_title = $way_str."设置";
        $this->assign('allaccount', $allaccount);
        $this->assign('ways',$ways);
        $this->assign('info',$info);
        $this->assign('way_str', $way_str);

        $this->display('form');
    }



    public function save()
    {
        $id = I('id', 0);
        $ways = I('ways',0);
        if(empty($id) || empty($ways) || !in_array($ways,[1,2])){
            $this->ajaxReturn([
                'status' => 0,
                'message' => '参数错误'
            ]);
        }

        if($ways == 1){
            $info = $this->TransferMerchant->getStatementPaymentInfo();
        }
        if($ways == 2){
            $info = $this->TransferMerchant->getUnderPaymentInfo();
        }

        if($info['id'] != $id){
            $idinfo = $this->TransferMerchant->field("id,ways")->where("id = {$id}")->find();
            $idsave = [
                'id'=>$id,
                'ways'=>$idinfo['ways']-0+$ways,
                'update_time'=>time()
            ];
            $this->TransferMerchant->save($idsave);
            //修改之前的
            $infosave = [
                'id'=>$info['id'],
                'ways'=>$info['ways']-$ways,
                'update_time'=>time()
            ];
            $this->TransferMerchant->save($infosave);
        }

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


}