<?php
namespace app\impexp\controller;

use app\admin\controller\Order;
use app\admin\model\CopyModel;
use app\admin\model\ElectricMeter;
use app\admin\model\ElectricMeterType;
use app\admin\model\OrderModel;
use app\admin\model\PaymentModel;
use app\admin\model\SettleModel;
use app\admin\model\StaffModel;
use app\admin\model\StatementModel;
use think\Exception;

class SaveData
{
    protected $emTypes = []; //电表类型缓存
    protected $staffs = []; //员工数据缓存

    public function importAll($data = [],$copy = false){
        $message = [];
        $sucCount = 0;
        $failCount = 0;
        $start = time();

        foreach ($data as $k => $v){
            $condition = [];

            //抄表单
            $condition['copy'] = [
                'staff_id' => $this->getStaffId($v['A']),    //抄表员
                'em_id' => $this->getEmId($v['B']),          //表号
                'current_number' => $v['C'],                 //当前表数
                'current_time' => $v['D'],        //本期时间
                'current_amount' => $v['E'],                 //本期余额
                'remark' => $v['F']      ,                    //备注
                'photo_id' => 1, //附件填充,
                'create_time' => $start,
                'update_time' => $start
            ];
            $copy_id = $this->addCopy($condition['copy']);

            if($copy_id == 0){
                $message['failMsg'][] = '第 <span style="color:#ff7345">' . $k . '</span>行记录, 电表号是: <span style="color:#f30707">'.$v['B'] .'</span> 不存在';
                $failCount ++ ;
                continue;
            }

                //账单
                $condition['statement'] = [
                    'copy_id' => $copy_id,
                    'emt_id' => $this->getEmType($v['G']),    //电表类型
                    'repo_power' => $v['H'],//报移动电量
                    'yd_unit' => '',       //这是空的 ---------------
                    'financ_unit' => $v['I'],
                    'financ_pay' => $v['J'], //财务支持金额
                    'recharge' => $v['K'],
                    'power_over' => $v['L'],
                    'remark' => $v['M'], //备注
                    'photo_id' => 1, //附件填充,
                    'create_time' => $start,
                    'update_time' => $start
                ];

                $statement = $this->addStatement($condition['statement']);

            if($copy === false){
                //缴费单
                throw new Exception('123123123');
                $condition['payment'] = [
                    'cp_id' => $copy_id,
                    'check_numb' => $v['O'],
                    'invoice_numb' => $v['P'],
                    'pay_sid' => $this->getStaffId($v['Q']),
                    'pay_date' => $v['R'],
                    'tax_rate' => $v['S'],
                    'tax_amount' =>  $v['AA'],
                    'pay_way' => $this->getPayWay($v['T']),
                    'invoice_type' => $this->getInvoiceType($v['U']),
                    'invoice_fid' => 1 //附件填充
                ];

                $payment = $this->addPayment($condition['payment']);

                //结算单
                $condition['settle'] = [
                    'cp_id' => $copy_id,
                    'client' => $this->getClientId($v['V']),
                    'amount' => $v['W'],
                    'settle_date' => $v['X'],
                    'invoice_numb' => $v['Y'],
                    'settle_sid' => $this->getStaffId($v['Z']),
                    'invoice_fid' => '1' //附件填充
                ];

                $settle = $this->addSettle($condition['settle']);

                $condition['order'] = [
                    'order_id' => Order::serial(),
                    'em_id' => $condition['copy']['em_id'],
                    'cp_id' => $copy_id,
                    'statement_id' => $statement->id,
                    'payment_id' => $payment->id,
                    'settle_id' => $settle->id,
                    'settle_status' => $this->getSettleStatus($v['AC']),
                    'settle_time' => $settle->settle_date,
                    'settle_uid' => $settle->settle_sid,
                    'payment_status' => $this->getPaymentStatus($v['AB']),
                    'payment_time' => $payment->pay_date,
                    'payment_uid' => $payment->pay_sid,
                    'status' => $this->getPaySettleStatus($this->getPaymentStatus($v['AB']),$this->getPaymentStatus($v['AC']))
                ];
            } else {
                $condition['order'] = [
                    'order_id' => Order::serial(),
                    'em_id' => $condition['copy']['em_id'],
                    'cp_id' => $copy_id,
                    'statement_id' => $statement->id,
                    'status' => 0,
                    'create_time' => $start,
                    'update_time' => $start
                ];
            }
            $this->addOrder($condition['order']);
            $sucCount ++ ;

        }
        $message['mes'] = '用时'.round((time() - $start) / 60).'导入成功 '.$sucCount.' 条数据 ,导入失败 '.$failCount.' 条数据';
        return $message;
    }


    public function getPaymentStatus($status){
        if($status == '已缴费') return 1;
        else return 0;
    }

    public function getSettleStatus($status){
        if($status == '已结算') return 1;
        else return 0;
    }


    /**
     * 通过 财务支出金额与税率 计算税额
     * @param $financ_pay
     * @param $tax_rate
     * @return float
     */
    public function calculationTaxAmount($financ_pay,$tax_rate){
        $financ_pay =  (int)$financ_pay;
        $tax_rate = $tax_rate / 100;
        return round($financ_pay / (1 + $tax_rate) * $tax_rate, 2);
    }

    /**
     * 通过员名字获取ID
     * @param $staff_name
     * @return mixed
     */
    public function getStaffId($staff_name){
        if(!empty($this->staffs)){
            if(isset($this->staffs[$staff_name]))
                return $this->staffs[$staff_name];
        } else {
            $staffs = StaffModel::field('id,name')->select();
            $temp = [];
            foreach ($staffs as $k => $v){
                $temp[$v['name']] = $v['id'];
            }
            $this->staffs = $temp;
            if(isset($this->staffs[$staff_name]))
                return $this->staffs[$staff_name];
            else
                return '';
        }
    }

    /**
     * 获取发票类型
     * @param $invoice
     * @return int
     */
    public function getInvoiceType($invoice){
        if($invoice == '增值税专用发票'){
            return 1;
        } else {
            return 2;
        }
    }

    /**
     * 获取支付方式
     * @param $payway
     * @return int
     */
    public function getPayWay($payway){
        if(is_numeric($payway)){
            return 1;
        } else if($payway == '电汇'){
            return 2;
        } else {
            return 3;
        }
    }

    //通过 电表号查询电表ID
    public function getEmId($emNumb){
        $em = ElectricMeter::get(['number'=>$emNumb]);
        if($em) return $em->id;
        return '';
    }

    //通过电表类型名称 查询电表类型ID
    public function getEmType($emtName){
        if(!empty($this->emTypes)){
            return $this->emTypes[$emtName];
        } else {
            $emTypes = ElectricMeterType::field('id,name')->select();
            foreach ($emTypes as $k => $v){
                $this->emTypes[$v['name']] = $v['id'];
            }
            return $this->emTypes[$emtName];
        }
    }

    //获取客户类型 移动还是铁塔
    public function getClientId($clientName){
        if($clientName == '移动') return 1;
        else return 2;
    }

    public function addCopy($copyData){
        //查询电表是否存在
        $em = ElectricMeter::find($copyData['em_id']);
        if($em){
            $copyData['em_id'] = $em->id;
            $copy = CopyModel::create($copyData);
            return $copy->id;
        } else {
            return 0;
        }
    }

    public function getPaySettleStatus($payStatus,$settleStatus){
        $payStatus = $this->getPaymentStatus($payStatus);
        $settleStatus = $this->getSettleStatus($settleStatus);

        if($payStatus==1 && $settleStatus == 1){
            return 1;
        } else if($payStatus == 1 && $settleStatus == 0){
            return 2;
        } else if($payStatus == 0 && $settleStatus == 1){
            return 3;
        } else {
            return 0;
        }
    }

    public function addStatement($statementData){
        return StatementModel::create($statementData);
    }
    public function addPayment($paymentData){
        return PaymentModel::create($paymentData);
    }
    public function addSettle($settleData){
        return SettleModel::create($settleData);
    }

    public function addOrder($oderData){
        return OrderModel::create($oderData);
    }
}