<?php
namespace app\common\controller;
use think\facade\View;
use think\facade\Db;
use app\common\variable\MsgCode;
use app\common\validate\Invoice as InvoiceValidate;
use think\exception\ValidateException;
use app\common\model\UserInvoice as UserInvoiceModel;
use app\common\model\UserMailAddress as UserMailAddressModel;
use app\common\model\Orders as OrdersModel;
use app\common\model\Invoice as InvoiceModel;
use app\common\model\InvoiceInfo as InvoiceInfoModel;
use app\common\model\InvoiceMailAddress as InvoiceMailAddressModel;
/**
 * 
 */
class Invoice extends Base
{
    public static function saveInvoiceTitle($D)
    {
        /**
         * 发票抬头验证
         */
        try {
            validate(InvoiceValidate::class)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(),MsgCode::$error);
        }
        $UserInvoiceModel=UserInvoiceModel::where(['uid'=>$D['uid']])->find();
        if (!$UserInvoiceModel)
            $UserInvoiceModel=new UserInvoiceModel;
        $UserInvoiceModel->uid                  =   $D['uid'];
        $UserInvoiceModel->type                 =   $D['type'];
        if($D['type']){
            $UserInvoiceModel->invoice_title        =   $D['invoice_title'];
        }else{
            $UserInvoiceModel->invoice_title        =   empty($D['invoice_title'])?'个人':$D['invoice_title'];
        }
        $UserInvoiceModel->invoice_type         =   $D['invoice_type'];
        $UserInvoiceModel->invoice_uscc         =   $D['invoice_uscc'];
        $UserInvoiceModel->bank_of_deposit      =   $D['bank_of_deposit'];
        $UserInvoiceModel->basic_deposit_account=   $D['basic_deposit_account'];
        $UserInvoiceModel->reg_address          =   $D['reg_address'];
        $UserInvoiceModel->reg_tel              =   $D['reg_tel'];

        /*发展历程*/
        $UserMailAddressList=[];
        if (!empty($D['mail_address'])) {
            $UserMailAddressModel=new UserMailAddressModel;
            foreach ($D['mail_address'] as $k => $v) {
                $UserMailAddressList[$k]=[
                    'uid'            =>  $D['uid'],
                    'name'           =>  $v['name'],
                    'area1'          =>  $v['area'][0],
                    'area2'          =>  $v['area'][1],
                    'area3'          =>  $v['area'][2],
                    'address'        =>  $v['address'],
                    'mobile'         =>  $v['mobile'],
                    'postcode'       =>  $v['postcode'],
                    'is_default'     =>  $v['is_default'],
                ];
                if ($v['id'])
                    $UserMailAddressList[$k]['id']=$v['id'];
            }
        }
        $isDefault=UserMailAddressModel::where(['uid'=>$D['uid'],'is_default'=>1])->find();
        // 启动事务
        Db::startTrans();
        try {
            $UserInvoiceModel->save();
            if ($isDefault)$isDefault->save();
            if (!empty($UserMailAddressList)) $UserMailAddressModel->saveAll($UserMailAddressList);
            // 提交事务
            Db::commit();
            return parent::ajaxReturn('已保存',MsgCode::$success,self::getInvoice($D['uid']));
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }
    }
    public static function getInvoice($uid)
    {
        $UserInvoiceModel=UserInvoiceModel::where(['uid'=>$uid])->find();
        if ($UserInvoiceModel) {
            $Data=UserMailAddressModel::where(['uid'=>$uid])->select()->toArray();
            foreach ($Data as $k => $v) {
                $Data[$k]['area']=[$v['area1'],$v['area2'],$v['area3']];
            }
            $UserInvoiceModel->mail_address=$Data;
            $UserInvoiceModel->default_address_id=0;
            $default_address=self::getUserMailAddressDefaultId($uid);
            if ($default_address)
                $UserInvoiceModel->default_address_id=$default_address->id;
        }
        return $UserInvoiceModel;
    }
    public static function getUserMailAddressDefaultId($uid)
    {
        $default_address_id=UserMailAddressModel::where(['uid'=>$uid,'is_default'=>1])->find();
        if (!$default_address_id)
            $default_address_id=UserMailAddressModel::where(['uid'=>$uid])->order('id desc')->find();
        return $default_address_id;
    }
    public static function applyInvoice($D)
    {
        if (!config('xy_invoice.invoice_status'))
            return parent::ajaxReturn('未开启发票索取',MsgCode::$error);
        $where=[];
        $where[]=['uid','=',$D['uid']];
        $where[]=['invoice_status','=',0];
        $where[]=['status','=',2];
        $where[]=['pay_type','in',[1,2,3]];
        $order=null;
        $price=0;
        if (!empty($D['all_selected']) && $D['all_selected']) {
            $order=OrdersModel::where($where)->whereNull('delete_time')->field('')->column('oid');
            $price=OrdersModel::where($where)->whereNull('delete_time')->sum('oprice');
        }else if(!empty($D['oid']) && count($D['oid'])>0){
            $where[]=['oid','in',$D['oid']];
            $order=OrdersModel::where($where)->whereNull('delete_time')->field('')->column('oid');
            $price=OrdersModel::where($where)->whereNull('delete_time')->sum('oprice');
        }else{
            return parent::ajaxReturn('请先选择需要开票的订单',MsgCode::$error);
        }
        if (!$order || !$price)
            return parent::ajaxReturn('暂无可开票的订单',MsgCode::$error);
        if ($price<config('xy_invoice.invoice_min_price'))
            return parent::ajaxReturn('开票总额小于'.config('xy_invoice.invoice_min_price').'元',MsgCode::$error);
        $UserInvoice=UserInvoiceModel::where(['uid'=>$D['uid']])->find();
        if (!$UserInvoice)
            return parent::ajaxReturn('请先创建发票抬头',MsgCode::$error);
        $address=UserMailAddressModel::where(['id'=>$D['address_id']])->find();
        if (!$address)
            return parent::ajaxReturn('请先创建邮寄地址',MsgCode::$error);
        $InvoiceModel=new InvoiceModel;
        $InvoiceModel->uid      =   $D['uid'];
        $InvoiceModel->price    =   round($price,2);
        $InvoiceModel->oid      =   implode(',', $order);
        $InvoiceModel->order_sum=   count($order);

        $InvoiceInfoModel=new InvoiceInfoModel;
        $InvoiceInfoModel->type                 =   $UserInvoice->type;
        $InvoiceInfoModel->invoice_title        =   $UserInvoice->invoice_title;
        $InvoiceInfoModel->invoice_type         =   $UserInvoice->invoice_type;
        $InvoiceInfoModel->invoice_uscc         =   $UserInvoice->invoice_uscc;
        $InvoiceInfoModel->bank_of_deposit      =   $UserInvoice->bank_of_deposit;
        $InvoiceInfoModel->basic_deposit_account=   $UserInvoice->basic_deposit_account;
        $InvoiceInfoModel->reg_address          =   $UserInvoice->reg_address;
        $InvoiceInfoModel->reg_tel              =   $UserInvoice->reg_tel;

        $InvoiceMailAddressModel=new InvoiceMailAddressModel;
        $InvoiceMailAddressModel->name      =   $address->name;
        $InvoiceMailAddressModel->area1     =   $address->area1;
        $InvoiceMailAddressModel->area2     =   $address->area2;
        $InvoiceMailAddressModel->area3     =   $address->area3;
        $InvoiceMailAddressModel->address   =   $address->address;
        $InvoiceMailAddressModel->mobile    =   $address->mobile;
        $InvoiceMailAddressModel->postcode  =   $address->postcode;
        // 启动事务
        Db::startTrans();
        try {
            $InvoiceModel->save();
            $InvoiceInfoModel->iid=$InvoiceModel->id;
            $InvoiceMailAddressModel->iid=$InvoiceModel->id;
            $InvoiceInfoModel->save();
            $InvoiceMailAddressModel->save();
            OrdersModel::where('oid','in',$order)->update(['invoice_status'=>1]);
            // 提交事务
            Db::commit();
            return parent::ajaxReturn('申请成功，请等待开票');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('申请失败，请重试',MsgCode::$error);
        }
    }
    public static function getPage($uid)
    {
        $where=[];
        $where[]=['i.uid','=',$uid];
        $Data=InvoiceModel::alias('i')->where($where)
            ->join('invoice_info info','info.iid=i.id')
            ->join('invoice_mail_address address','address.iid = i.id')
            ->join('area area1','area1.id = address.area1')
            ->join('area area2','area2.id = address.area2')
            ->join('area area3','area3.id = address.area3')
            ->field('i.*,info.type,info.invoice_title,info.invoice_type,info.invoice_uscc,info.bank_of_deposit,info.basic_deposit_account,info.reg_address,info.reg_tel,address.name,address.name,address.area1,address.area2,address.area3,address.address,address.mobile,address.postcode,area1.title as area1_text,area2.title as area2_text,area3.title as area3_text')
            ->order('id desc')->paginate(15)->each(function($v){
                return $v;
            });
        if ($Data->items()) {
            return parent::ajaxReturn('',0,$Data);
        }else{
            return parent::ajaxReturn('暂无数据~',MsgCode::$error);
        }
    }
}