package com.sqx.modules.errand.controller.app;

import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
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.errand.entity.*;
import com.sqx.modules.errand.service.ErrandComplaintService;
import com.sqx.modules.errand.service.TbIndentService;
import com.sqx.modules.order.entity.Evaluate;
import com.sqx.modules.utils.SenInfoCheckUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/app/tbindent")
@Api(value = "订单", tags = {"订单"})
public class AppTbIndentController {

    @Autowired
    private TbIndentService tbIndentService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private ErrandComplaintService errandComplaintService;

    @Login
    @PostMapping(value = "distance")
    @ApiOperation("根据经纬度计算两点之间距离")
    public Result distance(double ol, double od, double dl, double dd){

        return tbIndentService.distance(ol, od, dl, dd);
    }

    @Login
    @ApiOperation("保存用户输入地址")
    @PostMapping(value = "addUserAddress")
    public Result addUserAddress(@RequestAttribute Long userId, @RequestBody ErrandAddress errandAddress){

        return tbIndentService.addUserAddress(userId, errandAddress);
    }

    @Login
    @ApiOperation("编辑地址")
    @PostMapping(value = "updateAddress")
    public Result updateAddress(@RequestAttribute Long userId, @RequestBody ErrandAddress errandAddress){

        return tbIndentService.updateAddress(userId, errandAddress);
    }

    @Login
    @ApiOperation("获取用户历史地址")
    @GetMapping(value = "findUserAddress")
    public Result findUserAddress(@RequestAttribute Long userId){

        return tbIndentService.findUserAddress(userId);
    }

    @Login
    @ApiOperation("根据地址id获取地址信息")
    @GetMapping(value = "findAddressById")
    public Result findAddressById(@RequestAttribute Long userId, Integer addressId){

        return tbIndentService.findAddressById(userId, addressId);
    }

    @Login
    @ApiOperation("设置默认地址")
    @GetMapping(value = "addDefaultAddress")
    private Result addDefaultAddress(@RequestAttribute Long userId, Integer addressId){

        return tbIndentService.addDefaultAddress(userId, addressId);
    }

    @Login
    @ApiOperation("删除历史地址")
    @GetMapping(value = "delUserAddress")
    public Result delUserAddress(@RequestAttribute Long userId, Integer addressId){

        return tbIndentService.delUserAddress(userId, addressId);
    }

    @Login
    @ApiOperation("获取订单起点附近5公里内所有骑手")
    @GetMapping(value = "find5KmRider")
    public Result find5KmRider(double lng, double lat){

        return tbIndentService.find5KmRider(lng, lat);
    }

    @Login
    @ApiOperation("骑手上线时更新骑手坐标")
    @PostMapping(value = "updateCoordinate")
    public Result updateCoordinate(@RequestAttribute Long userId, double lng, double lat){

        return tbIndentService.updateCoordinate(userId, lng, lat);
    }



    @Login
    @GetMapping(value = "/findUserInfoById")
    @ApiOperation("获取登陆用户信息")
    public Result findUserInfoById(@RequestAttribute("userId") Long userId){
        UserEntity userEntity = tbIndentService.findUserInfoById(userId);

        return Result.success().put("data", userEntity);
    }

    @Login
    @ApiOperation("新用户领取新人红包")
    @GetMapping(value = "getNewUserRedPacket")
    public Result getNewUserRedPacket(@RequestAttribute Long userId){

        return tbIndentService.getNewUserRedPacket(userId);
    }

    @Login
    @GetMapping(value = "findAllRedPacket")
    @ApiOperation("获取该用户的所有红包")
    public Result findAllRedPacket(@RequestAttribute Long userId){
        List<ErrandRedPacket> allRedPacket = tbIndentService.findAllRedPacket(userId);
        return Result.success().put("data", allRedPacket);
    }

    @Login
    @PostMapping(value = "findRedPacket")
    @ApiOperation("获取用户可用红包")
    public Result findRedPacket(@RequestAttribute Long userId, @RequestBody TbIndent indent){
        List<ErrandRedPacket> redPackets = tbIndentService.findRedPacket(userId, indent);
        return Result.success().put("data", redPackets);
    }

    @Login
    @PostMapping(value = "basicsMoney")
    @ApiOperation("计算订单基础价格")
    public Result basicsMoney(@RequestBody TbIndent tbIndent){

        return Result.success().put("data",tbIndentService.basicsMoney(tbIndent));
    }

    @Login
    @PostMapping(value = "addIndent")
    @ApiOperation("用户下单")
    public Result addIndentBuy(@RequestAttribute Long userId, @RequestBody TbIndent tbIndent){
        tbIndent.setUserId(userId);
        return tbIndentService.addIndentBuy(tbIndent);
    }

    @Login
    @PostMapping(value = "findNewIndent")
    @ApiOperation("骑手查看可接订单")
    public Result findNewIndent(@RequestAttribute Long userId, @RequestBody TbIndent tbIndent){
        String receivingPettern = tbIndent.getReceivingPettern();
        double riderlat = tbIndent.getRiderlng();
        double riderlng = tbIndent.getRiderlat();
        Integer page = tbIndent.getPage();
        Integer limit = tbIndent.getLimit();
        String indentType = tbIndent.getIndentType();
        String buyType = tbIndent.getBuyType();
        return tbIndentService.findNewIndent(userId, receivingPettern, page, limit, riderlng, riderlat, indentType, buyType);
    }

    @Login
    @PostMapping(value = "indentReceiving")
    @ApiOperation("骑手接单")
    public Result indentReceiving(@RequestAttribute Long userId, String indentNumber){

        return tbIndentService.indentReceiving(userId, indentNumber);
    }

    @Login
    @PostMapping(value = "riderBuyGoods")
    @ApiOperation("骑手修改订单状态")
    public Result riderBuyGoods(@RequestBody TbIndent tbIndent){

        return tbIndentService.riderBuyGoods(tbIndent);
    }

    @Login
    @GetMapping(value = "findUserIndent")
    @ApiOperation("用户查看自己所有订单（全部、待付款、待接单、派送中（已接单未完成）、已完成）")
    public Result findUserIndent(@RequestAttribute Long userId, Integer page, Integer limit,String indentState){

        return tbIndentService.findUserIndent(userId, page, limit,indentState);
    }


    @PostMapping(value = "userIndentMessage")
    @ApiOperation("用户查看订单详情")
    public Result userIndentMessage(String indentNumber) {
        TbIndent indent = tbIndentService.userIndentMessage(indentNumber);
        return Result.success().put("data", indent);
    }

    @Login
    @PostMapping(value = "userCancleIndent")
    @ApiOperation("用户取消订单")
    public Result userCancleIndent(@RequestAttribute Long userId, String indentNumber){

        return tbIndentService.userCancleIndent(userId, indentNumber);
    }

    @Login
    @GetMapping(value = "findRiderIndent")
    @ApiOperation("骑手查看自己所有订单")
    public Result findRiderIndent(@RequestAttribute Long userId, Integer page, Integer limit, String indentState){

        return tbIndentService.findRiderIndent(userId, page, limit, indentState);
    }

    @Login
    @PostMapping(value = "indentMessage")
    @ApiOperation("骑手查看订单详情")
    public Result indentMessage(String indentNumber, double ol, double od) {
        TbIndent tbIndent = tbIndentService.indentMessage(indentNumber, ol, od);
        return Result.success().put("data", tbIndent);
    }

    @PostMapping(value = "indentMessageByOrderId")
    @ApiOperation("骑手查看订单详情")
    public Result indentMessageByOrderId(Long orderId, double ol, double od) {
        TbIndent tbIndent = tbIndentService.indentMessageByOrderId(orderId, ol, od);
        return Result.success().put("data", tbIndent);
    }

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

    //骑手已送达
    @Login
    @PostMapping(value = "riderDelivery")
    @ApiOperation("骑手已送达")
    public Result riderDelivery(@RequestAttribute Long userId, String indentNumber, String itemCode){

        return tbIndentService.riderDelivery(userId, indentNumber, itemCode);
    }

    //用户确认已送达
    @Login
    @PostMapping(value = "userDelivery")
    @ApiOperation("用户确认已送达")
    public Result userDelivery(@RequestAttribute Long userId, String indentNumber){

        return tbIndentService.userDelivery(userId, indentNumber);
    }

    @Login
    @PostMapping(value = "userEvaluate")
    @ApiOperation("用户评价（评价等级和内容）")
    public Result userEvaluate(@RequestAttribute Long userId, @RequestBody ErrandEvaluate errandEvaluate){
        errandEvaluate.setUserId(userId);
        return tbIndentService.userEvaluate(errandEvaluate);
    }

    @ApiOperation("用户投诉订单")
    @PostMapping(value = "insertComplaint")
    public Result insertComplaint(@RequestBody ErrandComplaint errandComplaint){

        return errandComplaintService.insertComplaint(errandComplaint);
    }

    @Login
    @ApiOperation("用户查看所有投诉")
    @GetMapping(value = "selectComplaint")
    public Result selectComplaint(@RequestAttribute Long userId, Integer page, Integer limit){

        return errandComplaintService.selectComplaint(userId, page, limit);
    }

    @Login
    @GetMapping(value = "findAllComplaint")
    @ApiOperation("骑手查看自己的所有被投诉")
    public Result findAllComplaint(@RequestAttribute Long userId, Integer illegalId, Integer complaintState, Integer page, Integer limit){

        return errandComplaintService.findAllComplaint(userId,illegalId, complaintState, page, limit);
    }

    @Login
    @GetMapping(value = "findComplaint")
    @ApiOperation("骑手查看被投诉内容")
    public Result findComplaint(@RequestAttribute Long userId, Long complaintId){

        return errandComplaintService.findComplaint(userId,complaintId);
    }

    @Login
    @PostMapping(value = "appealIndent")
    @ApiOperation("骑手提交申诉")
    public Result appealIndent(@RequestAttribute Long userId, @RequestBody ErrandComplaint errandComplaint){

        return errandComplaintService.appealIndent(userId, errandComplaint);
    }

    @Autowired
    private UserService userService;


    @Login
    @ApiOperation("转单")
    @PostMapping("/transferOfOrder")
    public Result transferOfOrder(Long indentId,String phone){
        UserEntity userEntity = userService.queryByPhone(phone);
        if(userEntity==null){
            return Result.error("用户不存在！");
        }
        CommonInfo one1 = commonInfoService.findOne(273);
        Double cashDeposit = Double.parseDouble(one1.getValue());
        if(!"1".equals(userEntity.getCheckCertification())){
            return Result.error("骑手未进行实名认证！");
        }
        if(userEntity.getCashDeposit().doubleValue()<cashDeposit){
            return Result.error("骑手保证金不足！");
        }

        TbIndent indent = tbIndentService.getById(indentId);
        if(userEntity.getUserId().equals(indent.getRiderUserId())){
            return Result.error("不能转给自己！");
        }
        if(!"3".equals(indent.getIndentState())){
            return Result.error("订单状态发生变更，请刷新后重试！");
        }
        indent.setRiderUserId(userEntity.getUserId());
        indent.setIsRider(1);
        tbIndentService.updateById(indent);
        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.getOpenId())){
            userService.pushToSingle("更换骑手","骑手已更换，新骑手将尽快为您送达",user.getClientid());
        }
        return Result.success();
    }



}
