<?php

namespace app\api\controller;

use app\api\service\auth\MysqlAdapter;
use app\common\model\ScanLog;
use app\common\model\StockConfig;
use app\api\service\StockService;
use app\common\model\StockLog;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use app\api\validate\Worker as WorkerValidate;
use think\facade\Cache;
use think\facade\Db;
use think\Response;
use app\common\model\GroupUser as GroupUserModel;
use app\api\controller\GroupUser as GroupUserController;
use app\common\model\ShopDelivery as ShopDeliveryModel;
use app\common\model\WorkerOut as WorkerOutModel;
use app\common\model\PackSpecs as PackSpecsModel;

/**
 * 打包工人相关接口
 */
class Worker extends Base
{
    protected $shopDeliveryModel = null;
    protected $groupUserController = null;
    protected $quantity_sum = 0;
    protected $labor_cost_money_sum = 0;
    protected $quantity_avg = 0;
    protected $labor_cost_money_avg = 0;
    protected $worker_num = 0;
    protected $worker_list = [];
    protected $time = null;



    /**
     * 判断权限
     * @access protected
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->shopDeliveryModel = new ShopDeliveryModel();
        $this->groupUserController = new GroupUserController();
        if (!str_contains($this->userinfo['role'], "1")) {
            $this->error(__('没有权限' . $this->userinfo['role']));
        }
    }
    //首页
    public function index(StockConfig $stockConfig, ScanLog $scanLog)
    {
        $data = [];
        $data['today'] = ScanLog::where('user_id', $this->userinfo['id'])->whereTime('createtime', 'today')->count();
        $data['yesterday'] = ScanLog::where('user_id', $this->userinfo['id'])->whereTime('createtime', 'yesterday')->count();

        $todayTime = date("Y-m-d");
        $startTime = strtotime($todayTime . ' 00:00:00');
        $startTime = date('Y-m-d H:i:s', $startTime);
        $endTime = strtotime($todayTime . ' 23:59:59');
        $endTime = date('Y-m-d H:i:s', $endTime);
        $time = $startTime . ',' . $endTime;

        $arr = explode(',', $time);
        $where[] = ['sl.createtime', '>=', strtotime($arr[0])];
        $where[] = ['sl.createtime', '<=', strtotime($arr[1])];

        $pid = $this->userinfo['id'];
        $where[] = ['sl.user_id', '=', $pid];


        $list = $scanLog->alias('sl')
            ->join("shop_delivery sd", "sl.code = sd.waybill_no", "INNER")
            ->where('sl.order_status', 1)
            ->where('sl.spec_id', '<>', null)
            ->where($where)
            ->field("sl.code,sl.spec_id,SUM(COALESCE(sd.num,0) * 1) as pack_count,SUM(COALESCE(sd.num,0) * COALESCE(sd.labor_cost_money,0)) as pack_money")
            ->group('sl.spec_id')
            ->select()->each(function ($item, $key) {
                $spec_name = $this->get_order_info($item['code']);
                $item['pack_name'] = $spec_name;
                unset($item['code']);
            });

        $data['pack_specs'] = $list;
        // $data['pack_specs'] = [
        //     [
        //         'pack_name' => '三斤',
        //         'pack_count' => '120',
        //         'pack_money' => '100'
        //     ],
        //     [
        //         'pack_name' => '五斤',
        //         'pack_count' => '120',
        //         'pack_money' => '100'
        //     ],
        //     [
        //         'pack_name' => '五斤保温',
        //         'pack_count' => '120',
        //         'pack_money' => '100'
        //     ],

        // ];
        $this->success('ok', $data);
    }

    //添加出入库
    public function scan(ScanLog $scanLog)
    {
        $data = $this->request->post();
        $result = false;
        Db::startTrans();
        $insert_data = [];
        try {
            validate(WorkerValidate::class)->scene('scan')->check($data);

            //$resData = $stockService::setGoOutStock($this->userinfo['id'], $data);
            $time = time();
            $insert_data = [
                'user_id'    => $this->userinfo['id'],
                'code'       => $data['code'],
                'order_status' => 0,
                'remark' => '未找到单号',
                'order_data' => [],
                'createtime' => date('Y-m-d H:i:s', $time)
            ];
            $sql_data = $this->shopDeliveryModel->where('waybill_no', $data['code'])->find();
            if (!empty($sql_data)) {
                switch ($sql_data['order_status']) {
                    case 'TRADE_CLOSED':
                        $insert_data['order_status']=3;
                        $insert_data['remark'] = '已退款';
                        break;

                    default:
                        if (!empty($sql_data['user_id']) && $sql_data['user_id'] != 0) {
                            $insert_data['order_status'] = 2;
                            $insert_data['remark'] = '请勿重复录入';
                        } else {
                            $result = $sql_data->save([
                                'user_id'    =>   $this->userinfo['id'],
                                'entry_time'    =>    $time,
                                'updatetime' =>    $time
                            ]);
                            if ($result) {
                                $insert_data['order_status'] = 1;
                                $insert_data['remark'] = '录入成功';
                                $insert_data['spec_id'] = $sql_data['spec_id'];
                            } else {
                                $insert_data['remark'] = '录入失败';
                            }
                        }

                        $entry_time = $sql_data['entry_time'];
                        if (!empty($sql_data['entry_time'])) {
                            $entry_time = date('Y-m-d H:i:s', $sql_data['entry_time']);
                        }
                        switch ($sql_data['incubator']) {
                            case 1:
                                $sql_data['incubator_title'] = '单层保温';
                                break;
                            case 2:
                                $sql_data['incubator_title'] = '双层保温';
                                break;
                            default:
                                $sql_data['incubator_title'] = '不是保温箱';
                                break;
                        }
                        $sql_data['entry_time'] = $entry_time;
                        $insert_data['order_data'] = $sql_data;
                        break;
                }
            }
            $result = $scanLog->save($insert_data);


            Db::commit();
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('没有新增任何数据'));
        }
        $this->success('', $insert_data);
    }

    //扫描记录
    public function scanlog(ScanLog $scanLog)
    {
        $where = [];
        $limit = $this->request->post('limit/d', 10);  //条数
        $time = $this->request->post('create_time/s'); //日期
        // if (!empty($type))    $where[] = ['a.type', '=', $type];
        // if (!empty($type_id)) $where[] = ['a.type_id', '=', $type_id];
        // if (!empty($spec_id)) $where[] = ['a.variety_id', '=', $spec_id];
        if (!empty($time)) {
            $arr = explode(',', $time);
            $where[] = ['sl.createtime', '>=', strtotime($arr[0])];
            $where[] = ['sl.createtime', '<=', strtotime($arr[1])];
        }

        $list = $scanLog->alias('sl')
            ->where('user_id', $this->userinfo['id'])
            ->whereIn('order_status', [0, 1, 2])
            ->where($where)
            ->order('createtime desc')
            ->paginate($limit)
            ->each(function ($item, $key) {
                $order_data = $this->shopDeliveryModel->where('waybill_no', $item['code'])->find();
                $item['order_data'] = [];
                if (!empty($order_data['waybill_no'])) {
                    $incubator_title = '不是保温箱';
                    switch ($order_data['incubator']) {
                        case 1:
                            $incubator_title = '单层保温';
                            break;
                        case 2:
                            $incubator_title = '双层保温';
                            break;
                    }
                    $item['order_data'] = $order_data;
                    $item['order_data']['incubator_title'] = $incubator_title;
                }
                return $item;
            });
        $this->success('ok', $list);
    }

    //数据统计，今日昨日,本周
    public function pack_data_statistics(ScanLog $scanLog, GroupUserModel $groupUserModel)
    {
        $where = [];
        $limit = $this->request->post('limit/d', 10);  //条数
        $todayTime = date("Y-m-d");
        $startTime = strtotime($todayTime . ' 00:00:00');
        $startTime = date('Y-m-d H:i:s', $startTime);
        $endTime = strtotime($todayTime . ' 23:59:59');
        $endTime = date('Y-m-d H:i:s', $endTime);
        $time = $startTime . ',' . $endTime;

        $time = $this->request->post('create_time/s', $time); //日期
        $this->time = $time;
        if (!empty($time)) {
            $arr = explode(',', $time);
            $where[] = ['sl.createtime', '>=', strtotime($arr[0])];
            $where[] = ['sl.createtime', '<=', strtotime($arr[1])];
        }

        $pid = $this->userinfo['id'];
        $where[] = ['sl.user_id', '=', $pid];


        $list = $scanLog->alias('sl')
            ->join("shop_delivery sd", "sl.code = sd.waybill_no", "INNER")
            ->where('sl.order_status', 1)
            ->where('sl.spec_id', '<>', null)
            ->where($where)
            ->field("sl.code,sl.spec_id,SUM(COALESCE(sd.num,0) * 1) as spec_quantity_sum,SUM(COALESCE(sd.num,0) * COALESCE(sd.labor_cost_money,0)) as spec_labor_cost_money_sum")
            ->group('sl.spec_id')
            ->paginate($limit)->each(function ($item, $key) {
                $spec_name = $this->get_order_info($item['code']);
                $item['spec_name'] = $spec_name;
                unset($item['code']);
            });
        $list_sum = $scanLog->alias('sl')
            ->join("shop_delivery sd", "sl.code = sd.waybill_no", "INNER")
            ->where('sl.order_status', 1)
            ->where('sl.spec_id', '<>', null)
            ->where($where)
            ->field("sl.code,sl.spec_id,SUM(COALESCE(sd.num,0) * 1) as spec_quantity_sum,SUM(COALESCE(sd.num,0) * COALESCE(sd.labor_cost_money,0)) as spec_labor_cost_money_sum")
            ->group('sl.spec_id')
            ->select();
        $quantity_sum = 0;
        $labor_cost_money_sum = 0;
        foreach ($list_sum as $item) {
            $spec_quantity_sum = $item['spec_quantity_sum'];
            $spec_labor_cost_money_sum = $item['spec_labor_cost_money_sum'];
            $quantity_sum = bcadd(strval($quantity_sum), strval($spec_quantity_sum), 0);
            $labor_cost_money_sum = bcadd(strval($labor_cost_money_sum), strval($spec_labor_cost_money_sum), 4);
            $labor_cost_money_sum = round((float)$labor_cost_money_sum, 2);
        }

        $data = [
            'quantity_sum' => $quantity_sum,
            'labor_cost_money_sum' => $labor_cost_money_sum,
            'list' => empty($list) ? [] : $list


        ];
        $this->success('ok', $data);
    }
    //获取数量、总价
    public function quantity_labor_cost_money(ScanLog $scanLog)
    {
        $where = [];
        $todayTime = date("Y-m-d");
        $startTime = strtotime($todayTime . ' 00:00:00');
        $startTime = date('Y-m-d H:i:s', $startTime);
        $endTime = strtotime($todayTime . ' 23:59:59');
        $endTime = date('Y-m-d H:i:s', $endTime);
        $time = $startTime . ',' . $endTime;

        $time = $this->request->post('create_time/s', $time); //日期
        $this->time = $time;
        if (!empty($time)) {
            $arr = explode(',', $time);
            $where[] = ['sl.createtime', '>=', strtotime($arr[0])];
            $where[] = ['sl.createtime', '<=', strtotime($arr[1])];
        }

        $pid = $this->userinfo['id'];
        $where[] = ['sl.user_id', '=', $pid];

        $list_sum = $scanLog->alias('sl')
            ->join("shop_delivery sd", "sl.code = sd.waybill_no", "INNER")
            ->where('sl.order_status', 1)
            ->where('sl.spec_id', '<>', null)
            ->where($where)
            ->field("sl.code,sl.spec_id,SUM(COALESCE(sd.num,0) * 1) as spec_quantity_sum,SUM(COALESCE(sd.num,0) * COALESCE(sd.labor_cost_money,0)) as spec_labor_cost_money_sum")
            ->group('sl.spec_id')
            ->select();
        $quantity_sum = 0;
        $labor_cost_money_sum = 0;
        foreach ($list_sum as $item) {
            $spec_quantity_sum = $item['spec_quantity_sum'];
            $spec_labor_cost_money_sum = $item['spec_labor_cost_money_sum'];
            $quantity_sum = bcadd(strval($quantity_sum), strval($spec_quantity_sum), 0);
            $labor_cost_money_sum = bcadd(strval($labor_cost_money_sum), strval($spec_labor_cost_money_sum), 4);
            $labor_cost_money_sum = round((float)$labor_cost_money_sum, 2);
        }

        $data = [
            'quantity_sum' => $quantity_sum,
            'labor_cost_money_sum' => $labor_cost_money_sum
        ];
        return $data;
    }
    //获取今天出工人员状态，0=未出个，1=出工
    public function get_worker_out_state($id, $pid, $time)
    {
        $groupUserModel = new GroupUserModel();
        $count = $groupUserModel->where('id', $id)->where('pid', $pid)->count();
        if ($count == 0) return 1;

        $workerOutModel = new WorkerOutModel();
        $todayTime = strtotime('today');
        $where = [];
        $where[] = ['user_id', '=', $id];
        $where[] = ['pid', '=', $pid];
        $where[] = ['state', '=', 1];
        if (!empty($time)) {
            $arr = explode(',', $time);
            $where[] = ['createtime', '>=', strtotime($arr[0])];
            $where[] = ['createtime', '<=', strtotime($arr[1])];
        }
        return $workerOutModel->where($where)->count();
    }
    public function get_order_info($waybill_no)
    {
        return $this->shopDeliveryModel->where('waybill_no', $waybill_no)->value('spec_name');
    }
}
