<?php

/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\modules\statement\controllers;

use Yii;
use yii\web\ForbiddenHttpException;
use qcbase\models\Auth;
use yii\data\ActiveDataProvider;
use common\components\Tool;
use common\models\Common;
use home\modules\statement\models\StatementAccount;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use common\models\PermissionScope;
use home\models\Attachment;
use yii\helpers\Url;
use home\modules\customer\models\Customer;
use home\modules\statement\models\StatementLink;
use home\modules\statement\models\StatementLinkContract;

/**
 * 对账单导入
 * 
 * @author HuLimin http://blog.u-bo.com
 * @since 0.1
 */
class StatementImportController extends \home\controllers\Controller
{
//    public function actions()
//    {
//        $actions = parent::actions();
//        unset($actions['index']);
//        return $actions;
//    }

    /**
     * 进账单管理列表页
     */
    public function actionImport()
    {
        $this->layout = '//modal';
        return $this->render('import');
    }

    /**
     * 导入映射
     */
    public function actionImportMap()
    {
        if(!Auth::checkAccess('statement/statement-import/import')){
            throw new ForbiddenHttpException('权限不足！');
        }
        $this->layout = '//modal';
        $request = Yii::$app->request;

        $bank_id = $request->post('bank_id');
        $account_no = $request->post('account_no');
        if(empty($bank_id)){
            return $this->flash("请选择收款银行！", 'error');
        }
        if(empty($account_no)){
            return $this->flash("请选择收款账号！", 'error');
        }
        if(empty($_FILES['excel']['tmp_name'])){
            return $this->flash("请选择导入文件！", 'error');
        }
        error_reporting(E_ALL ^ E_NOTICE);
        require Yii::getAlias("@common") . '/components/Reader.php';

        $excel = new \Spreadsheet_Excel_Reader();
        $excel->setOutputEncoding('utf-8');
        $excel->setRowColOffset(0);
        $excel->read($_FILES['excel']['tmp_name']);
        //读取excel标题信息
        $title = $excel->sheets[0]['cells'][0];
        $data['tmp_name'] = '.' . Yii::getAlias('@web') . '/upload/temp/' . time() . rand(0, 9) . ".xls";
        move_uploaded_file($_FILES['excel']['tmp_name'], $data['tmp_name']);

        return $this->render('import-map', [
                    'list' => $title,
                    'rows' => $excel->sheets[0]['numRows'] - 1,
                    'columns' => $excel->sheets[0]['numCols'],
                    'post' => $data,
                    'bank_id' => $bank_id,
                    'account_no' => $account_no
        ]);
    }

    /**
     * 执行导入
     */
    public function actionDoImport()
    {

        $this->layout = '//modal';
        require Yii::getAlias("@common") . '/components/Reader.php';
        $request = Yii::$app->request;
        $filename = $request->post('tmp_name'); //excel上传目录，读取完删除
        $field = ["remittance_user", "remittance_bank", "remittance_no", "account_debit", 'account_credit', 'serial_number', 'payment_time', 'remark'];
        foreach ($field as $value) {
            //将$_POST['field']=value 转换为$map['value']=field,即excel列对应字段的数组
            if(isset($map[$_POST[$value]])){
                //已有字段对应该列，即$map[$_POST[$value]]已被赋值过
                if(is_array($map[$_POST[$value]])){
                    $map[$_POST[$value]][] = $value;
                } else {
                    $map[$_POST[$value]] = array($map[$_POST[$value]], $value);
                }
            } else {
                $map[$_POST[$value]] = $value;
            }
        }
        //读取excel
        $excel = new \Spreadsheet_Excel_Reader();
        $excel->setOutputEncoding('utf-8');
        $excel->setRowColOffset(0); //设置
        $excel->read($filename);
        unlink($filename);
        error_reporting(E_ALL ^ E_NOTICE);
        for ($i = 1; $i < $excel->sheets[0]['numRows']; $i++) {
            for ($j = 0; $j < $excel->sheets[0]['numCols']; $j++) {
                if($map[$j]){
                    if(is_array($map[$j])){
                        //$j列对应多个字段
                        foreach ($map[$j] as $value) {
                            $data[$i][$value] = $excel->sheets[0]['cells'][$i][$j];
                        }
                    } else {
                        $data[$i][$map[$j]] = $excel->sheets[0]['cells'][$i][$j];
                    }
                }
            }
        }
        $bank_id = $request->post('bank_id');
        $account_no = $request->post('account_no');

        //数据库操作
        $type = 0;
        $account_error = 0;
        $account_success = 0;
        $importInfo = [];
        foreach ($data as $key => $value) {
            if((!empty($value['payment_time']) && !empty($value['payment_time'])) && (!empty($value['account_debit']) || !empty($value['account_credit']))){//"account_debit", 'account_credit'
                $model = new StatementAccount();
                $value['bank_id'] = $bank_id;
                $value['account_no'] = $account_no;
                $value['type'] = 1;
                if(strtotime($value['payment_time']) == false){
                    $value['payment_time'] = date("Y-m-d", ($value['payment_time'] - 19 - 70 * 365) * 86400 - 8 * 3600);
                } else {
                    $result = preg_match("/^[0-9]{4}(\-|\/)[0-9]{1,2}(\\1)[0-9]{1,2}(|\s+[0-9]{1,2}(|:[0-9]{1,2}(|:[0-9]{1,2})))$/", $value['payment_time']);
                    if($result == false){
                        $account_error++;
                        $importInfo[$key]['serial_number'] = $value['serial_number'];
                        $importInfo[$key]['status'] = 0;
                        $importInfo[$key]['info'] = "导入失败！日期{$value['payment_time']}格式有误！";
                        continue;
                    }
                }
                $model->setAttributes($value);
                if($model->save()){
                    //导入成功记录
                    $account_success++;
                    $importInfo[$key]['serial_number'] = $value['serial_number'];
                    $importInfo[$key]['status'] = 1;
                    $importInfo[$key]['info'] = '导入成功！';
                } elseif($model->hasErrors()){
                    $account_error++;
                    $importInfo[$key]['serial_number'] = $value['serial_number'];
                    $importInfo[$key]['status'] = 0;
                    $importInfo[$key]['info'] = '导入失败！' . implode(' ', $model->getFirstErrors());
                }
            }
        }
        return $this->render('do-import', [
                    'importInfo' => $importInfo,
                    'account_error' => $account_error,
                    'account_success' => $account_success
        ]);
    }

}
