<?php
/*
|--------------------------------------------------------------------------
| 协商价格管理(原来的 “订单系统/协商价格” )
|--------------------------------------------------------------------------
|  增删改查导出
|  @author liXiaoLin
|  @Date: 2021/7/28
|  @Time: 15:11
|  @Email: lixiaolin@bluearp.com
|  @version 1.0
|  @copyright BlueCity
*/

namespace App\Http\Controllers\Service;

use App\Http\Controllers\BaseController;
use App\Models\Admin;
use App\Models\OrderMsg;
use App\Models\SetmoneyType;
use App\Models\SettlementList;
use App\Models\Negotiated;
use App\Models\Orders;
use App\Models\SettlementMoney;
use App\Models\Pt;
use App\Services\AdminService;
use App\Services\CommonService;
use App\Services\NegotiateService;
use App\Services\OrderService;
use App\Services\PlatformService;
use App\Services\SettlementService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Maatwebsite\Excel\Facades\Excel;
use League\Flysystem\Exception;

use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Traits\CurdControllerMethod;
use Illuminate\Http\Request;


class NegotiatedController extends BaseController
{
    public $dataService = null;  // CurdControllerMethod 必备参数
    public $dataFields = ['sup_startime', 'sup_endtime', 'sup_price', 'sup_brname', 'ser_id', 'goods_id'];  // 保存和修改时的 fields 参数
    protected $validateRules = [
        'rules' => [
            'sup_startime' => 'required',
            'sup_endtime' => 'required',
            'sup_price' => 'required|gt:0',
            'sup_brname' => 'required',
            'sup_serid' => 'required',
            'sup_goodids' => 'required'
        ],
        'messages' => [

        ],
        'attributes' => [
            'sup_startime' => '开始时间',
            'sup_endtime' => '结束时间',
            'sup_price' => '商品价格',
            'sup_brname' => '商品品牌',
            'sup_serid' => '商品型号',
            'sup_goodids' => '商品IDs'
        ]
    ];

    public function __construct()
    {
        $service = new NegotiateService();
        $this->bootWithService($service);
    }

    use CurdControllerMethod;

    /**|---------------------------------------------------------------------------------
     * @name 列表
     * @param type 0:未处理；1：已审核；2：已撤销
     * @param order_num
     * @param pt_id
     * @param page
     * @param page_size
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function index(Request $request)
    {
        $token = $request->input('token');
        $priID = $request->get('Pri_id');
        $searchRequest = $request->only('order_num', 'p_id', 'shr_phone', 'shr_name', 'ser_id', 'type', 'creatDate');
        $colums = ['*'];
        $page = Request()->input('page', 1);
        if ($page < 1) {
            $page = 1;
        }
        $pageSize = (int)Request()->input('page_size', 20);
        $session = $request->get('session_token');
        $data = $this->dataService->search($searchRequest, $colums, $page, $pageSize,$session);

        $data = $this->dataService->formatPageContent($token, $priID, $data,$request->input('Login_id'));

        if (!empty($data['list'])) {
            return $this->success('获取成功', $data);
        } else {
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name  审核申请
     * @param id 数据id
     * @param content 备注内容
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function negotiated_deal(Request $request)
    {
        $params = $request->only('id');
        $id = $params['id'] ?? "";
        if (empty($id)) {
            return $this->error('参数错误', ErrorInc::INVALID_PARAM);
        }
        $is_exist = NegotiateService::getOne($id);

        if ($is_exist['state'] > 0 ) {
            $statName = NegotiateService::getStateName();
            return $this->error('该订单已处理协商价格为'.$statName[$is_exist['state']], ErrorInc::REPEAT_SUBMIT);
        }
        $setArr = SettlementService::getSettled($is_exist['order_num']);
        if ($setArr) {
            return $this->error('该订单已申请结算，无法审核', ErrorInc::FAILED_PARAM);
        }
        $order_status = OrderService::getOrderBy('sys_num', $is_exist['sys_num'],['order_status']);//查询订单列表确保订单状态实施性
        if(!$order_status){
            return $this->error('订单数据异常（'.$is_exist['sys_num'].'）请联系管理员', ErrorInc::INVALID_PARAM);
        }
        if ($order_status < 30) {//未接单，不做处理仅未后续功能准备判定

        } elseif ($order_status >= 30) {//已接单，删除其他价格
            if($is_exist['msg_id']){
                $msg_id = $is_exist['msg_id'];
            }else{
                $msg_id = OrderMsg::where('sys_num', $is_exist['sys_num'])->where('goods_id', $is_exist['goods_id'])->value('id');
            }

            $info = SettlementService::getOneByMsgID($msg_id);
            if (empty($info)) {
                return $this->error('协商商品异常，请核实商品', ErrorInc::FAILED_PARAM);
            }
            $money['sem_slid'] = $info['id'];
            $money['sem_synum'] = $is_exist['sys_num'];
            $money['sem_price'] = $is_exist['negotiated_price'];
            $money['sem_creacter'] = $request->get('session_token')['admin_acc'];
            $money['sem_type'] = 15;
            $money['add_time'] = date("Y-m-d H:i:s");
            SettlementService::deleteMoney($info['id']);
            SettlementService::insertMoney($money);

            $this->dataService->update(['ser_id' => $info['ser_id']], $is_exist['id']);

            $all_price['all_price'] = DB::table('settlement_money')->where('sem_slid', $info['id'])->sum('sem_price');
            SettlementList::where('id', $info['id'])->update($all_price);

        }
        $res = $this->dataService->update(['state' => 1, 'updated_at' => date("Y-m-d H:i:s")], $id);
        if ($request->filled('content')) {
            $content = $request->input('content');
            CommonService::accMe($is_exist['sys_num'], "协商价格", $content, '', '', $request->get('session_token')['admin_groupnew'], $request->get('session_token')['admin_acc'], $request->get('session_token')['id']);
        }
        if ($res) {
            $this->insertingLog('审核申请，', $is_exist['sys_num'], '订单:' . $is_exist['sys_num'], '协商价格', $request->ip(), $request->get('session_token')['admin_acc']);//日志
            return $this->success('操作成功');
        } else {
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
        }
    }


    /**|---------------------------------------------------------------------------------
     * @name  撤销申请
     * @param id 数据id
     * @param content 备注内容
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function negotiated_delete(Request $request)
    {
        $id = $request->input('id');
        if ($id) {
            $is_exist = NegotiateService::getOne($id);
            if($is_exist) {
                if ($is_exist['state'] > 0 ) {
                    $statName = NegotiateService::getStateName();
                    return $this->error('该订单已处理协商价格为'.$statName[$is_exist['state']], ErrorInc::REPEAT_SUBMIT);
                }else {
                    $res = $this->dataService->update(['state' => 2, 'updated_at' => date("Y-m-d H:i:s")], $id);
                    if ($request->filled('content')) {
                        $content = $request->input('content');
                        CommonService::accMe($is_exist['sys_num'], "协商价格", $content, '', '', $request->get('session_token')['admin_groupnew'], $request->get('session_token')['admin_acc'], $request->get('session_token')['id']);
                    }
                    if ($res) {
                        $this->insertingLog('撤销申请，', $is_exist['sys_num'], '订单:' . $is_exist['sys_num'], '协商价格', $request->ip(), $request->get('session_token')['admin_acc']);//日志
                        return $this->success('操作成功');
                    } else {
                        return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
                    }
                }
            }else{
                return $this->error('数据不存在', ErrorInc::DATA_EMPTY);
            }
        } else {
            return $this->error('参数错误', ErrorInc::INVALID_PARAM);
        }
    }


    /**|---------------------------------------------------------------------------------
     * @name  同步状态
     * @param type 1:开始；2:暂停
     * @param time 时间
     * @param max_id 数据id
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function sync_state(Request $request)
    {
        $params = $request->only('type', 'time','max_id');
        $checkKey=CommonService::checkKey(['time', 'type'],$params,array('time'=>'更新时间','type'=>'操作类型'));
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $time = $params['time'] ?? "";
        $type = $params['type'] ?? "";
        if(!in_array($type, [1,2,3])){
            return $this->error('type参数错误', ErrorInc::FAILED_PARAM);exit;
        }
        if ($type == 1) {
            if ($request->filled('max_id')) {
                $max_id = $params['max_id'];
                $list = Negotiated::where('state', 0)->where('id', '>', $max_id)->orderBy('created_at', 'ASC')->orderBy('created_at', 'ASC')->limit('10')->get();
            } else {
                $list = Negotiated::where('state', 0)->orderBy('created_at', 'ASC')->limit('10')->get();
            }

            if (!$list->isEmpty()) {
                $info = $list->toArray();
                $ordersinfo = array_column($info, 'order_num');
                $admins = AdminService::getAdmins(['admin_groupnew'=>'2']);
                $admins = array_column($admins, 'admin_groupnew','id');
                $orderArr = Orders::whereIn('order_num', $ordersinfo)->select('order_status', 'order_num', 'ser_id')->get()->toArray();
                $orderss = CommonService::jointArrayKey($orderArr, 'order_num');
                foreach ($info as $ks => $vs) {
                    $max_arr[] = $vs['id'];
                    $poss['order_status'] = $orderss[$vs['order_num']]['order_status'];
                    if (isset($orderss[$vs['order_num']]['ser_id']) && isset($admins[$orderss[$vs['order_num']]['ser_id']])) {
                        $poss['ser_id'] = $orderss[$vs['order_num']]['ser_id'];
                        $poss['company_name'] = $admins[$orderss[$vs['order_num']]['ser_id']];
                    }

                    $poss['updated_at'] = date("Y-m-d H:i:s");
                    Negotiated::where('id', $vs['id'])->update($poss);
                }
                $data['data'] = $list->count();
                $data['max_id'] = max($max_arr);
                return response()->json(['Data' => $data, 'ErrorCode' => 1, 'ErrorMessage' => "操作成功"]);
            } else {
                return response()->json(['Data' => "", 'ErrorCode' => 2, 'ErrorMessage' => "操作完成"]);
            }

        } elseif ($type == 2) {
            $data['max_id'] = $params['max_id']??'';
            $data['data'] = 0;
            return response()->json(['Data' => $data, 'ErrorCode' => 4, 'ErrorMessage' => "暂停成功"]);
        } elseif ($type == 3) {
            $time = date("Y-m-d", strtotime($time . " +1 day"));
            $num = Negotiated::where('state', 1)->where('updated_at', '<', $time)->orderBy('created_at', 'ASC')->count();
            return response()->json(['Data' => $num, 'ErrorCode' => 4, 'ErrorMessage' => "获取成功"]);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 导出
     * @param type 1:未处理；2：已审核；5：已撤销
     * @param order_num
     * @param pt_id
     * @param page
     * @param page_size
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function export(Request $request)
    {
        $negotiated = new Negotiated();
        $params = $request->only('state', 'order_num', 'pt_id');
        $order_num = $order_num ?? "";
        $p_id = $p_id ?? "";
        $input = $request->only('order_num', 'p_id', 'shr_phone', 'shr_name', 'ser_id');
        if ($request->filled('type')) {
            $negotiated = $negotiated->where('state', $request->input('type'));
        }
        if ($request->filled('order_num')) {
            $negotiated = $negotiated->where('order_num', 'like', $input['order_num'] . "%");
        }
        if ($request->filled('p_id')) {
            $negotiated = $negotiated->where('p_id', $input['p_id']);
        }
        if ($request->filled('shr_phone')) {
            $negotiated = $negotiated->where('shr_phone', 'like', $input['shr_phone'] . "%");
        }
        if ($request->filled('shr_name')) {
            $negotiated = $negotiated->where('shr_name', 'like', $input['shr_phone'] . "%");
        }
        if ($request->filled('ser_id')) {
            $negotiated = $negotiated->where('ser_id', $input['ser_id']);
        }
        if ($request->filled('creatDate')) {
            $negotiated = $negotiated->whereBetween('created_at', $request->input('creatDate'));
        }
        $session = $request->get('session_token');
        if ($session['admin_groupnew'] != 7){//管理员可以看全部
            $negotiated = $negotiated->where('company_id',$session['company_id']);
        }

        //列表数据
        $list = $negotiated->when($order_num, function ($query) use ($order_num) {
            $query->where('order_num', 'like', $order_num . '%');
        })->when($p_id, function ($query) use ($p_id) {
            $query->where('p_id', $p_id);
        })->orderBy('created_at', 'ASC')->get();
        $ptArr = Pt::pluck('pt_name', 'id');
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            foreach ($list as $k => $v) {
                if ($v['order_status'] == 1) {
                    $list[$k]['order_status_name'] = "新订单";
                }
                if ($v['order_status'] == 5) {
                    $list[$k]['order_status_name'] = "处理中";
                }
                if ($v['order_status'] == 10) {
                    $list[$k]['order_status_name'] = "可派单";
                }
                if ($v['order_status'] == 20) {
                    $list[$k]['order_status_name'] = "已派单";
                }
                if ($v['order_status'] == 30) {
                    $list[$k]['order_status_name'] = "安装中";
                }
                if ($v['order_status'] == 34) {
                    $list[$k]['order_status_name'] = "待完成";
                }
                if ($v['order_status'] == 40) {
                    $list[$k]['order_status_name'] = "已完成";
                }
                if ($v['order_status'] == 50) {
                    $list[$k]['order_status_name'] = "订单已撤销";
                }

                if (empty($v['supply_price'])) {
                    $list[$k]['supply_price'] = 0;
                }
                if (!$v['company_name']) {
                    $list[$k]['company_name'] = "暂未派单";
                }
                if ($v['state'] == 0) {
                    $list[$k]['state_name'] = "未处理";
                } elseif ($v['state'] == 1) {
                    $list[$k]['state_name'] = "已处理";
                } elseif ($v['state'] == 2) {
                    $list[$k]['state_name'] = "已拒绝";
                }

                if (isset($ptArr[$v['p_id']])) {
                    $list[$k]['pt_name'] = $ptArr[$v['p_id']];
                }
            }
        }
        $session = $request->get('session_token');
        DB::connection()->enableQueryLog();#开启执行日志
        $excel_count = $negotiated->count();
        $query = DB::getQueryLog()[0];//sql数组

        $bindings = $query['bindings'];//sql参数
        $sql = $query['query'];//sql语句
        //正则替换
        foreach ($bindings as $replace) {
            $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
            $sql = preg_replace('/\?/', $value, $sql, 1);
        }
        if (empty($excel_count)) {
            return response()->json(['Data' => '', 'ErrorCode' => '2', 'ErrorMessage' => '暂无数据']);
        }
        $Automation = new Automation;
        $con_name = '协商价格';//控制器名称
        $action = 'Negotiated';//控制器
        $field_data = $Automation->gainFields($session['id'], $action);
        if (empty($field_data)) {
            return response()->json(['Data' => '', 'ErrorMessage' => '您暂时无导出权限', 'ErrorCode' => 3]);
        }
        //创建空excel
        // $file_path = $Automation->createExcel($field_data['field_name']);
        $name = 'xieshangjiage' . date('YmdHis');
        Excel::create($name, function ($excel) use ($list) {
            $excel->sheet('sheet1', function ($excel) use ($list) {
                $excel->cell('A1', function ($cell) {
                    $cell->setValue('平台');
                });
                $excel->cell('B1', function ($cell) {
                    $cell->setValue('平台单号');
                });
                $excel->cell('C1', function ($cell) {
                    $cell->setValue('商品名称');
                });
                $excel->cell('D1', function ($cell) {
                    $cell->setValue('姓名');
                });
                $excel->cell('E1', function ($cell) {
                    $cell->setValue('电话');
                });
                $excel->cell('F1', function ($cell) {
                    $cell->setValue('地址');
                });
                $excel->cell('G1', function ($cell) {
                    $cell->setValue('服务商');
                });
                $excel->cell('H1', function ($cell) {
                    $cell->setValue('订单状态');
                });
                $excel->cell('I1', function ($cell) {
                    $cell->setValue('原结算金额  ');
                });
                $excel->cell('J1', function ($cell) {
                    $cell->setValue('申请结算金额');
                });
                $excel->cell('K1', function ($cell) {
                    $cell->setValue('申请人');
                });
                $excel->cell('L1', function ($cell) {
                    $cell->setValue('申请时间');
                });
                $excel->cell('M1', function ($cell) {
                    $cell->setValue('申请原因');
                });

                foreach ($list as $key => $value) {
                    $i = $key + 2;
                    $value['address'] = $value['shr_sheng'] . $value['shr_shi'] . $value['shr_xian'] . $value['shr_adress'];
                    $excel->cell('A' . $i, $value['pt_name']);
                    $excel->cell('B' . $i, " " . $value['order_num']);
                    $excel->cell('C' . $i, $value['goods_name']);
                    $excel->cell('D' . $i, $value['shr_name']);
                    $excel->cell('E' . $i, $value['shr_phone']);
                    $excel->cell('F' . $i, $value['address']);
                    $excel->cell('G' . $i, $value['company_name']);
                    $excel->cell('H' . $i, $value['order_status_name']);
                    $excel->cell('I' . $i, $value['supply_price']);
                    $excel->cell('J' . $i, $value['negotiated_price']);
                    $excel->cell('K' . $i, $value['creator']);
                    $excel->cell('L' . $i, $value['created_at']);
                    $excel->cell('M' . $i, $value['negotiated_reason']);
                }
            });
        })->save('xls', public_path('excel'));
        $data = '/excel/' . $name . '.xls';
        $Automation->publicInsert($action, $con_name, $excel_count, $session, $data, $sql);

        return response()->json(['Data' => $data, 'ErrorCode' => 1, 'ErrorMessage' => '导出成功']);
    }
}
