package io.hmit.modules.serviceOrder.controller;

import com.alibaba.fastjson.JSON;
import io.hmit.annotation.Login;
import io.hmit.annotation.LoginUser;
import io.hmit.common.constant.Constant;
import io.hmit.common.page.PageData;
import io.hmit.common.utils.Result;
import io.hmit.common.validator.AssertUtils;
import io.hmit.common.validator.ValidatorUtils;
import io.hmit.common.validator.group.AddGroup;
import io.hmit.common.validator.group.DefaultGroup;
import io.hmit.common.validator.group.UpdateGroup;
import io.hmit.dto.UserInfoDTO;
import io.hmit.entity.UserEntity;
import io.hmit.modules.serviceOrder.dto.PensionOrderDTO;
import io.hmit.modules.serviceOrder.dto.ReservationDTO;
import io.hmit.modules.serviceOrder.dto.StaffFinishDTO;
import io.hmit.modules.serviceOrder.service.*;
import io.hmit.service.PushMessage;
import io.hmit.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;

/**
 * 订单表
 *
 * @author zsh 408538940@qq.com
 * @since 1.0.0 2021-01-26
 */
@RestController
@RequestMapping("serviceOrder/pensionorder")
@Api(tags="订单表")
public class PensionOrderController {
    @Autowired
    private PensionOrderService pensionOrderService;

    @Autowired
    private UserService userService;

    @Autowired
    private PensionOrderDocumentService pensionOrderDocumentService;

    @Autowired
    private PensionOrderEvaluationService pensionOrderEvaluationService;

    @Autowired
    private PensionServiceService pensionServiceService;

    @Autowired
    private PushMessage pushMessage;

    @Login
    @GetMapping("page")
    @ApiOperation("全部订单(志愿者)")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<PensionOrderDTO>> page(@ApiIgnore @LoginUser UserEntity user,
                                                  @ApiIgnore @RequestParam Map<String, Object> params){
        PageData<PensionOrderDTO> page = pensionOrderService.getAllOrderPage(params, user.getId());
        return new Result<PageData<PensionOrderDTO>>().ok(page);
    }

    @Login
    @GetMapping("getElderAllOrderOrByStatusList")
    @ApiOperation("全部/根据状态返回订单(老人)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = "status", value = "订单状态： 0未接单 1已接单 2已完成 3已取消", paramType = "query", dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<PensionOrderDTO>> getElderAllOrderOrByStatusList(@ApiIgnore @LoginUser UserEntity creator,
                                                                            @ApiIgnore @RequestParam Map<String, Object> params){
        Integer status = null;
        if (null != params.get("status")) {
            status = Integer.parseInt(params.get("status").toString());
        }
        PageData<PensionOrderDTO> page = pensionOrderService.getElderAllOrderOrByStatusPage(params, creator.getId(), status);
        return new Result<PageData<PensionOrderDTO>>().ok(page);
    }

    @Login
    @GetMapping("getOrderPageByStatus")
    @ApiOperation(value = "根据状态返回订单(志愿者)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = "status", value = "订单状态： 0未接单 1已接单 2已完成 3已取消", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<PensionOrderDTO>> getOrderPageByStatus(@ApiIgnore @LoginUser UserEntity user,
                                                                  @ApiIgnore @RequestParam Map<String, Object> params){
        PageData<PensionOrderDTO> page = pensionOrderService.getOrderPageByStatus(params, user.getId(), Integer.parseInt(params.get("status").toString()));
        return new Result<PageData<PensionOrderDTO>>().ok(page);
    }

    @Login
    @GetMapping("getTodayOrderPageWithCover")
    @ApiOperation("今日订单(志愿者)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = "status", value = "订单状态： 0未接单 1已接单 2已完成 3已取消", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<PensionOrderDTO>> getTodayOrderPageByStatus(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<PensionOrderDTO> page = pensionOrderService.getTodayOrderPage(params);
        return new Result<PageData<PensionOrderDTO>>().ok(page);
    }

    @Login
    @GetMapping("getElderTodayOrderPage")
    @ApiOperation("今日订单(老人)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<PensionOrderDTO>> getElderTodayOrderPage(@ApiIgnore @LoginUser UserEntity creator,
                                                                    @ApiIgnore @RequestParam Map<String, Object> params){
        PageData<PensionOrderDTO> page = pensionOrderService.getElderTodayOrderPage(params, creator.getId());
        return new Result<PageData<PensionOrderDTO>>().ok(page);
    }

    @Login
    @GetMapping("getAllOrderByCommunityUserIdPage")
    @ApiOperation("本社区全部订单(社工)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<PensionOrderDTO>> getAllOrderByCommunityUserIdPage(@ApiIgnore @LoginUser UserEntity user,
                                                                              @ApiIgnore @RequestParam Map<String, Object> params){
        PageData<PensionOrderDTO> page = pensionOrderService.getAllOrderByCommunityUserIdPage(params, user.getId());
        return new Result<PageData<PensionOrderDTO>>().ok(page);
    }

    @Login
    @GetMapping("getElderAllOrderByCommunityUserIdPage")
    @ApiOperation("查询本社区某老人全部订单(社工)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = "name", value = "需要查询老人的名字", paramType = "query",required = true, dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<PensionOrderDTO>> getElderAllOrderByCommunityUserIdPage(@ApiIgnore @LoginUser UserEntity user,
                                                                                   @ApiIgnore @RequestParam Map<String, Object> params){
        PageData<PensionOrderDTO> page = pensionOrderService.getElderAllOrderByCommunityUserIdPage(params, user.getId(), params.get("name").toString());
        return new Result<PageData<PensionOrderDTO>>().ok(page);
    }

    @Login
    @GetMapping("orderInfo/{id}")
    @ApiOperation("预约订单详情(志愿者)")
    public Result<PensionOrderDTO> getOrderInfo(@ApiIgnore @LoginUser UserEntity user,
                                                @PathVariable("id") Long id){
        PensionOrderDTO data = pensionOrderService.getOrderInfoByIdAndUserIdOrStatus(id, null, null);
        return new Result<PensionOrderDTO>().ok(data);
    }

    @Login
    @GetMapping("takingOrder/{id}")
    @ApiOperation("接单(志愿者)")
    public Result takingOrder(@ApiIgnore @LoginUser UserEntity user,
                              @PathVariable("id") Long id){
        PensionOrderDTO pensionOrderDTO = pensionOrderService.getOrderInfoByIdAndStatus(id, Constant.OrderStatus.BOOKED.geStatus());
        Date recipientTime = new Date();
        pensionOrderDTO.setOrderRecipientId(user.getId());
        pensionOrderDTO.setOrderRecipientName(user.getUsername());
        pensionOrderDTO.setOrderRecipientPhone(user.getMobile());
        pensionOrderDTO.setOrderRecipientTime(recipientTime);
        pensionOrderDTO.setUpdateDate(recipientTime);
        pensionOrderDTO.setStatus(Constant.OrderStatus.ORDER.geStatus());
        pensionOrderDTO.setStatusName("已接单");
        pensionOrderService.update(pensionOrderDTO);
        pushMessage.sendWeChatMsg(pensionOrderDTO, userService.getUserByUserId(pensionOrderDTO.getCreator()).getOpenid(), "oldman");

        return new Result();
    }

    //新订单接口

    /**
     * 服务人员订单接口
     */
    @Login
    @GetMapping("staff")
    @ApiOperation(value = "根据状态返回订单列表(服务人员)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = "status", value = "订单状态： 1待完成 2已完成 3已取消", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<PensionOrderDTO>> staff(@ApiIgnore @LoginUser UserEntity user,
                                                   @ApiIgnore @RequestParam Map<String, Object> params){
        PageData<PensionOrderDTO> page = pensionOrderService.getOrderPageByStatus(params, user.getId(), Integer.parseInt(params.get("status").toString()));
        return new Result<PageData<PensionOrderDTO>>().ok(page);
    }

    /**
     * 服务人员完成订单接口
     */
    @Login
    @PostMapping("staffFinishedOrder")
    @ApiOperation(value = "服务人员完成订单接口(服务人员)")
    public Result staffFinishedOrder(@RequestBody String dto){
        String todto = null;
        try {
            todto = URLDecoder.decode(dto,"UTF-8");
        }catch (Exception ignored){}
//        StaffFinishDTO staffFinishDTO = JSON.parseObject(todto.substring(4), StaffFinishDTO.class);
        StaffFinishDTO staffFinishDTO = JSON.parseObject(todto, StaffFinishDTO.class);
        pensionOrderService.staffFinishedOrder(staffFinishDTO);
        return new Result();
    }

    /**
     * 机构订单接口
     */
    @Login
    @GetMapping("organization")
    @ApiOperation(value = "根据状态返回订单列表(机构)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = "status", value = "订单状态： 0未接单 1已派发 2已完成 3已取消 5已接单未派发", paramType = "query", dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<PensionOrderDTO>> organization(@ApiIgnore @LoginUser UserEntity user,
                                                          @ApiIgnore @RequestParam Map<String, Object> params){
        //登录->查询登录人员所属机构ID->机构ID查询服务ID（List）->服务ID + 状态查询订单（List）
        PageData<PensionOrderDTO> page = pensionOrderService.getOrganizationOrder(params, user.getId());
        return new Result<PageData<PensionOrderDTO>>().ok(page);
    }

    /**
     * 老人、子女订单接口
     */
    @Login
    @GetMapping("elderFamily")
    @ApiOperation(value = "全部/根据状态返回订单(老人/子女)", notes = "老人、子女的待完成实际是机构处的已派发未接单+已接单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = "status", value = "订单状态： 6待完成 3已取消 4待评价 留空全部", paramType = "query", dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<PensionOrderDTO>> elderFamily(@ApiIgnore @LoginUser UserEntity user,
                                                         @ApiIgnore @RequestParam Map<String, Object> params){
        Integer status = null;
        if (null != params.get("status")) {
            status = Integer.parseInt(params.get("status").toString());
        }
        PageData<PensionOrderDTO> page = pensionOrderService.getElderAllOrderOrByStatusPage(params, user.getId(), status);
        return new Result<PageData<PensionOrderDTO>>().ok(page);
    }

    /**
     * 老人、子女取消订单
     */
    @Login
    @GetMapping("elderFamilyCancel")
    @ApiOperation(value = "老人、子女取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单ID", paramType = "query", required = true, dataType="long") ,
            @ApiImplicitParam(name = "cancel_reason", value = "订单取消原因", paramType = "query", dataType="String")
    })
    public Result elderFamilyCancel(@ApiIgnore @LoginUser UserEntity user,
                                    @ApiIgnore @RequestParam Map<String, Object> params){
        Boolean result = pensionOrderService.elderFamilyCancel(Long.parseLong(params.get("id").toString()), params.get("cancel_reason").toString());
        if (!result) {
            return new Result().error();
        }
        return new Result();
    }


    //新订单接口

    @GetMapping("{id}")
    @ApiOperation("信息")
    public Result<PensionOrderDTO> get(@PathVariable("id") Long id){
        PensionOrderDTO data = pensionOrderService.get(id);
        data.setStaffImages(pensionOrderDocumentService.findByOrderIdAndRemark(id, "1"));
        data.setStaffVoiceMessage(pensionOrderDocumentService.findStaffVoiceId(id));
        data.setUserImages(pensionOrderDocumentService.findByOrderIdAndRemark(id, "3"));
        data.setPensionOrderEvaluationDTO(pensionOrderEvaluationService.findByOrderId(id));
        data.setIcon(pensionServiceService.get(data.getServiceId()).getDetailPicture());
        return new Result<PensionOrderDTO>().ok(data);
    }

    @Login
    @PostMapping("reservationOrder")
    @ApiOperation("预约保存")
    public Result reservationOrder(@ApiIgnore @LoginUser UserEntity user, @RequestBody String dto){

        String todto = null;
        try {
            todto = URLDecoder.decode(dto,"UTF-8");
        }catch (Exception ignored){}
        ReservationDTO reservationDTO = JSON.parseObject(todto, ReservationDTO.class);

        PensionOrderDTO data = new PensionOrderDTO().assemblePensionOrder(reservationDTO,user);
        data.setCommunityId(user.getCommunityId());
        data.setCommunityName(user.getCommunityName());
        pensionOrderService.reservation(data);
        return new Result();
    }

    @PostMapping
    @ApiOperation("保存")
    public Result save(@RequestBody PensionOrderDTO dto){
        //校验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        pensionOrderService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    public Result update(@RequestBody PensionOrderDTO dto){
        //校验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        pensionOrderService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    public Result delete(@RequestBody Long[] ids){
        //校验数据
        AssertUtils.isArrayEmpty(ids, "id");

        pensionOrderService.delete(ids);

        return new Result();
    }

    /**
     * 本机构全部人员
     */
    @Deprecated
    @Login
    @GetMapping("organizationStaff2")
    @ApiOperation(value = "本机构全部人员(机构)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<UserEntity>> organizationStaff2(@ApiIgnore @LoginUser UserEntity user,
                                                          @ApiIgnore @RequestParam Map<String, Object> params){
        PageData<UserEntity> page = userService.getOrganizationAllUsers(params, user.getId());
        return new Result<PageData<UserEntity>>().ok(page);
    }

    /**
     * 本机构全部人员
     */
    @Login
    @GetMapping("organizationStaff")
    @ApiOperation(value = "本机构全部人员(机构)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType="int")
    })
    public Result<PageData<UserInfoDTO>> organizationStaff(@ApiIgnore @LoginUser UserEntity user,
                                                               @ApiIgnore @RequestParam Map<String, Object> params){
        PageData<UserInfoDTO> page = userService.getOrganizationStaff(params, user.getId());
        return new Result<PageData<UserInfoDTO>>().ok(page);
    }

    /**
     * 机构处理
     */
    @Login
    @GetMapping("organizationHandle")
    @ApiOperation(value = "机构处理(机构)", notes = "传参为1（派单）时，需要recipient_id和appointment_time；传参为3（取消）时，cancel_reason必传；")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单ID", paramType = "query", required = true, dataType="long") ,
            @ApiImplicitParam(name = "status", value = "处理状态： 5接单 1派单 3取消 4机构完成", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = "recipientId", value = "接单服务人员ID", paramType = "query", dataType="long") ,
            @ApiImplicitParam(name = "appointmentTime", value = "预约时间", paramType = "query", dataType="Date") ,
            @ApiImplicitParam(name = "cancelReason", value = "订单取消原因", paramType = "query", dataType="String"),
            @ApiImplicitParam(name = "remark", value = "备注", paramType = "query", defaultValue = "null", dataType="String")
    })
    public Result organizationHandle(@ApiIgnore @LoginUser UserEntity user,
                                     @ApiIgnore @RequestParam Map<String, Object> params){
        Boolean result = pensionOrderService.organizationHandle(params, user.getId());
        if (!result) {
            return new Result().error();
        }
        return new Result();
    }

}
