<?php

namespace app\admin\controller\warehouse_order;


use app\admin\controller\BaseAdminController;
use app\admin\lists\warehouse_order\WarehouseOrderLists;
use app\admin\logic\store_product\StoreProductLogic;
use app\admin\logic\warehouse_order\WarehouseOrderLogic;
use app\admin\logic\warehouse_product\WarehouseProductLogic;
use app\admin\validate\warehouse_order\WarehouseOrderValidate;
use app\common\model\store_branch_product\StoreBranchProduct;
use app\common\model\store_order\StoreOrder;
use app\common\model\store_product\StoreProduct;
use app\common\model\store_product_unit\StoreProductUnit;
use app\common\model\supplier\Supplier;
use app\common\model\system_store\SystemStore;
use app\common\model\warehouse_order\WarehouseOrder;
use app\common\model\warehouse_product\WarehouseProduct;
use app\common\model\warehouse_product_storege\WarehouseProductStorege;
use app\common\service\xlsx\Beforehand;
use app\common\service\xlsx\OrderDetail;
use app\common\service\xlsx\WarehouseOrdeRentry;
use support\exception\BusinessException;
use support\Log;
use think\facade\Db;

/**
 * 仓储商品单控制器
 * Class WarehouseOrderController
 * @package app\admin\controller\warehouse_order
 */
class WarehouseOrderController extends BaseAdminController
{


    /**
     * @notes 获取仓储商品单列表
     * @return \think\response\Json
     * @author admin
     * @date 2024/08/20 10:50
     */
    public function lists()
    {

        return $this->dataLists(new WarehouseOrderLists());
    }


    /**
     * @notes 添加入库单
     * @return \think\response\Json
     * @author admin
     * @date 2024/08/20 10:50
     */
    public function add()
    {
        $params = $this->request->post();
        $params['admin_id'] = $this->adminId;
        $result = WarehouseOrderLogic::add($params);
        if (true === $result) {
            return $this->success('添加成功', [], 1, 1);
        }
    }
    /**
     * @notes 添加出库单
     * @return \think\response\Json
     * @author admin
     * @date 2024/08/20 10:50
     */
    public function outbound()
    {
        $product_arr = $this->request->post('product_arr');
        $warehouse_id = $this->request->post('warehouse_id');
        $delivery_time = $this->request->post('delivery_time');
        $mark = $this->request->post('mark');
        $type = $this->request->post('order_type', 1);
        Db::startTrans();
        try {
            if($type==1){
                $code=getNewOrderId('TGY');
            }else{
                $code=getNewOrderId('BS');
            }
            $arr = [
                'warehouse_id' => $warehouse_id,
                'store_id' => 0,
                'supplier_id' => 0,
                'code' => $code,
                'admin_id' => $this->adminId,
                'financial_pm' => 0,
                'batch' => 0,
                'mark' => $mark ?? "",
            ];
            $arr['delivery_time'] = strtotime($delivery_time);
            $res = WarehouseOrder::create($arr);
            foreach ($product_arr as $key => $arr) {
                $data = [
                    'warehouse_id' => $warehouse_id,
                    'product_id' => $arr['id'],
                    'store_id' => 0,
                    'financial_pm' => 0,
                    'batch' => 1,
                    'nums' => $arr['stock'],
                    'status' => 1,
                    'admin_id' => $this->adminId,
                    'type' => $type,
                    'order_type' => 0,
                ];
                $storeProduct = StoreProduct::where('id', $arr['id'])->find();
                $data['total_price'] = bcmul($arr['stock'], $storeProduct['purchase'], 2);
                $data['purchase'] = $storeProduct['purchase'];
                $data['oid'] = $res['id'];
                $data['financial_pm'] = 0;
                $data['price'] = $storeProduct['price'];
                WarehouseProductLogic::setOutbound($data,1,$this->adminId);
                $finds = WarehouseProduct::where('oid', $res['id'])->field('sum(nums) as nums,sum(total_price) as total_price')->find();
                WarehouseOrder::where('id', $res['id'])->update(['total_price' => $finds['total_price'], 'nums' => $finds['nums']]);
            }
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return $this->success('出库成功', [], 1, 1);
    }


    /**
     * @notes 编辑仓储商品单
     * @return \think\response\Json
     * @author admin
     * @date 2024/08/20 10:50
     */
    public function edit()
    {
        $params = $this->request->post();
        $params['admin_id'] = $this->adminId;
        $result = WarehouseOrderLogic::edit($params);
        if (true === $result) {
            return $this->success('编辑成功', [], 1, 1);
        }
    }

    /**
     * @notes 编辑仓储商品单
     * @return \think\response\Json
     * @author admin
     * @date 2024/08/20 10:50
     */
    public function update_edit()
    {
        $params = $this->request->post();
        $result = WarehouseOrderLogic::update_edit($params);
        if (true === $result) {
            return $this->success('编辑成功', [], 1, 1);
        }
        return $this->fail('编辑失败');
    }

    /**
     * @notes 删除仓储商品单
     * @return \think\response\Json
     * @author admin
     * @date 2024/08/20 10:50
     */
    public function delete()
    {
        $params = (new WarehouseOrderValidate())->post()->goCheck('delete');
        WarehouseOrderLogic::delete($params);
        return $this->success('删除成功', [], 1, 1);
    }


    /**
     * @notes 获取仓储商品单详情
     * @return \think\response\Json
     * @author admin
     * @date 2024/08/20 10:50
     */
    public function detail()
    {
        $params = (new WarehouseOrderValidate())->goCheck('detail');
        $result = WarehouseOrderLogic::detail($params);
        return $this->data($result);
    }
    /**
     * 入库表格
     */
    public function rentry_export()
    {
        $id = $this->request->post('id');
        $xlsx = new WarehouseOrdeRentry();
        $order = WarehouseOrder::where('id', $id)->findOrEmpty();
        $data = WarehouseProduct::where('oid', $id)->select();
        $order['total_num'] = 0;
        $credit_pay = 0;
        $cash_pay = 0;
        foreach ($data as $key => &$value) {
            $find = StoreProduct::where('id', $value->product_id)->withTrashed()->find();
            $value->store_name = $find['store_name'] ?? '';
            $value->store_info = $find['store_info'] ?? '';
            if (!empty($find['unit'])) {
                $value->unit_name = StoreProductUnit::where('id', $find['unit'])->value('name');
            } else {
                $value->unit_name = '';
            }
            $order['total_num'] += $value->nums;
            $value->supplier_name = Supplier::where('id', $value->supplier_id)->value('mer_name');
            if ($value->pay_type == 1) {
                $credit_pay += $value->total_price;
                $value->pay_type_name = '赊账';
            } elseif ($value->pay_type == 2) {
                $cash_pay += $value->total_price;
                $value->pay_type_name = '现款';
            } else {
                $value->pay_type_name = '未设置';
            }
        }
        $order['credit_pay'] = $credit_pay;
        $order['cash_pay'] = $cash_pay;
        $file_path = $xlsx->export($data, $order);

        return $this->success('导出成功', ['url' => $file_path]);
    }

    /**
     * 出库表格
     */
    public function export()
    {
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        if (in_array($type, [2, 3])) {
            return $this->fail('暂不支持此操作');
        }
        $xlsx = new OrderDetail();
        $order = WarehouseOrder::where('id', $id)->findOrEmpty();
        $system_store = SystemStore::where('id', $order['store_id'])->value('name');
        $data = WarehouseProduct::where('oid', $id)->select();
        $order['total_num'] = 0;
        $total_price = 0;
        foreach ($data as $key => &$value) {
            if (in_array($order['store_id'], [17, 18])) {
                $find = StoreBranchProduct::where('product_id', $value->product_id)->where('store_id', $order['store_id'])->withTrashed()->find();
            } else {
                $find = StoreProduct::where('id', $value->product_id)->withTrashed()->find();
            }
            $value->store_name = $find['store_name'] ?? '';
            $value->store_info = $find['store_info'] ?? '';
            // if($type==2){
            //     $value->price = $value['purchase'];
            //     $value->total_price=bcmul($value['purchase'],$value['nums'],2);
            //     $total_price+=$value->total_price;
            // }elseif($type==3){
            //     $value->price = $find['cost'];
            //     $value->total_price=bcmul($find['cost'],$value['nums'],2);
            //     $total_price+=$value->total_price;
            // }elseif($type==4){
            //     $value->price = $find['price'];
            //     $value->total_price=bcmul($find['price'],$value['nums'],2);
            //     $total_price+=$value->total_price;
            // }else{
            if ($type == 1) {
                $value->price = $value['purchase'];
                $value->total_price = bcmul($value['purchase'], $value['nums'], 2);
                $total_price += $value->total_price;
            }


            // }
            $value->cart_num = $value['nums'];
            if (!empty($find['unit'])) {
                $value->unit_name = StoreProductUnit::where('id', $find['unit'])->value('name');
            } else {
                $value->unit_name = '';
            }
            $order['total_num'] += $value->nums;
        }
        if ($type == 2) {
            $order['total_price'] = $total_price;
        }
        $order['delivery_time'] = date('Y-m-d H:i:s', $order['delivery_time']);
        $order['pay_time'] = $order['create_time'];
        $order['order_id'] = $order['code'];

        if ($order['oid'] > 0) {
            $orders = StoreOrder::where('id', $order['oid'])->findOrEmpty();
            $order['real_name'] = $orders['real_name'];
            $order['user_phone'] = $orders['user_phone'];
            $order['user_address'] = $orders['user_address'];
        }
        $file_path = $xlsx->export($data, $system_store, $order);

        return $this->success('导出成功', ['url' => $file_path]);
    }

    /**
     * 导出标签
     */
    public function export_tags()
    {
        $id = $this->request->post('id');
        $warehouseOrder = WarehouseOrder::where('id', $id)->field('oid,store_id,delivery_time')->find();
        $system_store = SystemStore::where('id', $warehouseOrder['store_id'])->value('introduction');
        $data = WarehouseProduct::where('oid', $id)->where('financial_pm', 0)->field('oid,product_id,nums')->select()
            ->each(function ($item) use ($system_store, $warehouseOrder) {
                $find = StoreProduct::where('id', $item['product_id'])->field('store_name,unit')->withTrashed()->find();
                $unit_name = StoreProductUnit::where('id', $find['unit'])->value('name');
                $item['system_store'] = $system_store;
                $item['subtitle'] = $item['oid'] . '  ' . convertStringToNumber($item['nums']) . '/' . $unit_name;
                $item['store_name'] = $find['store_name'];
                if ($warehouseOrder['oid']) {
                    $find = StoreOrder::where('id', $warehouseOrder['oid'])->field('real_name,user_address')->find();
                    if ($find) {
                        $item['address'] = $find['real_name'] . '  ' . $find['user_address'];
                    } else {
                        $item['address'] = '无地址';
                    }
                } else {
                    $item['address'] = '无地址';
                }
            })
            ->toArray();
        $file_path = (new Beforehand())->export($data, $system_store);
        return $this->success('导出成功', ['url' => $file_path]);
    }
}