package com.sqx.modules.errand.controller;

import com.sqx.common.exception.SqxException;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.datacentre.query.DataCenterQuery;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.errand.entity.TransferRecordEntity;
import com.sqx.modules.errand.service.TbIndentService;
import com.sqx.modules.errand.service.TransferRecordService;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.order.service.AppOrderService;
import com.sqx.modules.riderStation.entity.RiderStation;
import com.sqx.modules.riderStation.service.RiderStationService;
import com.sqx.modules.utils.SenInfoCheckUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/admin/tbindent")
@Api(value = "管理端-跑腿订单", tags = {"管理端-跑腿订单"})
public class TbIndentController {

    @Autowired
    private TbIndentService tbIndentService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private AppOrderService appOrderService;
    @Autowired
    private RiderStationService riderStationService;
    @Autowired
    private TransferRecordService transferRecordService;

    @ApiOperation("查看所有派单任务")
    @GetMapping(value = "findallIndent")
    public Result findallIndent(Integer page, Integer limit, Long userId, Long riderUserId, Long shopId,Integer indentType,String ordersNo,Integer status,String riderPhone){

        return tbIndentService.findallIndent(page, limit, userId, riderUserId, shopId,indentType,ordersNo,status,riderPhone);
    }

    @ApiOperation("任务中心 查看所有订单")
    @PostMapping(value = "findAllIndent")
    public Result findAllIndent(String indentType, String phone, String indentState, Integer page, Integer limit, String date, String dateType,String riderPhone){

        return tbIndentService.findAllIndent(indentType, phone, indentState, page, limit, date, dateType,riderPhone);
    }

    @ApiOperation("任务中心 查看所有订单")
    @PostMapping(value = "findAllIndents")
    public Result findAllIndents(String indentType, String phone, String indentState, Integer page, Integer limit, String date, String dateType,String riderPhone){

        return tbIndentService.findAllIndents(indentType, phone, indentState, page, limit, date, dateType,riderPhone);
    }

    @ApiOperation("订单中心")
    @PostMapping(value = "IndentCenter")
    public Result IndentCenter(Integer page, Integer limit, String indentType, String indentNumber, String indentState, String phone, String date, String dateType){

        return tbIndentService.IndentCenter(page, limit, indentType, indentNumber, indentState, phone, date, dateType);
    }

    @ApiOperation("管理端修改订单状态")
    @PostMapping(value = "updateIndentState")
    public Result updateIndentState(String indentNumber, String indentState){

        return tbIndentService.updateIndentState(indentNumber, indentState);
    }

    @ApiOperation("管理员下架订单")
    @PostMapping(value = "adminSoldOutIndent")
    public Result adminSoldOutIndent(String indentNumber){

        return tbIndentService.adminSoldOutIndent(indentNumber);
    }


    @PostMapping(value = "riderCancleIndent")
    @ApiOperation("骑手取消订单")
    public Result riderCancleIndent(String indentNumber){
        return tbIndentService.riderCancleIndent(indentNumber,2);
    }

    @ApiOperation("数据中心")
    @GetMapping(value = "findDataCenter")
    public Result findDataCenter(){

        return tbIndentService.findDataCenter();
    }

    @ApiOperation("任务分析")
    @GetMapping(value = "taskAnalysis")
    public Result taskAnalysis(DataCenterQuery query, String indentState){

        return tbIndentService.taskAnalysis(query, indentState);
    }

    @ApiOperation("订单分析")
    @GetMapping(value = "selectOrderByStatus")
    public Result selectOrderByStatus(DataCenterQuery query){

        return tbIndentService.selectOrderByStatus(query);
    }

    @ApiOperation("骑手收入统计 完成订单数统计")
    @GetMapping(value = "findIncome")
    public Result findIncome(Long userId, String date, String dateType, Integer page, Integer limit){

        return tbIndentService.findIncome(userId, date, dateType, page, limit);
    }


    @ApiOperation("转单")
    @PostMapping("/transferOfOrder")
    public Result transferOfOrder(Long indentId,Long riderUserId){
        TbIndent indent = tbIndentService.getById(indentId);
        if("5".equals(indent.getIndentType())){
            TbOrder tbOrder = appOrderService.getById(indent.getOrderId());
            if(tbOrder.getAutoSendOrder()!=null && tbOrder.getAutoSendOrder()==1){
                return Result.error("商家配送不允许转单！");
            }
        }

        if (!"3".equals(indent.getIndentState()) && !"4".equals(indent.getIndentState())) {
            throw new SqxException("订单状态发生变更，请刷新后重试！");
        }

        UserEntity indentuserEntity = userService.selectUserById(indent.getRiderUserId());
        if(indentuserEntity == null){
            throw new SqxException("订单骑手已失效，无法发起转单！");
        }

        UserEntity userEntity = userService.selectUserById(riderUserId);
        if(userEntity == null){
            throw new SqxException("被转单骑手已失效，无法发起转单！");
        }

        if(userEntity.getRiderStationId().intValue() != indentuserEntity.getRiderStationId().intValue()){
            throw new SqxException("无法选择其他站点骑手进行转单操作！");
        }

        CommonInfo one1 = commonInfoService.findOne(273);
        Double cashDeposit = Double.parseDouble(one1.getValue());
        if(userEntity.getCashDeposit().doubleValue()<cashDeposit){
            return Result.error("骑手保证金不足！");
        }
        if(!"1".equals(userEntity.getCheckCertification())){
            return Result.error("骑手未进行实名认证！");
        }

        if(indent.getRiderUserId()!=null && userEntity.getUserId().equals(indent.getRiderUserId())){
            return Result.error("不能选择相同的骑手！");
        }
        indent.setRiderUserId(riderUserId);
        indent.setIsRider(1);
        tbIndentService.updateById(indent);
        //获取站点内容
        RiderStation station = riderStationService.stationById(userEntity.getRiderStationId());
        if(station != null){
            userEntity.setStationName(station.getStationName());
        }
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        TransferRecordEntity tr = new TransferRecordEntity();
        tr.setUserId(userEntity.getUserId());
        tr.setUserName(userEntity.getUserName());
        tr.setUserPhone(userEntity.getPhone());
        tr.setOrderId(indent.getOrderId());
        tr.setReceveTime(format);
        tr.setStationName(station.getStationName());
        tr.setDeleteFlag(0);
        transferRecordService.insertPrintInfo(tr);

        UserEntity user = userService.getById(indent.getUserId());
        CommonInfo one = commonInfoService.findOne(335);
        List<String> msgList=new ArrayList<>();
        msgList.add(0,indent.getIndentNumber());
        if("3".equals(indent.getIndentState())){
            msgList.add(1,"已接单");
        }else if("4".equals(indent.getIndentState())){
            msgList.add(1,"已取货");
        }else{
            msgList.add(1,"进行中");
        }
        msgList.add(2,"骑手已更换，新骑手将尽快为您送达");
        msgList.add(3, DateUtils.format(new Date()));
        if(StringUtils.isNotEmpty(user.getOpenId())){
            SenInfoCheckUtil.sendMsg(user.getOpenId(),one.getValue(),msgList,5);
        }
        if(StringUtils.isNotEmpty(user.getClientid())){
            userService.pushToSingle("更换骑手","骑手已更换，新骑手将尽快为您送达",user.getClientid());
        }
        return Result.success();
    }


}
