package com.ym.mec.web.controller;

import com.ym.mec.biz.dal.dao.StudentPaymentRouteOrderDao;
import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.dao.SellOrderDao;
import com.ym.mec.biz.dal.dao.StudentPaymentOrderDao;
import com.ym.mec.biz.dal.dto.BasicUserDto;
import com.ym.mec.biz.dal.dto.OutOrderInfoDto;
import com.ym.mec.biz.dal.dto.StudentPaymentRouteOrderDto;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.SellOrder;
import com.ym.mec.biz.dal.entity.StudentPaymentRouteOrder;
import com.ym.mec.biz.dal.enums.AuditStatusEnum;
import com.ym.mec.biz.dal.page.StudentPaymentOrderQueryInfo;
import com.ym.mec.biz.dal.page.StudentPaymentRouteOrderQueryInfo;
import com.ym.mec.biz.service.StudentPaymentRouteOrderService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.page.PageInfo;

@RequestMapping("routeOrder")
@Api(tags = "分润订单服务")
@RestController
public class StudentPaymentRouteOrderController extends BaseController {

    @Autowired
    private StudentPaymentRouteOrderService studentPaymentRouteOrderService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private StudentPaymentOrderDao studentPaymentOrderDao;
    @Autowired
    private SellOrderDao sellOrderDao;
    @Autowired
    private StudentPaymentRouteOrderDao studentPaymentRouteOrderDao;

    @ApiOperation(value = "财务订单列表")
    @GetMapping("/finance")
    @PreAuthorize("@pcs.hasPermissions('routeOrder/finance')")
    public HttpResponseResult<PageInfo<StudentPaymentRouteOrderDto>> queryOrderPage(StudentPaymentOrderQueryInfo queryInfo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getRoutingOrganId())) {
                queryInfo.setRoutingOrganId(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
                return failed("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getRoutingOrganId().split(",")))) {
                    return failed("非法请求");
                }
            }
        }
        if (StringUtils.isNotBlank(queryInfo.getSearch())) {
            List<BasicUserDto> users = studentPaymentOrderDao.getUsers(queryInfo.getSearch());
            List<Integer> userIds = users.stream().map(BasicUserDto::getUserId).collect(Collectors.toList());
            if (userIds.size() <= 0) {
                userIds.add(0);
            }
            queryInfo.setUserIds(userIds);
        }

        PageInfo<StudentPaymentRouteOrderDto> studentPaymentRouteOrderPageInfo = studentPaymentRouteOrderService.OrderQueryPage(queryInfo);
        return succeed(studentPaymentRouteOrderPageInfo);
    }

    @ApiOperation(value = "财务订单列表")
    @GetMapping("/queryPage")
    @PreAuthorize("@pcs.hasPermissions('routeOrder/queryPage')")
    public HttpResponseResult<PageInfo<StudentPaymentRouteOrder>> queryPage(StudentPaymentRouteOrderQueryInfo queryInfo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getOrganId())) {
                queryInfo.setOrganId(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
                return failed("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                    return failed("非法请求");
                }
            }
        }

        return succeed(studentPaymentRouteOrderService.queryAuditList(queryInfo));
    }

    @ApiOperation(value = "财务订单列表")
    @GetMapping("/query")
    @PreAuthorize("@pcs.hasPermissions('routeOrder/query')")
    public HttpResponseResult<StudentPaymentRouteOrder> query(Long id) {
    	StudentPaymentRouteOrder studentPaymentRouteOrder = studentPaymentRouteOrderService.get(id);
    	
        return succeed(studentPaymentRouteOrder);
    }


    @ApiOperation(value = "添加订单")
    @PostMapping("/add")
    @PreAuthorize("@pcs.hasPermissions('routeOrder/add')")
    public HttpResponseResult<StudentPaymentRouteOrder> add(@RequestBody StudentPaymentRouteOrder studentPaymentRouteOrder) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (studentPaymentRouteOrder.getServiceAmount() == null) {
        	studentPaymentRouteOrder.setServiceAmount(BigDecimal.ZERO);
        }
        if (studentPaymentRouteOrder.getSaleAmount() == null) {
        	studentPaymentRouteOrder.setSaleAmount(BigDecimal.ZERO);
        }
        studentPaymentRouteOrder.setCreateBy(sysUser.getId());
        studentPaymentRouteOrder.setUpdateBy(sysUser.getId());
        if(studentPaymentRouteOrder.getPayTime().after(new Date())){
            failed("交易日期不能大于当前时间");
        }

        return succeed(studentPaymentRouteOrderService.addOutOrder(studentPaymentRouteOrder));
    }


	@ApiOperation(value = "订单审核")
	@PostMapping("/auditOutOrder")
	@PreAuthorize("@pcs.hasPermissions('routeOrder/auditOutOrder')")
	public HttpResponseResult<String> auditOutOrder(Long studentPaymentRouteOrderId, AuditStatusEnum auditStatus, String memo) {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		studentPaymentRouteOrderService.auditOutOrder(studentPaymentRouteOrderId, auditStatus, memo, sysUser.getId());
		return succeed();
	}


    @ApiOperation(value = "修改订单")
    @PostMapping("/update")
    @PreAuthorize("@pcs.hasPermissions('routeOrder/update')")
    public HttpResponseResult<StudentPaymentRouteOrder> update(@RequestBody StudentPaymentRouteOrder studentPaymentRouteOrder) {
    	StudentPaymentRouteOrder originOrder = studentPaymentRouteOrderService.get(studentPaymentRouteOrder.getId());
    	if(originOrder == null){
    		return failed("参数不正确");
    	}
    	if(originOrder.getAuditStatus() != AuditStatusEnum.REJECT ){
    		return failed("只有“拒绝”状态才能修改订单");
    	}
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (studentPaymentRouteOrder.getServiceAmount() == null) {
        	studentPaymentRouteOrder.setServiceAmount(BigDecimal.ZERO);
        }
        if (studentPaymentRouteOrder.getSaleAmount() == null) {
        	studentPaymentRouteOrder.setSaleAmount(BigDecimal.ZERO);
        }
        studentPaymentRouteOrder.setUpdateBy(sysUser.getId());
        if(studentPaymentRouteOrder.getSchoolId() == null){
            studentPaymentRouteOrder.setSchoolId(999999999);
        }

        return succeed(studentPaymentRouteOrderService.updateOutOrder(studentPaymentRouteOrder));
    }

    @ApiOperation(value = "获取订单信息")
    @GetMapping("/getOrderInfo")
    @PreAuthorize("@pcs.hasPermissions('routeOrder/getOrderInfo')")
    public HttpResponseResult<OutOrderInfoDto> getOrderInfo(Long orderId) {
        OutOrderInfoDto outOrderInfoDto = new OutOrderInfoDto();
        StudentPaymentOrder order = studentPaymentOrderDao.get(orderId);
        outOrderInfoDto.setStudentPaymentOrder(order);
        StudentPaymentRouteOrder routeOrder = studentPaymentRouteOrderDao.getByOrderNo(order.getOrderNo());
        outOrderInfoDto.setCalenderId(routeOrder.getCalenderId());
        List<SellOrder> sellOrders = sellOrderDao.getOrderSellOrder(orderId);
        BigDecimal goodsAmount = sellOrders.stream().map(SellOrder::getActualAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal serviceAmount = outOrderInfoDto.getStudentPaymentOrder().getActualAmount().subtract(goodsAmount);
        outOrderInfoDto.setServiceAmount(serviceAmount);
        outOrderInfoDto.setGoodsAmount(goodsAmount);
        outOrderInfoDto.setSellOrders(sellOrders);
        return succeed(outOrderInfoDto);
    }

    @ApiOperation(value = "删除订单")
    @PostMapping("/delete")
    @PreAuthorize("@pcs.hasPermissions('routeOrder/delete')")
    public HttpResponseResult<Boolean> delete(Long orderId) {
        return succeed(studentPaymentRouteOrderService.deleteRouteOrder(orderId));
    }
}
