<?php
/**
 * Created by PhpStorm.
 * User: 86132
 * Date: 2020/7/17
 * Time: 14:36
 */

namespace app\api\controller;


use app\common\controller\Api;
use think\Db;

/**
 * 发票接口
 */
class Invoice extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * @ApiTitle    (发票接口-填写发票资料)
     * @ApiSummary  (填写发票资料)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Invoice/ApplyForProfessionalInvoice)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="invoice_head", type="string", required=false, description="发票抬头")
     * @ApiParams   (name="invoice_people", type="string", required=true, description="收票人")
     * @ApiParams   (name="mobile", type="int", required=true, description="手机号码")
     * @ApiParams   (name="address", type="string", required=true, description="收票地址")
     * @ApiParams   (name="address_con", type="string", required=true, description="详细地址")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": "1"
    })
     */
    public function ApplyForProfessionalInvoice()
    {
        $user_id = $this->is_token($this->request->header());
        $param = $this->request->param();
        $selectedOptionszero = input('data');
        $arr = json_decode(htmlspecialchars_decode($selectedOptionszero), true);
        $str = implode($arr, ',');
//        if ($param['type'] == 1) {
//            $is_company = Db::name('company')->where(['company_holder' => $user_id])->find();
//            if (empty($is_company)) {
//                $is_team = Db::name('team')->where(['user_id' => $user_id])->value('company_id');
//                if (empty($is_team)) {
//                    $this->error('您还没有加入公司不能开企业单位发票', 0);
//                }
//            }
        $data = [
            'user_id' => $user_id,
            'shou' => $param['invoice_people'],
            'mobile' => $param['mobile'],
            'address' => $param['address'],
            'address_con' => $param['address_con'],
            'invoice_head' => $param['invoice_head'],
            'selectedOptionszero' => $str
        ];
//        } else {
//            $data = [
//                'user_id' => $user_id,
//                'shou' => $param['invoice_people'],
//                'mobile' => $param['mobile'],
//                'address' => $param['address'],
//                'address_con' => $param['address_con'],
//                'type' => $param['type'],
//                'invoice_head' => $param['invoice_head'],
//            ];
//        }
        $invoice_id = Db::name('invoice_ziliao')->where(['user_id' => $user_id])->value('id');
        if (empty($invoice_id)) {
            $res = Db::name('invoice_ziliao')->insert($data);
        } else {
            $res = Db::name('invoice_ziliao')->where(['id' => $invoice_id])->update($data);
        }
        if ($res) {
            $this->success('成功', 1);
        } else {
            $this->error('失败', 0);
        }
    }


    /**
     * @ApiTitle    (发票接口-发票资料渲染)
     * @ApiSummary  (发票资料渲染)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Invoice/InvoiceDataRendering)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": {
    "company_list": {
    "company_name": "",
    "credit": "",
    "bank_name": "",
    "bank_num": "",
    "company_tel": "",
    "invoice_address": ""
    },
    "user_list": {
    "shou": "",
    "mobile": "",
    "address": "",
    "address_con": ""
    "invoice_head":""
    }
    }
    })
     */
    public function InvoiceDataRendering()
    {
        $user_id = $this->is_token($this->request->header());
        $is_company = Db::name('company')->where(['company_holder' => $user_id])->where(['status' => 1])->value('id');
        if (empty($is_company)) {
            $is_team = Db::name('team')->where(['user_id' => $user_id])->where(['status' => 1])->value('company_id');
            if (empty($is_team)) {
                $company_list = '';
            } else {
                $team_company_arr = Db::name('company')->where(['id' => $is_team])->find();
                $company_list = [
                    'paragraph' => $team_company_arr['paragraph'],
                    'credit' => $team_company_arr['credit'],
                    'bank_name' => $team_company_arr['bank_name'],
                    'bank_num' => $team_company_arr['bank_num'],
                    'company_tel' => $team_company_arr['company_tel'],
                    'invoice_address' => $team_company_arr['invoice_address'],
                ];
            }
        } else {
            $company_arr = Db::name('company')->where(['id' => $is_company])->find();
            $company_list = [
                'paragraph' => $company_arr['paragraph'],
                'credit' => $company_arr['credit'],
                'bank_name' => $company_arr['bank_name'],
                'bank_num' => $company_arr['bank_num'],
                'company_tel' => $company_arr['company_tel'],
                'invoice_address' => $company_arr['invoice_address'],
            ];
        }
        $ziliao = Db::name('invoice_ziliao')->where(['user_id' => $user_id])->find();
        if (empty($ziliao)) {
            $user_list = '';
        } else {
            $data_arr = explode(',', $ziliao['selectedOptionszero']);
            $user_list = [
                'shou' => $ziliao['shou'],
                'mobile' => $ziliao['mobile'],
                'address' => $ziliao['address'],
                'address_con' => $ziliao['address_con'],
                'invoice_head' => $ziliao['invoice_head'],
                'selectedOptionszero' => $data_arr
            ];
        }
        $return['company_list'] = $company_list;
        $return['user_list'] = $user_list;
        $this->success('成功', $return);
    }


    /**
     * @ApiTitle    (发票接口-申请发票)
     * @ApiSummary  (申请发票)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Invoice/ApplicationForOrdinaryInvoice)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="invoice_type", type="int", required=true, description="发票类型:1=专用发票,2=普通发票")
     * @ApiParams   (name="type", type="int", required=true, description="抬头类型:1=企业单位,2=个人")
     * @ApiParams   (name="order_sn", type="string", required=true, description="订单号")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": "1"
    })
     */
    public function ApplicationForOrdinaryInvoice()
    {
        $user_id = $this->is_token($this->request->header());
        $param = $this->request->param();
        $ziliao = Db::name('invoice_ziliao')->where(['user_id' => $user_id])->find();
        if ($param['type'] == 1) {
            $is_company = Db::name('company')->where(['company_holder' => $user_id])->find();
            if (empty($is_company)) {
                $is_team = Db::name('team')->where(['user_id' => $user_id])->value('company_id');
                $team = Db::name('company')->where(['id' => $is_team])->find();
                $data = [
                    'invoice_head_name' => $team['company_name'],
                    'invoice_head' => 1,
                    'invoice_type' => $param['invoice_type'],
                    'company_code' => $team['credit'],
                    'bank_name' => $team['bank_name'],
                    'bank_num' => $team['bank_num'],
                    'paragraph' => $team['paragraph'],
                    'company_tel' => $team['company_tel'],
                    'register_tel' => $team['register_tel'],
                    'invoice_address' => $team['invoice_address'],
                    'order_sn' => $param['order_sn'],
                    'user_id' => $user_id,
                    'invoice_people' => $ziliao['shou'],
                    'mobile' => $ziliao['mobile'],
                    'address' => $ziliao['address'],
                    'address_con' => $ziliao['address_con'],
                    'invoice_status' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ];
            } else {
                $data = [
                    'invoice_head_name' => $is_company['company_name'],
                    'invoice_head' => 1,
                    'invoice_type' => $param['invoice_type'],
                    'company_code' => $is_company['credit'],
                    'bank_name' => $is_company['bank_name'],
                    'bank_num' => $is_company['bank_num'],
                    'paragraph' => $is_company['paragraph'],
                    'company_tel' => $is_company['company_tel'],
                    'register_tel' => $is_company['register_tel'],
                    'invoice_address' => $is_company['invoice_address'],
                    'order_sn' => $param['order_sn'],
                    'user_id' => $user_id,
                    'invoice_people' => $ziliao['shou'],
                    'mobile' => $ziliao['mobile'],
                    'address' => $ziliao['address'],
                    'address_con' => $ziliao['address_con'],
                    'invoice_status' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ];
            }
        } else {
            $data = [
                'invoice_head' => 2,
                'invoice_type' => $param['invoice_type'],
                'order_sn' => $param['order_sn'],
                'user_id' => $user_id,
                'invoice_people' => $ziliao['shou'],
                'invoice_head_people' => $ziliao['invoice_head'],
                'mobile' => $ziliao['mobile'],
                'address' => $ziliao['address'],
                'address_con' => $ziliao['address_con'],
                'invoice_status' => 1,
                'createtime' => time(),
                'updatetime' => time()
            ];
        }
        $res = Db::name('order_invoice')->insert($data);
        Db::name('order')->where(['order_sn' => $param['order_sn']])->update(['invoice_status' => 2]);
        if ($res) {
            $this->success('成功', 1);
        } else {
            $this->error('失败', 0);
        }
    }


    /**
     * @ApiTitle    (发票接口-发票查询)
     * @ApiSummary  (发票查询)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Invoice/InvoiceQuery)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="type", type="string", required=true, description="1:待开票,2=开票中,3=已开票")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": {
    "ToBeReviewed": 待开票,
    "GoodsToBeReceived": 开票中,
    "Completed": 已开票,
    "itemList": [
    {
    "total": "总价",
    "order_sn": "202007161753342661571130",
    "username": "下单人",
    "shopping": 快递,
    "shop_order": 快递单号,
    "invoice_code": 发票代码,
    "invoice_num": 发票号,
    "buy_num": 数量,
    "list": [
    {
    "avatar": "http://qco519e0n.bkt.clouddn.com/uploads/20200703/Fpi3RGA38eqT3eDk_sh99hOZ7wAA.png",
    "name": "12kf(123)+10.50v",
    "class_con": "详细分类3",
    "logo": "品牌1",
    "price": 60,
    "gradient": [
    {
    "tidu": "100",
    "price": "0.10"
    }
    ]
    }
    ]
    }
    })
     */
    public function InvoiceQuery()
    {
        $user_id = $this->is_token($this->request->header());
        $type = input('type');
        $ToBeReviewed_arr = Db::name('order')->where(['user_id' => $user_id])->where(['invoice_status' => 1])->select();
        $incoice = [];
        $incoice['invoice_status'] = array(array('eq', 2), array('eq', 3), 'or');
        $GoodsToBeReceived_arr = Db::name('order_invoice')->where(['user_id' => $user_id])
            ->where($incoice)
            ->select();
        $Completed_arr = Db::name('order_invoice')->where(['user_id' => $user_id])->where(['invoice_status' => 4])->select();
        $return['ToBeReviewed'] = count($ToBeReviewed_arr);
        $return['GoodsToBeReceived'] = count($GoodsToBeReceived_arr);
        $return['Completed'] = count($Completed_arr);
        $map = [];
        $map2 = [];
        if ($type == 1) {
            $map['o.invoice_status'] = array('eq', $type);
            $map2['invoice_status'] = array('eq', $type);
            $list = Db::name('order')
                ->alias('o')
                ->where($map)
                ->where(['o.user_id' => $user_id])
                ->join('user u', 'u.id=o.user_id')
                ->field('o.id,o.total,o.order_sn,u.username')
                ->select();
            $shopping = Db::name('order')->where(['user_id' => $user_id])->where($map2)->select();
            foreach ($list as $k1 => $v1) {
                $list[$k1]['shopping'] = null;
                $list[$k1]['shop_order'] = null;
                $list[$k1]['invoice_code'] = null;
                $list[$k1]['invoice_num'] = null;
            }
            foreach ($shopping as $k => $v) {
                $order_con_arr[0] = Db::name('order_con')->where(['order_sn' => $v['order_sn']])->select();
                $order_con = $this->three_arr($order_con_arr);
                foreach ($order_con as $k1 => $v1) {
                    $product_arr[$k1] = $this->GenerateOrderPriceCalculation($v1['product_id'], $v1['buy_num']);
                    $buy_num[$k1] = $v1['buy_num'];
                }
                $product_list = $this->three_arr($product_arr);
                $list[$k]['buy_num'] = array_sum($buy_num);
                $list[$k]['list'] = $product_list;
            }
            $return['itemList'] = $list;
            $this->success('成功', $return);
        }
        if ($type == 2) {
            $map['i.invoice_status'] = array(array('eq', 2), array('eq', 3), 'or');
            $map2['invoice_status'] = array(array('eq', 2), array('eq', 3), 'or');
            $list = Db::name('order_invoice')
                ->alias('i')
                ->where(['i.user_id' => $user_id])
                ->where($map)
                ->join('user u', 'u.id=i.user_id')
                ->join('order o', 'o.order_sn=i.order_sn')
                ->field('o.id,o.total,o.order_sn,u.username,o.order_status')
                ->select();
            $shopping = Db::name('order_invoice')->where(['user_id' => $user_id])->where($map2)->select();
        }
        if ($type == 3) {
            $map['i.invoice_status'] = array('eq', 4);
            $map2['invoice_status'] = array('eq', 4);
            $list = Db::name('order_invoice')
                ->alias('i')
                ->where(['i.user_id' => $user_id])
                ->where($map)
                ->join('user u', 'u.id=i.user_id')
                ->join('order o', 'o.order_sn=i.order_sn')
                ->field('o.id,o.total,o.order_sn,u.username,o.order_status')
                ->select();
            $shopping = Db::name('order_invoice')->where(['user_id' => $user_id])->where($map2)->select();
        }
        foreach ($shopping as $k => $v) {
            if ($v['shopping'] == NULL) {
                foreach ($list as $k1 => $v1) {
                    $list[$k]['shopping'] = null;
                    $list[$k]['shop_order'] = null;
                }
            } else {
                foreach ($list as $k1 => $v1) {
                    $list[$k]['shopping'] = $v['shopping'];
                    $list[$k]['shop_order'] = $v['shop_order'];
                }
            }
            if ($v['invoice_code'] == NULL) {
                foreach ($list as $k1 => $v1) {
                    $list[$k]['invoice_code'] = null;
                    $list[$k]['invoice_num'] = null;
                }
            } else {
                foreach ($list as $k1 => $v1) {
                    $list[$k]['invoice_code'] = $v['invoice_code'];
                    $list[$k]['invoice_num'] = $v['invoice_num'];
                }
            }
        }
        foreach ($shopping as $k => $v) {
            $order_con_arr[0] = Db::name('order_con')->where(['order_sn' => $v['order_sn']])->select();
            $order_con = $this->three_arr($order_con_arr);
            foreach ($order_con as $k1 => $v1) {
                $product_arr[$k1] = $this->GenerateOrderPriceCalculation($v1['product_id'], $v1['buy_num']);
                $buy_num[$k1] = $v1['buy_num'];
            }
            $product_list = $this->three_arr($product_arr);
            $list[$k]['buy_num'] = array_sum($buy_num);
            $list[$k]['list'] = $product_list;
        }
        $return['itemList'] = $list;
        $this->success('成功', $return);
    }


    /**
     * @ApiTitle    (发票接口-发票搜索)
     * @ApiSummary  (发票搜索)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Invoice/InvoiceSearch)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="keyword", type="string", required=true, description="搜索")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": {
    "ToBeReviewed": 待开票,
    "GoodsToBeReceived": 开票中,
    "Completed": 已开票,
    "itemList": [
    {
    "total": "总价",
    "order_sn": "202007161753342661571130",
    "username": "下单人",
    "shopping": 快递,
    "shop_order": 快递单号,
    "invoice_code": 发票代码,
    "invoice_num": 发票号,
    "buy_num": 数量,
    "list": [
    {
    "avatar": "http://qco519e0n.bkt.clouddn.com/uploads/20200703/Fpi3RGA38eqT3eDk_sh99hOZ7wAA.png",
    "name": "12kf(123)+10.50v",
    "class_con": "详细分类3",
    "logo": "品牌1",
    "price": 60,
    "gradient": [
    {
    "tidu": "100",
    "price": "0.10"
    }
    ]
    }
    ]
    }
    })
     */
    public function InvoiceSearch()
    {
        $user_id = $this->is_token($this->request->header());
        $key = input('key');
        $map = [];
        $map2 = [];
        $map['i.order_sn'] = ['LIKE', '%' . $key . '%'];
        $map2['order_sn'] = ['LIKE', '%' . $key . '%'];
        $list = Db::name('order_invoice')
            ->alias('i')
            ->where(['i.user_id' => $user_id])
            ->where($map)
            ->join('user u', 'u.id=i.user_id')
            ->join('order o', 'o.order_sn=i.order_sn')
            ->field('o.id,o.invoice_status,o.total,o.order_sn,u.username,o.order_status')
            ->select();
        $shopping = Db::name('order_invoice')->where(['user_id' => $user_id])->where($map2)->select();
        foreach ($shopping as $k => $v) {
            if ($v['shopping'] == NULL) {
                foreach ($list as $k1 => $v1) {
                    $list[$k]['shopping'] = null;
                    $list[$k]['shop_order'] = null;
                }
            } else {
                foreach ($list as $k1 => $v1) {
                    $list[$k]['shopping'] = $v['shopping'];
                    $list[$k]['shop_order'] = $v['shop_order'];
                }
            }
            if ($v['invoice_code'] == NULL) {
                foreach ($list as $k1 => $v1) {
                    $list[$k]['invoice_code'] = null;
                    $list[$k]['invoice_num'] = null;
                }
            } else {
                foreach ($list as $k1 => $v1) {
                    $list[$k]['invoice_code'] = $v['invoice_code'];
                    $list[$k]['invoice_num'] = $v['invoice_num'];
                }
            }
        }
        foreach ($shopping as $k => $v) {
            $order_con_arr[0] = Db::name('order_con')->where(['order_sn' => $v['order_sn']])->select();
            $order_con = $this->three_arr($order_con_arr);
            foreach ($order_con as $k1 => $v1) {
                $product_arr[$k1] = $this->GenerateOrderPriceCalculation($v1['product_id'], $v1['buy_num']);
                $buy_num[$k1] = $v1['buy_num'];
            }
            $product_list = $this->three_arr($product_arr);
            $list[$k]['buy_num'] = array_sum($buy_num);
            $list[$k]['list'] = $product_list;
        }
        $return['itemList'] = $list;
        $this->success('成功', $return);
    }
}