package com.ym.mec.web.controller;

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.StudentPaymentOrderDao;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.dto.BasicUserDto;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
import com.ym.mec.biz.dal.page.SporadicOrderQueryInfo;
import com.ym.mec.biz.dal.page.StudentPaymentOrderQueryInfo;
import com.ym.mec.biz.service.StudentPaymentOrderDetailService;
import com.ym.mec.biz.service.StudentPaymentOrderService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.page.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RequestMapping("order")
@Api(tags = "订单服务")
@RestController
public class StudentPaymentOrderController extends BaseController {

    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private StudentPaymentOrderDao studentPaymentOrderDao;

    @ApiOperation(value = "获取订单列表")
    @GetMapping("/queryPage")
    @PreAuthorize("@pcs.hasPermissions('order/queryPage')")
    public Object 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.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("非法请求");
                }
            }
        }
        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<StudentPaymentOrder> studentPaymentOrderPageInfo = studentPaymentOrderService.OrderQueryPage(queryInfo);

        int openHideMode = Integer.parseInt(sysConfigDao.findConfigValue("open_hide_mode"));
        if (openHideMode == 1) {
            for (StudentPaymentOrder row : studentPaymentOrderPageInfo.getRows()) {
                if (row.getComAmount() != null) {
                    BigDecimal balancePaymentAmount = row.getBalancePaymentAmount() == null ? BigDecimal.ZERO : row.getBalancePaymentAmount();
                    BigDecimal comAmount = row.getComAmount() == null ? BigDecimal.ZERO : row.getComAmount();
                    row.setExpectAmount(comAmount.add(balancePaymentAmount));
                    row.setActualAmount(comAmount.add(balancePaymentAmount));
                }
            }
        }
        return succeed(studentPaymentOrderPageInfo);
    }

    @ApiOperation(value = "获取零星收费订单列表")
    @GetMapping("/sporadicQueryPage")
    @PreAuthorize("@pcs.hasPermissions('order/sporadicQueryPage')")
    public Object sporadicQueryPage(SporadicOrderQueryInfo 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(studentPaymentOrderService.sporadicQueryPage(queryInfo));
    }

    @ApiOperation(value = "获取订单列表1")
    @GetMapping("/queryPage1")
    @PreAuthorize("@pcs.hasPermissions('order/queryPage1')")
    public Object queryOrderPage1(StudentPaymentOrderQueryInfo 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("非法请求");
                }
            }
        }
        queryInfo.setOrderType("1");

        PageInfo<StudentPaymentOrder> studentPaymentOrderPageInfo = studentPaymentOrderService.OrderQueryPage(queryInfo);

        for (StudentPaymentOrder row : studentPaymentOrderPageInfo.getRows()) {
            BigDecimal balancePaymentAmount = row.getBalancePaymentAmount() == null ? BigDecimal.ZERO : row.getBalancePaymentAmount();
            BigDecimal comAmount = row.getComAmount() == null ? BigDecimal.ZERO : row.getComAmount();
            if (row.getComAmount() != null) {
                row.setExpectAmount(comAmount.add(balancePaymentAmount));
                row.setActualAmount(comAmount.add(balancePaymentAmount));
            }
        }
        return succeed(studentPaymentOrderPageInfo);
    }

    @ApiOperation(value = "获取订单列表2")
    @GetMapping("/queryPage2")
    @PreAuthorize("@pcs.hasPermissions('order/queryPage2')")
    public Object queryOrderPage2(StudentPaymentOrderQueryInfo 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("非法请求");
                }
            }
        }
        queryInfo.setOrderType("2");

        PageInfo<StudentPaymentOrder> studentPaymentOrderPageInfo = studentPaymentOrderService.OrderQueryPage(queryInfo);

        for (StudentPaymentOrder row : studentPaymentOrderPageInfo.getRows()) {
            BigDecimal balancePaymentAmount = row.getBalancePaymentAmount() == null ? BigDecimal.ZERO : row.getBalancePaymentAmount();
            BigDecimal perAmount = row.getPerAmount() == null ? BigDecimal.ZERO : row.getPerAmount();
            if (row.getPerAmount() != null) {
                row.setExpectAmount(perAmount.add(balancePaymentAmount));
                row.setActualAmount(perAmount.add(balancePaymentAmount));
            }
        }
        return succeed(studentPaymentOrderPageInfo);
    }

    @ApiOperation(value = "获取乐器采购清单")
    @GetMapping("/getMusicalList")
    @PreAuthorize("@pcs.hasPermissions('order/getMusicalList')")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "String")})
    public Object getMusicalList(String musicGroupId) {
        return succeed(studentPaymentOrderDetailService.getMusicalList(musicGroupId));
    }

    @ApiOperation(value = "乐器清单确认")
    @GetMapping("/verifyMusicalList")
    @PreAuthorize("@pcs.hasPermissions('order/verifyMusicalList')")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "String")})
    public Object verifyMusicalListMusicalList(String musicGroupId) {
        return succeed(studentPaymentOrderDetailService.verifyMusicalList(musicGroupId));
    }

    @ApiOperation(value = "财务订单列表")
    @GetMapping("/finance")
    @PreAuthorize("@pcs.hasPermissions('order/finance')")
    public Object financeOrder(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("非法请求");
                }
            }
        }

        PageInfo<StudentPaymentOrder> studentPaymentOrderPageInfo = studentPaymentOrderService.OrderQueryPage(queryInfo);
        return succeed(studentPaymentOrderPageInfo);
    }


    @ApiOperation(value = "查询订单状态")
    @GetMapping("/getOrderStatus")
    @PreAuthorize("@pcs.hasPermissions('order/getOrderStatus')")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "订单id", required = true, dataType = "int")})
    public HttpResponseResult<Boolean> getOrderStatus(Long id) throws Exception {
        return succeed(studentPaymentOrderService.getOrderStatus(id));
    }


}
