<?php


namespace app\admin\controller;

use app\admin\model\ActionLog;
use app\admin\model\DataGroup as DataGroupModel;
use app\admin\model\GoodLog;
use app\admin\model\GoodStockInfo;use app\admin\model\ProcessOrder;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\Validate;

//退货单
class Orderback extends Base
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function list()
    {
        $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']) : "10";
        $where = [['a.is_del', "=", 0]];
        $thNo = isset($this->post['thNo']) && $this->post['thNo'] != "" ? trim($this->post['thNo']) : "";
        if ($thNo != "") {
            $where[] = ['a.thNo', "like", "%{$thNo}%"];
        }
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? intval($this->post['status']) : "";
        if ($status !== "") {
            // $where['status'] = $status;
            $where[] = ['a.status', "=", $status];
        }
        $post_code = isset($this->post['post_code']) && $this->post['post_code'] != "" ? trim($this->post['post_code']) : "";
        if ($post_code != "") {
            $where[] = ['a.post_code', "like", "%{$post_code}%"];
        }
        $post_compay = isset($this->post['post_compay']) && $this->post['post_compay'] != "" ? trim($this->post['post_compay']) : "";
        if ($post_compay != "") {
            $where[] = ['a.post_company', "=", $post_compay];
        }
        $customer_code = isset($this->post['customer_code']) && $this->post['customer_code'] != "" ? trim($this->post['customer_code']) : "";
        if ($customer_code != "") {
            $where[] = ['a.customer_code', "like", "%{$customer_code}%"];
        }

        $relaComNo = isset($this->post['relaComNo']) && $this->post['relaComNo'] != "" ? trim($this->post['relaComNo']) : "";
        if ($relaComNo != "") $where[] = ['b.supplierNo', '=', $relaComNo];

        $order_code = isset($this->post['order_code']) && $this->post['order_code'] != "" ? trim($this->post['order_code']) : "";
        if ($order_code != "") {
            $where[] = ['a.orderCode', "like", "%{$order_code}%"];
        }
        $out_code = isset($this->post['out_code']) && $this->post['out_code'] != "" ? trim($this->post['out_code']) : "";
        if ($out_code != "") {
            $where[] = ['a.outCode', "like", "%{$out_code}%"];
        }
        $return_code = isset($this->post['return_code']) && $this->post['return_code'] != "" ? trim($this->post['return_code']) : "";
        if ($return_code != "") {
            $where[] = ['a.returnCode', "like", "%{$return_code}%"];
        }
        $start = isset($this->post['start']) && $this->post['start'] != '' ? $this->post['start'] : "";
        if ($start !== "") {
            $where[] = ['a.addtime', ">=", $start];
        }
        $end = isset($this->post['end']) && $this->post['end'] != '' ? $this->post['end'] : "";
        if ($end !== "") {
            $where[] = ['a.addtime', "<=", $end];
        }

        $order_source = isset($this->post['order_source']) && $this->post['order_source'] != "" ? trim($this->post['order_source']) : "";
        if ($order_source !== "") {
            $where[] = ['b.order_source', "=", $order_source];
        }

        $supplierNo = trim($this->post['supplierNo'] ?? '');
        if ($supplierNo !== '') $where[] = ['a.supplierNo', 'like', '%'.$supplierNo.'%'];

        $companyNo = trim($this->post['companyNo'] ?? '');
        if ($companyNo !== '') $where[] = ['a.companyNo', 'like', '%'.$companyNo.'%'];

        $condition = [];
//        $role=$this->checkRole();
//        if(!empty($role['write']) && $this->uid!=""){
//            // $where[]=["a.apply_id","in",$role['write']];
//            $condition .="cgderid = {$this->uid} or apply_id in (".implode(',',$role['write']).")";
//        }
//		$hand = resign_hand_user($this->uid);
//        $role = $this->checkDataShare();
//        if (!empty($role[DataGroupModel::$type_全部])) $condition .= "cgderid in {$hand} or apply_id in (" . implode(',',
//        $role[DataGroupModel::$type_全部]) . ")";

        //只有level2的账号过滤数据权限
        if ($this->level == 2) {
            $role = $this->checkDataShare();
            $hand = resign_hand_user($this->uid, 0);
            if (!empty($role[DataGroupModel::$type_全部])) {
                $arr = array_unique(array_merge($hand, $role[DataGroupModel::$type_全部]));
                $condition[] = ['a.apply_id', 'in', $arr];
                $condition[] = ['a.cgderid', 'in', $hand];
            }
        }

        //供应商账号不允许看到库存品数据
        if ($this->level == 3) $where[] = ['b.is_stock', '<>', 1];
//        if(!empty($role['platform']) ){
//            $where[]=["platform_id","in",$role['platform']];
//        }
        $count = Db::name("order_back")
            ->alias('a')
            ->leftJoin('sale b', 'b.orderCode=a.orderCode AND b.is_del=0')
            ->where($where)
            ->where(function ($query) use ($condition) {
                $query->whereOr($condition);
            })
            ->count('a.id');
        $total = ceil($count / $size);
        $page = $page >= $total ? $total : $page;
        $list = Db::name("order_back")
            ->alias('a')
            ->leftJoin('sale b', 'b.orderCode=a.orderCode AND b.is_del=0')
            ->where($where)
            ->where(function ($query) use ($condition) {
                $query->whereOr($condition);
            })
            ->field('a.*,b.order_source')
            ->page($page, $size)
            ->order("a.addtime desc")
            ->select()
            ->toArray();
        $data = [];

        $all_wsm = Db::name("warehouse_info")
            ->alias("a")
            ->where(["a.wsm_code" => array_column($list, 'return_wsm')])
            ->column("a.name,a.supplierNo", 'a.wsm_code');//b.name,b.code

        $userCommon = \app\admin\common\User::getIns();
        $names = $userCommon->handle('getCodeAndName', ['code' => array_unique(array_column($all_wsm, 'supplierNo'))]);

        foreach ($list as $value) {
            $value['wsm_name'] = "";
            $value['wsm_supplier'] = '';
            $value['wsm_supplierNo'] = '';
            if ($value['return_wsm'] != "") {
//                $wsmcode = Db::name("warehouse_info")
//                    ->alias("a")
////                    ->leftJoin("supplier b","a.supplierNo=b.code")
//                    ->where(["a.wsm_code"=>$value['return_wsm']])
//                    ->field("a.name as wsm_name,a.supplierNo")//b.name,b.code
//                    ->find();
                $value['wsm_name'] = $all_wsm[$value['return_wsm']]['name'] ?? '';//isset($wsmcode['wsm_name']) ? $wsmcode['wsm_name']:"";
                $value['wsm_supplier'] = $names['data'][$all_wsm[$value['return_wsm']]['supplierNo']] ?? '';//isset($wsmcode['name']) ? $wsmcode['name']:"";
                $value['wsm_supplierNo'] = $all_wsm[$value['return_wsm']]['supplierNo'];//isset($wsmcode['code']) ? $wsmcode['code']:"";
            }
//            $value['customer_name'] = '';
//            if ($value['customer_code'] != '') {
//                $customer = Db::name("customer_info")->where(['companyNo'=>$value['customer_code']])->find();
//                $value['customer_name'] = $names['data'][$value['customer_code']] ?? '';//isset($customer['companyName'])?$customer['companyName']:'';
//            }
            $inorder = Db::name("order_backinfo")
                ->where(['thNo' => $value['thNo'], "is_del" => 0])
                ->select()
                ->toArray();
            $value['child'] = empty($inorder) ? [] : $inorder;
//            $value['supplierName'] = $names['data'][$value['supplierNo']] ?? '';//isset($customer['companyName'])?$customer['companyName']:'';

            //是否具有编辑权限
//            $value['is_allow_update'] = 0;
//            if (in_array($this->roleid, [1, 33]) || in_array($value['apply_id'], $role[DataGroupModel::$type_可编辑])) $value['is_allow_update'] = 1;

            $data[] = $value;
        }
        return app_show(0, "获取成功", ["list" => $data, "count" => $count]);
    }

    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(){
        $thNo = isset($this->post['thNo']) && $this->post['thNo']!="" ? trim($this->post['thNo']):"";
        if($thNo==""){
            return error_show(1004,"参数thNo不能为空");
        }
        $info =Db::name("order_back")->where(['thNo'=>$thNo])->find();
        if(empty($info)){
            return error_show(1004,"未找到数据");
        }
        $orderinfo = Db::name("sale")->where(["orderCode"=>$info["orderCode"]])->find();
        $info['origin_price']=$orderinfo['origin_price'];
        $info['sale_price']=$orderinfo['sale_price'];
        $info['order_type']=$orderinfo['order_type'];
        $info['order_source']=$orderinfo['order_source'];
        $info['total_price']=$orderinfo['total_price'];
//        $info['companyNo']=$orderinfo['supplierNo'];

//      $info['company'] = Db::name('business')
//          ->where(['companyNo' => $orderinfo['supplierNo'], 'is_del' => 0])
//          ->value('company','');
        $info['addr_cn']=GetAddr($info['addr_code']);
        if($orderinfo['order_type']==3 || $orderinfo['order_type']==4){
            $goon = Db::name("good_zixun")
                ->where(["spuCode"=>$orderinfo['good_code'],"is_del"=>0])
                ->find();
            $is_stock=0;
        }else {
            $goon = Db::name('good_platform')
                ->alias('a')
                ->leftJoin('good b', 'b.spuCode=a.spuCode')
                ->where(['a.skuCode' => $orderinfo['skuCode']])
                ->find();
            $is_stock=$goon['is_stock'];
        }
        if (empty($goon)) {
            return error_show(1003, "未找到商品数据");
        }
        $info['out_wsm_name']="";
        $info['out_wsm_supplier']='';
        $info['out_wsm_supplierNo']='';
        if($is_stock==1){
            $out =Db::name("order_out")->where(['outCode'=>$info['outCode']])->find();
            if($out==false){
                return error_show(1003, "未找到出库单数据");
            }
            if($out['wsm_code']!=''){
//              $wsmcode = Db::name("warehouse_info")
//                  ->alias("a")
////                  ->leftJoin("supplier b","a.supplierNo=b.code")
//                  ->where(["a.wsm_code"=>$out['wsm_code']])
//                  ->field("a.name as wsm_name")
//                  ->find();
//              $info['out_wsm_name'] =isset($wsmcode['wsm_name']) ? $wsmcode['wsm_name']:"";
//              $info['out_wsm_supplier'] =isset($wsmcode['name']) ? $wsmcode['name']:"";
//              $info['out_wsm_supplierNo'] =isset($wsmcode['code']) ? $wsmcode['code']:"";
            }
        }
        $retutninfo = Db::name("order_return")->where(['returnCode'=>$info['returnCode']])->find();
        $info['apply_id'] = $retutninfo['apply_id'];
        $info['apply_name'] = $retutninfo['apply_name'];
        $info['return_tag'] = $retutninfo['return_tag'];
        $int = isset($goon['cat_id']) && $goon['cat_id'] != 0 ? made($goon['cat_id']) : [];
        $info['wsm_name']="";
        $info['wsm_supplier']='';
        $info['wsm_supplierNo']='';
//        if($info['return_wsm']!=""){
//          $wsmcode = Db::name("warehouse_info")
//              ->alias("a")
////              ->leftJoin("supplier b","a.supplierNo=b.code")
//              ->where(["a.wsm_code"=>$info['return_wsm']])
//              ->field("a.name as wsm_name")
//              ->find();
//          $info['wsm_name'] =isset($wsmcode['wsm_name']) ? $wsmcode['wsm_name']:"";
//          $info['wsm_supplier'] =isset($wsmcode['name']) ? $wsmcode['name']:"";
//          $info['wsm_supplierNo'] =isset($wsmcode['code']) ? $wsmcode['code']:"";
//        }
        $inorder= Db::name("order_backinfo")
            ->alias("a")
            ->leftJoin("result_info b","a.error_code=b.result_code")
            ->where(['a.thNo'=>$info['thNo'],"a.is_del"=>0])
            ->field("a.*,b.result as error_msg")
            ->select()
            ->toArray();
        $info['child']=empty($inorder)? [] : $inorder;

        $info['can']=$int;


        //补充仓库名称
        $warehouse = Db::name('warehouse_info')
            ->alias('wi')
            ->where(['wi.is_del' => 0, 'wi.status' => 1])
            ->whereIn('wi.wsm_code', [$info['can_sell_wsm'], $info['defective_wsm'], $out['wsm_code']??'', $info['return_wsm']])
//          ->leftJoin('supplier s', 's.code=wi.supplierNo AND s.is_del=0')
            ->column('wi.name,wi.supplierNo', 'wi.wsm_code');

        $userCommon = \app\admin\common\User::getIns();
        $names = $userCommon->handle('getCodeAndName', ['code' => array_unique(array_merge(array_column($warehouse, 'supplierNo')))]);

//        $info['company'] = $names['data'][$orderinfo['supplierNo']] ?? '';

        $info['can_sell_wsm_name'] = isset($warehouse[$info['can_sell_wsm']]['name']) ? $warehouse[$info['can_sell_wsm']]['name'] : '';
        $info['can_sell_wsm_supplierNo'] = isset($warehouse[$info['can_sell_wsm']]['supplierNo']) ? $warehouse[$info['can_sell_wsm']]['supplierNo'] : '';
        $info['can_sell_wsm_supplier'] = isset($warehouse[$info['can_sell_wsm']]['supplierNo']) ? $names['data'][$warehouse[$info['can_sell_wsm']]['supplierNo']]??'' : '';
        $info['defective_wsm_name'] = isset($warehouse[$info['defective_wsm']]['name']) ? $warehouse[$info['defective_wsm']]['name'] : '';
        $info['defective_wsm_supplierNo'] = isset($warehouse[$info['defective_wsm']]['supplierNo']) ? $warehouse[$info['defective_wsm']]['supplierNo'] : '';
        $info['defective_wsm_supplier'] = isset($warehouse[$info['defective_wsm']]['supplierNo'])?$names['data'][$warehouse[$info['defective_wsm']]['supplierNo']]??'' : '';


        if (isset($out) && $out['wsm_code'] != '') {
            $info['out_wsm_name'] = $warehouse[$info['out_wsm_name']]['name'] ?? '';
            $info['out_wsm_supplier'] = $names['data'][$warehouse[$info['out_wsm_name']]['supplierNo']] ?? '';
            $info['out_wsm_supplierNo'] = $warehouse[$info['out_wsm_name']]['supplierNo'] ?? '';
        }
        if ($info['return_wsm'] != '') {
            $info['wsm_name'] = $warehouse[$info['wsm_name']]['name'] ?? '';
            $info['wsm_supplier'] = $names['data'][$warehouse[$info['wsm_name']]['supplierNo']] ?? '';
            $info['wsm_supplierNo'] = $warehouse[$info['wsm_name']]['supplierNo'] ?? '';
        }

        return app_show(0, "获取成功", $info);
    }

    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
  public function check(){
      $thNo = isset($this->post['thNo']) && $this->post['thNo']!="" ? trim($this->post['thNo']):"";
      if($thNo==""){
          return error_show(1004,"参数thNo不能为空");
      }
      $info =Db::name("order_back")->where(['thNo'=>$thNo])->find();
      if(empty($info)){
          return error_show(1004,"未找到数据");
      }
      $normal = isset($this->post['normal']) && $this->post['normal']!=="" ? intval($this->post['normal']):"";
      if($normal===""){
          return error_show(1004,"参数normal不能为空");
      }
      $errorlist = isset($this->post['errorlist']) && $this->post['errorlist']!=="" ? $this->post['errorlist']:[];
      if($info['status']== 2){
          return error_show(1002,"退货单已验货");
      }
      $receive=$normal+array_sum(array_column($errorlist,'error_num'));
      $remark =  isset($this->post['remark']) && $this->post['remark']!=="" ? trim($this->post['remark']):"";
      $info['received_num'] = $receive;
      $info['normal_num'] = $normal;
      $info['remark'] = $remark;
     $str = $info['status'];
      $info['status'] =empty($errorlist)?3: 2;
      $info['updatetime'] = date("Y-m-d H:i:s");
      Db::startTrans();
      try{
          $up=Db::name("order_back")->save($info);
          if($up){
              $stn = ["order_code"=>$info['thNo'],"status"=>$str,"action_remark"=>'',"action_type"=>"edit"];
              ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname],$stn,"CKTHD",$info['status'],$info);

              if($info['status'] == 2) $roleid = [10, 31, 41];//特殊处理,写入到10采购负责人、31库管人员、41库管-张凯旋这三个角色下的所有人
              else $roleid = [31,41];//特殊处理,写入到31库管人员、41库管-张凯旋这三个角色下的所有人

              $handle_user_list = Db::name('user_role')
                  ->where('is_del', 0)
                  ->whereIn('roleid', $roleid)
                  ->column('uid');
              $process = ["order_code" => $info['thNo'], "order_id" => $info['id'], "order_status" => $info['status'], 'order_type' => "CKTHD", "before_status" => $str, 'handle_user_list' => implode(',', $handle_user_list)];
              ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], $process);
              if(empty($errorlist)){
                  Db::commit();
                  return app_show(0,'更新成功');
              }

              foreach($errorlist as $value){
                  $data=[];
                  isset($value['id'])&&$value['id']!=''?$data['id']=$value['id']:"";
                  $data['thNo']=$thNo;
                  $data['error_num']=$value['error_num'];
                  $data['error_code']=$value['error_code'];
                  $data['error_remark']=$value['error_remark'];
                  $data['is_del']=isset($value['is_del'])?$value['is_del']:0;
                  isset($value['id'])&&$value['id']!=''? "" : $data['addtime']=date("Y-m-d H:i:s");
                  $data['updatetime']=date("Y-m-d H:i:s");
                  $in = Db::name("order_backinfo")->save($data);
                  if(!$in){
                      Db::rollback();
                      return error_show(1005,'更新失败');
                  }
              }
             Db::commit();
             return app_show(0,'更新成功');
          }
          Db::rollback();
          return error_show(1005,'更新失败');
      }catch (\Exception $e){
          Db::rollback();
          return error_show(1004,$e->getMessage());
      }
  }

  public function CheckExam(){
      $thNo = isset($this->post['thNo']) && $this->post['thNo']!="" ? trim($this->post['thNo']):"";
      if($thNo==""){
          return error_show(1004,"参数thNo不能为空");
      }
      $info =Db::name("order_back")->where(['thNo'=>$thNo])->find();
      if(empty($info)){
          return error_show(1004,"未找到数据");
      }
      $errorlist = isset($this->post['errorlist']) && $this->post['errorlist']!=="" ? $this->post['errorlist']:[];
      Db::startTrans();
      try{
          $temp=$info['status'];
          $info['status'] =3;
          $info['updatetime'] = date("Y-m-d H:i:s");
          $up=Db::name("order_back")->save($info);
          if($up){
              $stn = ["order_code"=>$thNo,"status"=>$temp,"action_remark"=>'',"action_type"=>"edit"];
              ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], $stn, "CKTHD", $info['status'], $stn);

              //特殊处理,写入到31库管人员、41库管-张凯旋这三个角色下的所有人
              $handle_user_list = Db::name('user_role')
                  ->where('is_del', 0)
                  ->whereIn('roleid', [31, 41])
                  ->column('uid');
              $process = ["order_code" => $info['thNo'], "order_id" => $info['id'], "order_status" => 3, "order_type" => "CKTHD", "before_status" => $temp, 'handle_user_list' => implode(',', $handle_user_list)];
              ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], $process);

              if(empty($errorlist)){
                  $up =Db::name("order_backinfo")->where(["thNo"=>$thNo,"is_del"=>0])->save(["status"=>1,
                      "updatetime"=>date("Y-m-d H:i:s")]);
                  if($up){
                      Db::commit();
                      return app_show(0,'更新成功');
                  }else{
                      Db::rollback();
                      return error_show(1005,'异常记录数据更新失败');
                  }
              }else{
                  foreach($errorlist as $value){
                      $temp=Db::name("order_backinfo")->where(['id'=>$value["id"],"is_del"=>0,"thNo"=>$thNo])->find();
                      if(empty($temp)){
                          Db::rollback();
                          return error_show(1005,'异常记录数据未找到');
                      }
                      $temp['status']=$value['status'];
                      $temp['exam_remark']=$value['remark'];
                      $temp['updatetime']=date("Y-m-d H:i:s");
                      $com = Db::name("order_backinfo")->save($temp);
                      if($com==false){
                          Db::rollback();
                          return error_show(1005,'异常记录数据更新失败');
                      }
                  }
                  Db::commit();
                  return app_show(0,'更新成功');
              }
          }
          Db::rollback();
          return error_show(1005,'更新失败');
      }catch (\Exception $e){
          Db::rollback();
          return error_show(1004,$e->getMessage());
      }
  }
    public function Exam(){
        $thNo = isset($this->post['thNo']) && $this->post['thNo']!="" ? trim($this->post['thNo']):"";
        if($thNo==""){
            return error_show(1004,"参数thNo不能为空");
        }
        $info =Db::name("order_back")->where(['thNo'=>$thNo])->find();
        if(empty($info)){
            return error_show(1004,"未找到数据");
        }
        $status = isset($this->post['status']) && $this->post['status']!=="" ? intval($this->post['status']):"";
        if($status===""){
            return error_show(1004,"参数status不能为空");
        }
        $return_wsm=isset($this->post["return_wsm"])&&$this->post["return_wsm"]!=""?trim($this->post["return_wsm"]):"";

        $normal_num=isset($this->post["normal_num"])&&$this->post["normal_num"]!=""?intval($this->post["normal_num"])
            :"";
//        $defective_wsm=isset($this->post["defective_wsm"])&&$this->post["defective_wsm"]!=""?trim($this->post["defective_wsm"]):"";

//        $defective_num=isset($this->post["defective_num"])&&$this->post["defective_num"]!==""?intval($this->post["defective_num"]):"";
//        $loss_num=isset($this->post["loss_num"])&&$this->post["loss_num"]!=""?intval($this->post["loss_num"]):"";
        if($status==4){
//            if($defective_num===""){
//                return error_show(1004,"参数defective_num不能为空");
//            }
//            if($loss_num===""){
//                return error_show(1004,"参数loss_num不能为空");
//            }
            if($normal_num===""){
                return error_show(1004,"参数normal_num不能为空");
            }
//            if($defective_wsm===""){
//                return error_show(1004,"参数defective_wsm不能为空");
//            }
            if($return_wsm===""){
                return error_show(1004,"参数return_wsm不能为空");
            }
            $info['return_wsm']=$return_wsm;
            $info['normal_num']=$normal_num;
//            $info['loss_num']=$loss_num;//order_back表里没有这三个字段,不知道是干嘛的
//            $info['defective_wsm']=$defective_wsm;
//            $info['defective_num']=$defective_num;
        }
        $remark= isset($this->post['remark']) && $this->post['remark']!="" ? trim($this->post['remark']):"";
        Db::startTrans();
        try{
            $var = $info['status'];
            $info['status'] =$status;
            $info['remark'] =$remark;
            $info['updatetime'] = date("Y-m-d H:i:s");
            $up=Db::name("order_back")->save($info);
            if($up){
                $stn = ["order_code"=>$thNo,"status"=>$var,"action_remark"=>'',"action_type"=>"edit"];
                ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname],$stn,"CKTHD",$info['status'],$this->post);

                if (in_array($status, [2, 3])) {

                    if ($status == 2) $roleid = [10, 31, 41];//特殊处理,写入到10采购负责人、31库管人员、41库管-张凯旋这三个角色下的所有人
                    else $roleid = [31, 41];//特殊处理,写入到、31库管人员、41库管-张凯旋这三个角色下的所有人

                    $handle_user_list = Db::name('user_role')
                        ->where('is_del', 0)
                        ->whereIn('roleid', $roleid)
                        ->column('uid');
                    $process = ["order_code" => $info['thNo'], "order_id" => $info['id'], "order_status" => $status, "order_type" => "CKTHD", "before_status" => $var, 'handle_user_list' => implode(',', $handle_user_list)];

                } else $process = ["order_code" => $info['thNo'], "order_id" => $info['id'], "order_status" => $status, "order_type" => "CKTHD", "before_status" => $var];

                ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], $process);
                Db::commit();
                return app_show(0,'更新成功');
            }
            Db::rollback();
            return error_show(1005,'更新失败');
        }catch (\Exception $e){
            Db::rollback();
            return error_show(1004,$e->getMessage());
        }
    }


    //新写一个退货接口
    public function ExamNew()
    {
        $param = $this->request->only(['thNo', 'status', 'status_remark', 'can_sell_wsm' => '', 'can_sell_num' => 0, 'defective_wsm' => '', 'defective_num' => 0, 'loss_num' => 0], 'post', 'trim');

        $val = Validate::rule(['thNo|退货编码' => 'require', 'status|状态' => 'require|number|in:4,2,1', 'status_remark|备注' => 'checkRemark:']);

        $val->extend('checkRemark', function ($val, $rule, $data) {
            return $data['status'] == 4 ? true : (empty($val) ? '请填写备注' : true);
        });
        if (!$val->check($param)) return error_show(1004, $val->getError());
        Db::startTrans();
        try {

            $info = Db::name("order_back")
                ->field('id,order_type,status,outCode,good_code,return_num,orderCode,returnCode,apply_id,apply_name')
                ->where(['thNo' => $param['thNo'], 'is_del' => 0])
                ->find();

            if (empty($info)) throw new Exception('未找到数据');
            $sale= Db::name('sale')->where(['orderCode'=>$info['orderCode'],"is_del"=>0])->find();
            if($sale==false){
                Db::rollback();
                return error_show(1004,"未找到销售单数据");
            }
            $spuCode= $info['good_code'];
            if($sale['order_type']!=1){
              if($sale['order_type']==3 ||$sale['order_type']==4){
		          $goon = Db::name("good_zixun")->where(["spuCode"=>$sale['good_code'],"is_del"=>0])->find();
		          $isZx=1;
		      }else {
		          $goon = Db::name('good_basic')->where(['spuCode' => $sale['good_code']])->find();
		          $isZx=2;
		      }
              $spuCode = $this->CheckGoodZx($goon,$isZx,$param['thNo']);
            }
            $out =Db::name("order_out")->where(['outCode'=>$info['outCode']])->find();
            if($out==false){
                Db::rollback();
                return error_show(1004,"未找到发货单数据");
            }
            $returninfo =Db::name("order_return")->where(['returnCode'=>$info['returnCode']])->find();
            if($returninfo==false){
                Db::rollback();
                return error_show(1004,"未找到售后单数据");
            }
			$sabebn =Db::name("sale_info")->where([["orderCode",'=',$info['orderCode']],["num",">",0]])->select()->toArray();
            if($param['can_sell_num']!=0&& $param['can_sell_wsm']!=''){
//                    if($sale['is_stock']==1){ //库存品退回原仓库 备库单释放数量 采购单
//                        $param['can_sell_wsm'] = $out['wsm_code'];
//                    }
                    $stock = Db::name("good_stock")->where(["spuCode"=>$spuCode,'wsm_code'=>$param['can_sell_wsm']])
                    ->find();
                    if(empty($stock)) {
                        $stock=[
                            "spuCode"=>$spuCode,
                            "wsm_code"=>$param['can_sell_wsm'],
                            "usable_stock"=>0,
                            "wait_out_stock"=>0,
                            "wait_in_stock"=>0,
                            "total_stock"=>0,
                            "addtime"=>date("Y-m-d H:i:s"),
                            "updatetime"=>date("Y-m-d H:i:s"),
                        ];
                    }
                    $stock['usable_stock']+=$param['can_sell_num'];
                    $stock['updatetime']=date("Y-m-d H:i:s");
                    $st_up = Db::name("good_stock")->save($stock);
                    if($st_up==false){
                        return error_show(1005,'可售商品入库失败');
                    }
                    $stockid = isset($stock['id']) ? $stock['id'] : Db::name("good_stock")->getLastInsID();

                        if(!empty($sabebn)){
                        	$total_num =$param['can_sell_num'];
                        	foreach ($sabebn as $ve){
                        		$tempnum=0;
                        		if ($total_num==0) break;
                        		if($total_num>=$ve['num']){
                        			$tempnum = $ve['num'];
                        			$total_num-=$ve['num'];
                        			$ve['th_num']+=$ve['num'];
                        			$ve['num']=0;
                        		}else{
                        		    $tempnum = $total_num;
                        			$ve['num']-=$total_num;
                        			$ve['th_num']+=$total_num;
                        			$total_num=0;
                        		}
                        		$bnin=GoodStockInfo::ReturnAdd($stockid,$ve['bnCode'],$tempnum,$ve['stockid']);
                        		if($bnin==false){
                        			 Db::rollback();
                                    return error_show(1005, '可售商品Bn库存数入库失败');
                        		}
								$up=Db::name("sale_info")->save($ve);
                        		if($up==false){
                        			 Db::rollback();
                                    return error_show(1005, '可售商品Bn库存数入库失败');
                        		}
								$bnin=GoodStockInfo::ReturnBn($info['returnCode'],$ve['id'],$tempnum);
                        		if($bnin==false){
                        			 Db::rollback();
                                    return error_show(1005, '可售商品Bn库存数入库失败');
                        		}
                        	}
                        }else{
                        	if($sale['order_type']==1){
                        	 $ordernum = Db::name("order_num")->where(['orderCode' =>$info['orderCode']])->find();
					        if ($ordernum == false) {
					        	Db::rollback();
					            return error_show(1005, '未找到关联采购单');
					        }
					         $cgd = Db::name("purchease_order")->where(["cgdNo" => $ordernum['cgdNo'], "is_del" => 0])->find();
					        if ($cgd == false) {
					        	Db::rollback();
					            return error_show(1005, '未找到采购单数据');
					        }
					        $bn =makeNo("BN");
					        $yp=GoodStockInfo::AddBn($stockid,$bn,$param['can_sell_num'],$cgd['good_price']);
					        if($yp==false){
					        	Db::rollback();
								return error_show(1005, '商品批次退货入库失败');
					        }
                        	}
                        }
                $good_data=['good_log_code'=>$param['thNo'],"stock_id"=> $stockid,"type"=>1,'stock'=>$param['can_sell_num'],"stock_name"=>"usable_stock"];
                GoodLog::LogAdd($this->post['token'],$good_data,'RKTHD');
             }

            if($param['defective_num']!=0&& $param['defective_wsm']!=''){
                $defective = Db::name("good_stock")->where(["spuCode"=>$spuCode,'wsm_code'=>$param['defective_wsm']])->find();
                if(empty($defective)) {
                    $defective=[
                        "spuCode"=>$spuCode,
                        "wsm_code"=>$param['defective_wsm'],
                        "usable_stock"=>0,
                        "wait_out_stock"=>0,
                        "wait_in_stock"=>0,
                        "total_stock"=>0,
                        "addtime"=>date("Y-m-d H:i:s"),
                        "updatetime"=>date("Y-m-d H:i:s"),
                    ];
                    $order = ["order_code"=>$spuCode,"status"=>1,"action_remark"=>'', "action_type"=>"create"];
                }else{
                    $order = ["order_code"=>$spuCode,"status"=>1,"action_remark"=>'', "action_type"=>"edit"];
                }
                $defective['usable_stock']+=$param['defective_num'];
                $defective['updatetime'] = date("Y-m-d H:i:s");
                $upd=  Db::name("good_stock")->save($defective);
                if($upd==false){
                    Db::rollback();
                    return error_show(1005,'次品商品入库失败');
                }
                $stockid = isset($defective['id']) ? $defective['id'] : Db::name("good_stock")->getLastInsID();
                $sabebn =Db::name("sale_info")->where(["orderCode"=>$info['orderCode']])->select()->toArray();
                 if(!empty($sabebn)){
                        	$total_num =$param['defective_num'];
                        	foreach ($sabebn as $ve){
                        		$tempnum=0;
                        		if ($total_num==0) break;
                        		if($total_num>=$ve['num']){
                        			$tempnum = $ve['num'];
                        			$total_num-=$ve['num'];
                        			$ve['th_num']+=$ve['num'];
                        			$ve['num']=0;
                        		}else{
                        		    $tempnum = $total_num;
                        			$ve['num']-=$total_num;
                        			$ve['th_num']+=$total_num;
                        			$total_num=0;
                        		}
                        	    $bnin=GoodStockInfo::ReturnAdd($stockid,$ve['bnCode'],$tempnum,$ve['stockid']);
                        		if($bnin==false){
                        			 Db::rollback();
                                    return error_show(1005, '可售商品Bn库存数入库失败');
                        		}
								$up=Db::name("sale_info")->save($ve);
                        		if($up==false){
                        			 Db::rollback();
                                    return error_show(1005, '可售商品Bn库存数入库失败');
                        		}
								$bnin=GoodStockInfo::ReturnBn($info['returnCode'],$ve['id'],$tempnum);
                        		if($bnin==false){
                        			 Db::rollback();
                                    return error_show(1005, '可售商品Bn库存数入库失败');
                        		}
                        	}
                        }else{
	                        if($sale['order_type']==1){
	                             $ordernum = Db::name("order_num")->where(['orderCode' =>$info['orderCode']])->find();
						        if ($ordernum == false) {
						            Db::rollback();
						            return error_show(1005, '未找到关联采购单');
						        }
						         $cgd = Db::name("purchease_order")->where(["cgdNo" => $ordernum['cgdNo'], "is_del" => 0])->find();
						        if ($cgd == false) {
						            Db::rollback();
						            return error_show(1005, '未找到采购单数据');
						        }
						        $bn =makeNo("BN");
						        $yp=GoodStockInfo::AddBn($stockid,$bn,$param['defective_num'],$cgd['good_price']);
						        if($yp==false){
						            Db::rollback();
									return error_show(1005, '商品批次退货入库失败');
						        }
	                            }
                        }
                $good_data=['good_log_code'=>$param['thNo'],"stock_id"=>isset($defective['id'])? $defective['id']:Db::name("good_stock")->getLastInsID(),"type"=>1,'stock'=>$param['defective_num'],"stock_name"=>"usable_stock"];
                GoodLog::LogAdd($this->post['token'],$good_data,'RKTHD');
            }
            $update_data = ['status' => $param['status'], 'updatetime' => date('Y-m-d H:i:s')];

            //status==4通过,其他值表示驳回
            if ($param['status'] != 4) $update_data['status_remark'] = $param['status_remark'];
            else {
                $update_data['can_sell_wsm'] = $param['can_sell_wsm'];
                $update_data['can_sell_num'] = $param['can_sell_num'];
                $update_data['defective_wsm'] = $param['defective_wsm'];
                $update_data['defective_num'] = $param['defective_num'];
                $update_data['loss_num'] = $param['loss_num'];

                if($sale['is_stock']==1){
                    $sale['th_num']+= $info['return_num'];
                    if($sale['th_num']==$sale['send_num']&& $sale['wsend_num']==0){
                        $sale['status']=3;
                    }
                    $sale['th_fee']+= round($info['return_num']*$sale['sale_price'],2);
                    $sale['updatetime']= date("Y-m-d H:i:s");
                    $uap=Db::name("sale")->save($sale);
                    if($uap==false){
                        Db::rollback();
                        return error_show(1005,'销售单订单更新失败');
                    }
//                    $ordernum =Db::name("order_num")->where(['orderCode'=>$info['orderCode']])->find();
//                    if($ordernum==false){
//                        Db::rollback();
//                        return error_show(1005,'未找到关联采购单');
//                    }
//                    $ordernum['send_num']-=$info['return_num'];
//                    $orderup =Db::name("order_num")->save($ordernum);
//                    if($orderup==false){
//                        Db::rollback();
//                        return error_show(1005,'关联数据更新失败');
//                    }
//                    $cgd =Db::name("purchease_order")->where(["cgdNo"=>$ordernum['cgdNo'],"is_del"=>0])->find();
//                    if($cgd==false){
//                        Db::rollback();
//                        return error_show(1005,'未找到采购单数据');
//                    }
//                    $cgd['th_fee']+= round($cgd['good_price']*$param['can_sell_num'],2);
//                    $cgd['th_num']+=  $param['can_sell_num'];
//                    if($cgd['th_num']==$cgd['send_num']&& $cgd['wsend_num']==0){
//                        $cgd['status']=4;
//                    }
//                    $cgd['updatetime']= date("Y-m-d H:i:s");
//                    $cgdup =Db::name("purchease_order")->save($cgd);
//                    if($cgdup==false){
//                        Db::rollback();
//                        return error_show(1005,'采购单数据更新失败');
//                    }
//                    if($cgd['bkcode']!=""){
//                        $bk=Db::name("purchease_order")->where(["bkcode"=>$cgd['bkcode'],"order_type"=>1,"order_source"=>0,"is_del"=>0])->find();
//                        if($bk==false){
//                            Db::rollback();
//                            return error_show(1005,'未找到备库单数据');
//                        }
//                       $orderbk = Db::name("order_bk")->where(['cgdNo'=>$bk['cgdNo'],"is_del"=>0])->find();
//                        if($orderbk==false){
//                            Db::rollback();
//                            return error_show(1005,'备库单未完全入库');
//                        }
//                        $merge_num = Db::name("purchease_order")->where(["bkcode"=>$bk['bkcode'],"order_type"=>1,"is_del"=>0])->where("order_source","<>",0)->field("sum(send_num)-sum(th_num) as num")->find();
//
//                        $orderbk['balance_num']=$orderbk['total_num']-$merge_num['num'];
//                        $orderbk['merge_num']=$merge_num['num'];
//                        $orderbk['updatetime']=date("Y-m-d H:i:s");
//                        $orderbkup=Db::name("order_bk")->save($orderbk);
//                        if($orderbkup==false){
//                            Db::rollback();
//                            return error_show(1005,'备库单库存数据释放失败');
//                        }
//                    }
                }else{
                    if($returninfo['return_tag']==1){
                        $sale['th_num']+= $info['return_num'];
                        if($sale['th_num']==$sale['send_num']&& $sale['wsend_num']==0){
                            $sale['status']=3;
                        }
                        $sale['th_fee']+= round($info['return_num']*$sale['sale_price'],2);
                        $sale['updatetime']= date("Y-m-d H:i:s");
                        $uap=Db::name("sale")->save($sale);
                        if($uap==false){
                            Db::rollback();
                            return error_show(1005,'销售单订单更新失败');
                        }
                        $ordernum =Db::name("order_num")->where(['orderCode'=>$info['orderCode']])->find();
                        if($ordernum==false){
                            Db::rollback();
                            return error_show(1005,'未找到关联采购单');
                        }
                        $ordernum['send_num']-=$info['return_num'];
                        $orderup =Db::name("order_num")->save($ordernum);
                        if($orderup==false){
                            Db::rollback();
                            return error_show(1005,'关联数据更新失败');
                        }
                        $cgd =Db::name("purchease_order")->where(["cgdNo"=>$ordernum['cgdNo'],"is_del"=>0])->find();
                        if($cgd==false){
                            Db::rollback();
                            return error_show(1005,'未找到采购单数据');
                        }
                        $cgd['th_num']+=  $info['return_num'];
                        if($cgd['th_num']==$cgd['send_num']&& $cgd['wsend_num']==0){
                            $cgd['status']=4;
                        }
                        $cgd['th_fee']+=  round($info['return_num']*$cgd['good_price'],2);
                        $cgd['updatetime']= date("Y-m-d H:i:s");
                        $cgdup =Db::name("purchease_order")->save($cgd);
                        if($cgdup==false){
                            Db::rollback();
                            return error_show(1005,'采购单数据更新失败');
                        }

                    }else{
                        $sale['th_num']+= $info['return_num'];
                        if($sale['th_num']==$sale['send_num']&& $sale['wsend_num']==0){
                            $sale['status']=3;
                        }
                        $sale['th_fee']+= round($info['return_num']*$sale['sale_price'],2);
                        $sale['updatetime']= date("Y-m-d H:i:s");
                        $uap=Db::name("sale")->save($sale);
                        if($uap==false){
                            Db::rollback();
                            return error_show(1005,'销售单订单更新失败');
                        }
//                        $ordernum =Db::name("order_num")->where(['orderCode'=>$info['orderCode']])->find();
//                        if($ordernum==false){
//                            Db::rollback();
//                            return error_show(1005,'未找到关联采购单');
//                        }
//                        $ordernum['send_num']-=$info['return_num'];
//                        $orderup =Db::name("order_num")->save($ordernum);
//                        if($orderup==false){
//                            Db::rollback();
//                            return error_show(1005,'关联数据更新失败');
//                        }
//                        $cgd =Db::name("purchease_order")->where(["cgdNo"=>$ordernum['cgdNo'],"is_del"=>0])->find();
//                        if($cgd==false){
//                            Db::rollback();
//                            return error_show(1005,'未找到采购单数据');
//                        }
//                        $cgd['th_fee']+= round($cgd['good_price']*$param['can_sell_num'],2);
//                        $cgd['th_num']+=  $param['can_sell_num'];
//                        if($cgd['th_num']==$cgd['send_num']&& $cgd['wsend_num']==0){
//                            $cgd['status']=4;
//                        }
//                        $cgd['updatetime']= date("Y-m-d H:i:s");
//                        $cgdup =Db::name("purchease_order")->save($cgd);
//                        if($cgdup==false){
//                            Db::rollback();
//                            return error_show(1005,'采购单数据更新失败');
//                        }
                    }
                }
            }

            $res = Db::name("order_back")
                ->where(['id' => $info['id']])
                ->update($update_data);

            if ($res) {
                $data=[
                    "orderCode"=>$info['orderCode'],
                    "th_type"=>3,
                    "th_num"=>$info['return_num'],
                    "th_fee"=>round($info['return_num']*$sale['sale_price'],2),
                    "thCode"=>$info['returnCode'],
                    "apply_id"=>$info['apply_id'],
                    "apply_name"=>$info['apply_name'],
                    "spuCode"=>$sale['good_code'],
                    "good_name"=>$sale['good_name'],
                    "cat_id"=>$sale['cat_id'],
                    "addtime"=>date("Y-m-d H:i:s"),
                    "status"=>1,
                    "is_del"=>0
                ];
                $inse=Db::name("th_data")->insert($data);
                if($inse==false){
                    Db::rollback();
                    return error_show(1004,"退货单更新失败");
                }
                if($info['return_num']>=$out['send_num']){
                    $out['status']=4;
                    $out['updatetime']=date("Y-m-d H:i:s");
                    $upout =Db::name("order_out")->save($out);
                    if($upout==false){
                        Db::rollback();
                        return error_show(1005,'出库单数据更新失败');
                    }
                }

                $stn = ["order_code" => $param['thNo'], "status" => $info['status'], "action_remark" => '', "action_type" => "edit"];
                ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname], $stn, "CKTHD",  $param['status'], $stn);

                if (in_array($param['status'], [1,2, 3])) {
                    if ($param['status'] == 2) $roleid = [10, 31, 41];//特殊处理,写入到10采购负责人、31库管人员、41库管-张凯旋这三个角色下的所有人
                    else $roleid = [31, 41];//特殊处理,写入到、31库管人员、41库管-张凯旋这三个角色下的所有人

                    $handle_user_list = Db::name('user_role')
                        ->where('is_del', 0)
                        ->whereIn('roleid', $roleid)
                        ->column('uid');

                    //如果是退货商品验收(节点1),把供应商负责人也加进去
                    if ($param['status'] == 1) $handle_user_list[] = $sale['cgderid'];

                    $process = ["order_code" => $param['thNo'], "order_id" => $info['id'], "order_status" => $param['status'], "order_type" => "CKTHD", "before_status" => $info['status'], 'handle_user_list' => implode(',', $handle_user_list)];

                } else $process = ["order_code" => $param['thNo'], "order_id" => $info['id'], "order_status" => $param['status'], "order_type" => "CKTHD", "before_status" => $info['status']];

                ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], $process);

                Db::commit();
                return app_show(0, '操作成功');
            } else throw new Exception('操作失败');

        } catch (Exception $exception) {

            Db::rollback();
            return error_show(1005, $exception->getMessage());
        }

    }
}