<?php


namespace app\admin\controller;
use app\admin\BaseController;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\Validate;

class InvCat extends BaseController{
    public function __construct(App $app) {parent::__construct($app);}
    //商品关联开票类目
    public function AddGood(){
            $spuCode=isset($this->post['spuCode'])&&$this->post['spuCode']!=''?trim($this->post['spuCode']):"";
            if($spuCode==''){
                return error_show(1004,"参数 spuCode 不能为空");
            }
            $goodinfo =Db::name("good")->where(["spuCode"=>$spuCode])->findOrEmpty();
            if(empty($goodinfo)) return error_show(1004,"商品数据未找到");
            $inv_good_name = isset($this->post['inv_good_name'])&&$this->post['inv_good_name']!=''?trim($this->post['inv_good_name']):"";
            if($inv_good_name==''){
                return error_show(1004,"参数 inv_good_name 不能为空");
            }
            $tax = isset($this->post['tax'])&&$this->post['tax']!=''?trim($this->post['tax']):"";
            if($tax=="") return error_show(1004,"参数 tax 不能为空");
            $cat_code = isset($this->post['cat_code'])&&$this->post['cat_code']!=''?trim($this->post['cat_code']):"";
            if($cat_code==''){
               return error_show(1004,"参数 cat_code 不能为空");
            }
            $catinfo=Db::name("inv_cat")->where(["cat_code"=>$cat_code])->findOrEmpty();
            if(empty($catinfo)) return error_show(1004,"未找到对应的开票类目");
            $taxArr=$catinfo['tax']!=''? explode("、",$catinfo['tax']):[];
            if(!in_array($tax,$taxArr))return error_show(1004,"未找到对应的开票类目税率");
            $tax=str_replace("%","",$tax)/100;
			$invTag=isset($this->post['inv_tag'])&& $this->post['inv_tag']!==''?intval($this->post['inv_tag']):0;
			$is_discount=isset($this->post['is_discount'])&& $this->post['is_discount']!==''?intval($this->post['is_discount']):0;
			$addTax=isset($this->post['addTax'])&& $this->post['addTax']!==''?trim($this->post['addTax']):'';
			if($is_discount==1){
				// 优惠政策下 税率标识只能选择 0非零说率 1免税 2不征税 增值税管理为空"出口零税/免税/不征税"
				if($tax==0 && $invTag==3){
					return error_show(1004,"税率标识不能选择零税率");
				}
				if($addTax==''){
					return error_show(1004,"参数 addTax 不能为空");
				}
			}else{
				// 非优惠政策下 零税率 税率标识只能选择 3 普通零税率  增值税管理为空
				// 非优惠政策下 非零税率 税率标识只能选择 0 非零税率  增值税管理为空
				if($tax==0 && $invTag!=3){
					return error_show(1004,"税率标识只能选择零税率");
				}
				$addTax='';
			}

            $data=[
                "inv_cat_name"=>$catinfo['short_name'],
                "inv_cat_code"=>$catinfo['merge_code'],
                "inv_tax"=>$tax,
                "inv_good_name"=>$inv_good_name,
                "inv_tag"=>$invTag,
                "is_discount"=>$is_discount,
                "addTax"=>$addTax,
                "status"=>1,
                "updatetime"=>date("Y-m-d H:i:s")
            ];
            $up =Db::name("good")->where($goodinfo)->update($data);
            return $up? app_show(0,"添加成功"):error_show(1004,"添加失败");

    }
    //商品列表
    public function GoodList(){
        $page =isset($this->post['page'])&&  $this->post['page']!="" ? intval($this->post['page']) :1;
        $size =isset($this->post['size'])&&  $this->post['size']!="" ? intval($this->post['size']) :15;
        $condition =[];
        $status =isset($this->post['status'])&&$this->post['status']!==''?intval($this->post['status']):"";
        if($status!==''){
          $condition[]=["status","=",$status];
        }
         $isZx =isset($this->post['isZx'])&&$this->post['isZx']!==''?intval($this->post['isZx']):"";
        if($isZx!==''){
          $condition[]=["isZx","=",$isZx];
        }
        $spuCode=isset($this->post['spuCode'])&&$this->post['spuCode']!=''?trim($this->post['spuCode']):"";
        if($spuCode!="") $condition[]=["spuCode","like","%$spuCode%"];
        $good_name=isset($this->post['good_name'])&&$this->post['good_name']!=''?trim($this->post['good_name']):"";
        if($good_name!="") $condition[]=["good_name","like","%$good_name%"];
        $companyNo=isset($this->post['companyNo'])&&$this->post['companyNo']!=''?trim($this->post['companyNo']):"";
        if($companyNo!="") $condition[]=["companyNo","like","%$companyNo%"];
        $supplierNo=isset($this->post['supplierNo'])&&$this->post['supplierNo']!=''?trim($this->post['supplierNo']):"";
        if($supplierNo!="") $condition[]=["supplierNo","like","%$supplierNo%"];
         $creater=isset($this->post['creater'])&&$this->post['creater']!=''?trim($this->post['creater']):"";
        if($creater!="") $condition[]=["creater","like","%$creater%"];
        $count=Db::name("good")->where($condition)->count();
        $total=ceil($count/$size);
        $page = $page>=$total? intval($total):$page;
        $list =Db::name("good")->where($condition)->order("addtime desc")->page($page,$size)->select()->toArray();
        foreach ($list as &$value){
            $company =Db::name("supplier_info")->where(["code"=>$value['companyNo']])->find();
            $value['companyName']=$company['name']??"";
            $supplier =Db::name("supplier_info")->where(["code"=>$value["supplierNo"]])->find();
            $value["supplierName"]=$supplier["name"]??"";
        }
        return app_show(0,"获取成功",["list"=>$list,"count"=>$count]);
    }
    //商品详情
    public function goodinfo(){
         $spuCode=isset($this->post['spuCode'])&&$this->post['spuCode']!=''?trim($this->post['spuCode']):"";
         if($spuCode=="") return error_show(1004,"参数 spuCode 不能为空");
         $goodinfo =Db::name("good")->where(["spuCode"=>$spuCode])->findOrEmpty();
         if(empty($goodinfo))return error_show(1004,"商品数据未找到");
          $company =Db::name("company_info")->where(["companyNo"=>$goodinfo['companyNo']])->find();
            $goodinfo['companyName']=$company['company_name']??"";
            $supplier =Db::name("supplier_info")->where(["code"=>$goodinfo["supplierNo"]])->find();
            $goodinfo["supplierName"]=$supplier["name"]??"";

            return app_show(0,"获取成功",$goodinfo);
    }
    //发票类目列表
    public function catlist(){
        $page =isset($this->post['page'])&&  $this->post['page']!="" ? intval($this->post['page']) :1;
        $size =isset($this->post['size'])&&  $this->post['size']!="" ? intval($this->post['size']) :15;
        $condition =[];
        $cat_name = isset($this->post['cat_name'])&&$this->post['cat_name']!=''?trim($this->post['cat_name']):"";
        if($cat_name!=''){
            $condition[]=["cat_name|short_name","like","%$cat_name%"];
        }
        $cat_code = isset($this->post['cat_code'])&&$this->post['cat_code']!=''?trim($this->post['cat_code']):"";
        if($cat_code!=''){
            $condition[]=["cat_code|merge_code","like","%$cat_code%"];
        }
        $status =isset($this->post['status'])&&$this->post['status']!==''?intval($this->post['status']):"";
        if($status!==''){
          $condition[]=["status","=",$status];
        }
        $count =Db::name("inv_cat")->where($condition)->count();
        $total=ceil($count/$size);
        $page = $page>=$total? intval($total):$page;
        $list =Db::name("inv_cat")->where($condition)->order("addtime desc")->page($page,$size)->select()->toArray();
        foreach ($list as &$value){
            $value['tax'] = $value['tax']==''?[]:explode("、",$value['tax']);
        }
        return app_show(0,"获取成功",["list"=>$list,"count"=>$count]);
    }
    //类目查询
    public function query(){
       $condition =[["tax","<>",""]];
        $cat_name = isset($this->post['cat_name'])&&$this->post['cat_name']!=''?trim($this->post['cat_name']):"";
        if($cat_name!=''){
            $condition[]=["short_name","like","%$cat_name%"];
        }
        $cat_code = isset($this->post['cat_code'])&&$this->post['cat_code']!=''?trim($this->post['cat_code']):"";
        if($cat_code!=''){
            $condition[]=["cat_code|merge_code","like","%$cat_code%"];
        }
       $list =Db::name("inv_cat")->where($condition)->order("addtime desc")->limit(30)->select()->toArray();
        foreach ($list as &$value){
            $value['tax'] = $value['tax']==''?[]:explode("、",$value['tax']);
        }
      return app_show(0,"获取成功",$list);
    }

    //批量设置类目信息
    public function addGoodBatch()
    {

        $list = $this->request->post('list/a', [], 'trim');

        $val = Validate::rule([
            'spuCode|商品编号' => 'require|max:255',
            'tax|税率' => 'require|max:4',
            'cat_code|类目编号简写' => 'require|max:255',
            'inv_good_name|开票商品名称' => 'require|max:255',
            'inv_tag|税率标识' => 'require|between:0,3',
            'is_discount|是否有优惠政策' => 'require|in:0,1',
            'addTax|增值税管理内容' => 'max:255',
        ]);

        Db::startTrans();

        try {

            $all_spuCode = Db::name('good')
                ->whereIn('spuCode', array_column($list, 'spuCode'))
                ->column('id', 'spuCode');

            $all_cat_code = Db::name('inv_cat')
                ->whereIn('cat_code', array_column($list, 'cat_code'))
                ->column('tax,merge_code,short_name', 'cat_code');

            $date = date('Y-m-d H:i:s');
            foreach ($list as $value) {
                if (!$val->check($value)) throw new Exception($val->getError());

                if (!isset($all_spuCode[$value['spuCode']])) throw new Exception($value['spuCode'].'商品数据未找到');
                if (!isset($all_cat_code[$value['cat_code']])) throw new Exception($value['cat_code'].'未找到对应的开票类目');
                if (!in_array($value['tax'], $all_cat_code[$value['cat_code']]['tax'] != '' ? explode('、', $all_cat_code[$value['cat_code']]['tax']) : [])) throw new Exception($value['tax'].'未找到对应的开票类目税率');
                $value['tax'] = str_replace('%', '', $value['tax']);
                $value['tax'] = round(bcdiv($value['tax'], 100, 3), 2);


                if ($value['is_discount'] == 1) {
                    // 优惠政策下 税率标识只能选择 0非零说率 1免税 2不征税 增值税管理为空"出口零税/免税/不征税"
                    if ($value['tax'] == 0 && $value['inv_tag'] == 3) throw new Exception($value['spuCode'].'税率标识不能选择零税率');

                    if ($value['addTax'] == '') throw new Exception($value['spuCode'].'参数 addTax 不能为空');

                } else {
                    // 非优惠政策下 零税率 税率标识只能选择 3 普通零税率  增值税管理为空
                    // 非优惠政策下 非零税率 税率标识只能选择 0 非零税率  增值税管理为空
                    if ($value['tax'] == 0 && $value['inv_tag'] != 3) throw new Exception($value['spuCode'].'税率标识只能选择零税率');

                    $value['addTax'] = '';
                }

                $data = [
                    'inv_cat_name' => $all_cat_code[$value['cat_code']]['short_name'],
                    'inv_cat_code' => $all_cat_code[$value['cat_code']]['merge_code'],
                    'inv_tax' => $value['tax'],
                    'inv_good_name' => $value['inv_good_name'],
                    'inv_tag' => $value['inv_tag'],
                    'is_discount' => $value['is_discount'],
                    'addTax' => $value['addTax'],
                    'status' => 1,
                    'updatetime' => $date
                ];

                Db::name("good")->where('id', $all_spuCode[$value['spuCode']])->update($data);

            }

            Db::commit();

            return app_show(0, '添加成功');
        } catch (Exception $exception) {
            Db::rollback();
            return error_show(1004, '添加失败,' . $exception->getMessage());
        }

    }
}