<?php


namespace app\admin\controller;

use app\admin\model\ActionLog;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\Validate;

//物流信息
class Express extends Base
{

    //获取快递公司列表
    public function list()
    {

        $param = $this->request->only(['page' => 1, 'size' => 10, 'type' => 0, 'name' => '', 'plat_type' => ''], 'post', 'trim');
        $where = [['type', '=', $param['type']]];
        if ($param['name'] != '') $where[] = ['name|shortName', 'like', '%' . $param['name'] . '%'];
        if ($param['plat_type'] != '') $where[] = ['plat_type', '=', $param['plat_type']];

        $count = Db::name('express')
            ->where($where)
            ->count('id');

        $list = Db::name("express")
            ->field('id,type,comTypeName,name,plat_type,shortName,shortNameEn,shortNumber,canOrder')
            ->where($where)
            ->page($param['page'], $param['size'])
            ->select()
            ->toArray();
        return app_show(0, '获取成功', ['list' => $list, 'count' => $count]);
    }

    //快递公司启禁用
    public function SetUse()
    {
        $param = $this->request->only(['id' => 0], 'post', 'trim');

        $express = Db::name('express')
            ->field('id,canOrder')
            ->where(['id' => $param['id']])
            ->findOrEmpty();
        if (empty($express)) return error_show(1004, '未找到数据');

        Db::startTrans();

        try {

            $express['canOrder'] = $express['canOrder'] == 0 ? 1 : 0;

            $up = Db::name('express')
                ->save($express);

            $orde = ['order_code' => $param['id'], 'status' => 0, 'action_remark' => '', 'action_type' => 'edit'];
            ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], $orde, 'express', 0, $orde);
            Db::commit();
            return $up ? app_show(0, '更新成功') : error_show(1005, '更新失败');
        } catch (Exception $exception) {
            Db::rollback();
            return json_show(1004, '更新失败,' . $exception->getMessage());
        }
    }

    //获取可用的快递公司列表
    public function GetExpress()
    {
        $type = isset($this->post['type']) && $this->post['type'] !== "" ? intval($this->post['type']) : '';
        $where[] = ['canOrder', "=", 1];
        if ($type === 0) {
            $where[] = ["type", "=", $type];
        }
        $order_source = isset($this->post['order_source']) && $this->post['order_source'] !== "" ? intval($this->post['order_source']) : '1';

        $plat_type = 1;
        if ($order_source == 5) {
            $plat_type = 2;
        }
        $where[] = ["plat_type", "=", $plat_type];
        $name = isset($this->post['name']) && $this->post['name'] != "" ? trim($this->post['name']) : '';
        if ($name != '') {
            $where[] = ["name|shortName", "like", "%{$name}%"];
        }
        $list = Db::name("express")->where($where)->field('id,type,comTypeName,name,shortName,shortNameEn,shortNumber,canOrder')
            ->select();
        return app_show(0, '获取成功', $list);
    }

    //SupplierExpress 相关数据表不存在,以下5个接口貌似无用
    //获取公司关联的快递公司
    public function getSupplierExpress()
    {

        $param = $this->request->only(['page'=>1,'size'=>10, 'key_supplierNo'=>''], 'post', 'trim');

        $where=[['a.is_del','=',0]];
        if($param['key_supplierNo']!='') $where[]=['a.supplierNo','like','%'.$param['key_supplierNo'].'%'];

        $count = Db::name('express_supplier')
            ->alias('a')
            ->leftJoin('supplier b','b.code=a.supplierNo')
            ->where($where)
            ->count('a.id');

        $rs = Db::name('express_supplier')
            ->field('a.id,a.supplierNo,a.addtime,a.status,a.express_ids,b.name supplierName')
            ->alias('a')
            ->where($where)
            ->leftJoin('supplier b','b.code=a.supplierNo')
            ->order('a.id','desc')
            ->page($param['page'],$param['size'])
            ->append(['express_list'])
            ->withAttr('express_list',function($val,$da){
                return Db::name('express')
                    ->field('id,name')
                    ->whereIn('id',$da['express_ids'])
                    ->order('id','desc')
                    ->select()
                    ->toArray();
            })
            ->select()
            ->toArray();

        return json_show(0, '操作成功',['count'=>$count,'list'=>$rs]);
    }

    //详情公司关联的快递公司
    public function infoSupplierExpress()
    {
        $id = $this->request->param('id/d', 0, 'trim');

        $rs = Db::name('express_supplier')
            ->field('a.*,b.name supplierName')
            ->alias('a')
            ->where(['a.id'=>$id,'a.is_del'=>0])
            ->leftJoin('supplier b','b.code=a.supplierNo')
            ->withAttr('express_ids',function($val,$da){
                return explode(',',$val);
            })
            ->findOrEmpty();

        return $rs ? json_show(0, '获取详情成功',$rs) : json_show(1004, '当前记录不存在');

    }

    //编辑公司关联的快递公司
    public function setSupplierExpress()
    {

        $param = $this->request->only(['express_ids', 'supplierNo'], 'post', 'trim');

        $val = Validate::rule([
            'express_ids|快递公司id集合' => 'require|array|max:100',
            'supplierNo|公司编码' => 'require|length:18'
        ]);

        if (!$val->check($param)) return json_show(1004, $val->getError());

        $tmp = Db::name('express_supplier')
            ->field('id')
            ->where('supplierNo', $param['supplierNo'])
            ->findOrEmpty();

        $date = date('Y-m-d H:i:s');
        if ($tmp) {
            $rs = Db::name('express_supplier')
                ->where('supplierNo', $param['supplierNo'])
                ->update([
                    'express_ids' => implode(',',$param['express_ids']),
                    'updatetime' => $date
                ]);
        } else {
            $rs = Db::name('express_supplier')
                ->where('supplierNo', $param['supplierNo'])
                ->insert([
                    'supplierNo' => $param['supplierNo'],
                    'express_ids' => implode(',',$param['express_ids']),
                    'addtime' => $date,
                    'updatetime' => $date
                ]);
        }

        return $rs ? json_show(0, '操作成功') : json_show(1004, '操作失败');
    }

    //启禁用公司关联的快递公司
    public function statusSupplierExpress()
    {
        $param = $this->request->only(['id', 'status'], 'post', 'trim');
        $val = Validate::rule([
            'id' => 'require|number|gt:0',
            'status|状态' => 'require|number|in:0,1'
        ]);
        if (!$val->check($param)) return json_show(1004, $val->getError());

        $tmp = Db::name('express_supplier')
            ->field('id,status')
            ->where('id', $param['id'])
            ->findOrEmpty();

        if (empty($tmp)) return json_show(1004, '该记录不存在');
        if ($tmp['status'] == $param['status']) return json_show(1005, '重复操作');

        $rs = Db::name('express_supplier')
            ->where('id', $param['id'])
            ->where('status', '<>', $param['status'])
            ->update([
                'status' => $param['status'],
                'updatetime' => date('Y-m-d H:i:s')
            ]);

        return $rs ? json_show(0, '操作成功') : json_show(1004, '操作失败');

    }

    //删除公司关联的快递公司
    public function deleteSupplierExpress()
    {
        $id = $this->request->param('id/d', 0, 'trim');

        $rs = Db::name('express_supplier')
            ->where(['id' => $id, 'is_del' => 0])
            ->update([
                'is_del' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ]);

        return $rs ? json_show(0, '删除成功') : json_show(1004, '删除失败,当前记录不存在');

    }


}