package com.bs.df.controller;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.annotation.TableField;
import com.bs.common.annotation.Anonymous;
import com.bs.common.constant.Constants;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.utils.SecurityUtils;
import com.bs.common.utils.ServletUtils;
import com.bs.df.domain.DfBizClue;
import com.bs.df.domain.DfBroker;
import com.bs.df.mapper.DfBizClueMapper;
import com.bs.df.mapper.DfOrderMapper;
import com.bs.df.service.IDfBizClueService;
import com.bs.df.service.IDfBrokerService;
import com.bs.system.mapper.SysUserMapper;
import com.bs.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;
import com.bs.df.domain.DfOrder;
import com.bs.df.service.IDfOrderService;

import javax.annotation.Resource;

/**
 * 客户订单Controller
 *
 * @author bs
 * @date 2024-04-06
 */
@Api(tags = "客户订单")
@RestController
@RequestMapping("/order/order")
public class DfOrderController extends BaseController {
    @Resource
    private IDfOrderService dfOrderService;
    @Resource
    private IDfBrokerService dfBrokerService;
    @Resource
    private ISysUserService userService;
    @Resource
    private DfOrderMapper dfOrderMapper;
    @Resource
    private IDfBizClueService dfBizClueService;
    @Resource
    private DfBizClueMapper dfBizClueMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 分页查询客户订单列表
     */
    @ApiOperation("分页查询客户订单列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(DfOrder dfOrder) {
        Integer pageNum = ServletUtils.getParameterToInt(Constants.PAGE_NUM);
        Integer pageSize = ServletUtils.getParameterToInt(Constants.PAGE_SIZE);
        SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
        if (sysUser.getDeptId().equals(-1L)) {
            dfOrder.setBrokerId(null);
        }
        LambdaQueryWrapper<DfOrder> queryWrapper = new LambdaQueryWrapper();
        if (Validator.isEmpty(dfOrder.getOrderByColumn())) {
            queryWrapper.orderByDesc(DfOrder::getSubmitTime);
        }
        if (Validator.isNotEmpty(dfOrder.getUserOrProduct())) {
            queryWrapper.like(DfOrder::getUserName, dfOrder.getUserOrProduct())
                    .or()
                    .like(DfOrder::getProductName, dfOrder.getUserOrProduct());
        }
        condition(queryWrapper, dfOrder);
        boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if (!admin) {
            if (!sysUser.getDeptId().equals(-1L)) {
                SysUser byId = userService.getById(SecurityUtils.getUserId());
                if ("jj".equals(byId.getUserType())) {
                    queryWrapper.eq(DfOrder::getBrokerId, SecurityUtils.getUserId());
                }
            }
        }
        String orderByColumn = dfOrder.getOrderByColumn();
        String isAsc = dfOrder.getIsAsc();
        if (StringUtils.isNotEmpty(orderByColumn) && StringUtils.isNotEmpty(isAsc)) {
            applyOrderBy(queryWrapper, orderByColumn, isAsc);
        }
        List<DfOrder> list = dfOrderService.list(queryWrapper);
        List<DfOrder> dfOrders = setOrderList(list);
        if (StringUtils.isNotEmpty(dfOrder.getBrokerName())) {
            dfOrders = dfOrders.stream()
                    .filter(info -> info.getBrokerName() != null && info.getBrokerName().contains(dfOrder.getBrokerName()))
                    .collect(Collectors.toList());
        }
        Integer start = (pageNum - 1) * pageSize;
        List<DfOrder> result = dfOrders.stream()
                .skip(start)
                .limit(pageSize)
                .collect(Collectors.toList());
        TableDataInfo data = getDataTable(result);
        data.setTotal(dfOrders.size());
        return data;
    }

    public void applyOrderBy(LambdaQueryWrapper<DfOrder> queryWrapper, String orderName, String orderType) {
        boolean isAsc = "ASC".equalsIgnoreCase(orderType);
        switch (orderName) {
            case "orderNo":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getOrderNo);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getOrderNo);
                }
                break;
            case "userName":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getUserName);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getUserName);
                }
                break;
            case "productName":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getProductName);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getProductName);
                }
                break;
            case "submitTime":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getSubmitTime);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getSubmitTime);
                }
                break;
            case "applyAmount":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getApplyAmount);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getApplyAmount);
                }
                break;
            case "limitAmount":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getLimitAmount);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getLimitAmount);
                }
                break;
            case "loanAmount":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getLoanAmount);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getLoanAmount);
                }
                break;
            case "loanRate":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getLoanRate);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getLoanRate);
                }
                break;
            case "loadMonth":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getLoadMonth);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getLoadMonth);
                }
                break;
            case "isFirst":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getIsFirst);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getIsFirst);
                }
                break;
            case "settleAmount":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getSettleAmount);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getSettleAmount);
                }
                break;
            case "staus":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getStaus);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getStaus);
                }
                break;
            case "remark":
                if (isAsc) {
                    queryWrapper.orderByAsc(DfOrder::getRemark);
                } else {
                    queryWrapper.orderByDesc(DfOrder::getRemark);
                }
                break;

            default:
                queryWrapper.orderByDesc(DfOrder::getSubmitTime);

                break;
        }
    }

    private List<DfOrder> setOrderList(List<DfOrder> list) {
        List<SysUser> userList = userService.list();
        Map<Long, String> userIdToRealNameMapVo = userList.stream()
                .filter(user -> user != null && user.getUserId() != null && user.getRealName() != null)
                .collect(Collectors.toMap(SysUser::getUserId, SysUser::getRealName));
        Map<Long, String> userIdToPhoneMapVo = userList.stream()
                .filter(user -> user != null && user.getUserId() != null && user.getPhonenumber() != null)
                .collect(Collectors.toMap(SysUser::getUserId, SysUser::getPhonenumber));
        Map<Long, String> userIdToNickNameMapVo = userList.stream()
                .filter(user -> user != null && user.getUserId() != null && user.getNickName() != null)
                .collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));

        Map<Long, String> userIdToNameMapVo = userList.stream()
                .filter(user -> user != null && user.getUserId() != null && user.getUserName() != null)
                .collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));
        list.forEach(order -> {
            String realName = userIdToRealNameMapVo.get(order.getBrokerId());
            String nickName = userIdToNickNameMapVo.get(order.getBrokerId());
            String userName = userIdToNameMapVo.get(order.getBrokerId());
            String phone = userIdToPhoneMapVo.get(order.getBrokerId());
            if (Validator.isEmpty(realName)) {
                if (Validator.isEmpty(nickName)) {
                    order.setBrokerName(userName);
                } else {
                    order.setBrokerName(nickName);
                }
            } else {
                order.setBrokerName(realName);
            }
            order.setBrokerPhone(phone);
        });
        return list;
    }

    /**
     * 查询客户订单列表
     */
    @ApiOperation("查询客户订单列表")
    @GetMapping("/list")
    public AjaxResult list(DfOrder dfOrder) {
        LambdaQueryWrapper<DfOrder> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper, dfOrder);
        queryWrapper.orderByDesc(DfOrder::getCreateTime);
        List<DfOrder> list = dfOrderService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出客户订单列表
     */
    @ApiOperation("导出客户订单列表")
    @Log(title = "客户订单导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DfOrder dfOrder) {
        LambdaQueryWrapper<DfOrder> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.orderByDesc(DfOrder::getSubmitTime);
        condition(queryWrapper, dfOrder);
        boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if (!admin) {
            SysUser byId = userService.getById(SecurityUtils.getUserId());
            if ("jj".equals(byId.getUserType())) {
                queryWrapper.eq(DfOrder::getBrokerId, SecurityUtils.getUserId());
            }
        }
        List<DfOrder> list = dfOrderService.list(queryWrapper);
        List<DfOrder> dfOrders = setOrderList(list);
        dfOrders.forEach(order -> {
            String isFirst = order.getIsFirst();
            if (StringUtils.isNotEmpty(isFirst)) {
                String isFirstDisplay = isFirst.equals("1") ? "是" : "否";
                order.setIsFirst(isFirstDisplay);
            }
        });
        if (StringUtils.isNotEmpty(dfOrder.getUserName())) {
            dfOrders = dfOrders.stream()
                    .filter(info -> info.getUserName() != null && info.getUserName().contains(dfOrder.getUserName()))
                    .collect(Collectors.toList());
        }
        if (StringUtils.isNotEmpty(dfOrder.getBrokerName())) {
            dfOrders = dfOrders.stream()
                    .filter(info -> info.getBrokerName() != null && info.getBrokerName().contains(dfOrder.getBrokerName()))
                    .collect(Collectors.toList());
        }
        if (StringUtils.isNotEmpty(dfOrder.getPhone())) {
            dfOrders = dfOrders.stream()
                    .filter(info -> info.getPhone() != null && info.getPhone().contains(dfOrder.getPhone()))
                    .collect(Collectors.toList());
        }
        ExcelUtil<DfOrder> util = new ExcelUtil<DfOrder>(DfOrder.class);
        util.exportExcel(response, dfOrders, "客户订单数据");
    }

    /**
     * 获取客户订单详细信息
     */
    @ApiOperation("获取客户订单详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        DfOrder byId = dfOrderService.getById(id);
        List<SysUser> list = userService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, byId.getBrokerId()));
        if (!list.isEmpty()) {
            String realName = list.get(0).getRealName();
            if (Validator.isEmpty(realName)) {
                String nickName = list.get(0).getNickName();
                if (Validator.isEmpty(nickName)) {
                    String userName = list.get(0).getUserName();
                    byId.setBrokerName(userName);
                } else {
                    byId.setBrokerName(nickName);
                }
            } else {
                byId.setBrokerName(realName);
            }
            String phonenumber = list.get(0).getPhonenumber();
            byId.setBrokerPhone(phonenumber);
        }
        return success(byId);
    }

    /**
     * 新增客户订单
     */
    @PostMapping
    public AjaxResult add(@RequestBody DfOrder dfOrder) {
        return toAjax(dfOrderService.save(dfOrder));
    }


    /**
     * 新增客户订单
     */
    @ApiOperation("新增客户订单")
    @PostMapping("/visitorAdd")
    @Anonymous
    public AjaxResult visitorAdd(@RequestBody DfOrder dfOrder) {
//        SysUser sysUser = sysUserMapper.selectById(dfOrder.getShareUser());
//        if (sysUser == null) {
//            return AjaxResult.warn("链接有误");
//        }
//        List<Long> productIdsByBrokerId = dfBrokerService.getProductIdsByBrokerIdByUserId(Long.valueOf(dfOrder.getShareUser()));
//        Long productId = Long.valueOf(dfOrder.getProductId());
//        if (!productIdsByBrokerId.contains(productId)) {
//            return AjaxResult.warn("链接有误");
//        }
        Date date = new Date();
        dfOrder.setCreateTimeVo(date);
        String billNumber = dfOrderService.getBillNumber("RK");
        dfOrder.setOrderNo(billNumber);
        dfOrder.setTenantId(0L);
        dfOrderMapper.insertOrder(dfOrder);
        List<DfOrder> dfOrders = dfOrderService.list(new LambdaQueryWrapper<DfOrder>().eq(DfOrder::getOrderNo, billNumber)
                .orderByDesc(DfOrder::getCreateTime));
//        if (Validator.isNotEmpty(dfOrder.getShareUser())) {
//            List<DfBizClue> list = dfBizClueService.list(new LambdaQueryWrapper<DfBizClue>().eq(DfBizClue::getShareUser, dfOrder.getShareUser())
//                    .isNull(DfBizClue::getOrderId));
//            for (DfBizClue clue : list) {
//                clue.setOrderId(dfOrders.get(0).getId().toString());
//                clue.setPhone(dfOrder.getPhone());
//                clue.setNickName(dfOrder.getUserName());
//                dfBizClueMapper.updateClue(clue);
//            }
//        }
        if (Validator.isNotEmpty(dfOrder.getUnionId())) {
            List<DfBizClue> list = dfBizClueService.list(new LambdaQueryWrapper<DfBizClue>().eq(DfBizClue::getUnionId, dfOrder.getUnionId())
                    .isNull(DfBizClue::getOrderId));
            for (DfBizClue clue : list) {
                clue.setOrderId(dfOrders.get(0).getId().toString());
                //clue.setNickName(dfOrder.getUserName());
                if (Validator.isEmpty(clue.getUserName())) {
                    clue.setUserName(dfOrder.getUserName());
                    clue.setPhone(dfOrder.getPhone());
                }
                dfBizClueMapper.updateClue(clue);
            }
        }
//        dfOrder.setTenantId(SecurityUtils.getTenantId());
//        dfOrder.setCreateBy(SecurityUtils.getUserId());
//        dfOrder.setCreateDept(SecurityUtils.getDeptId());
        return toAjax(true);
    }

    /**
     * 修改客户订单
     */
    @ApiOperation("修改客户订单")
    @Log(title = "客户订单修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DfOrder dfOrder) {
        return toAjax(dfOrderService.updateById(dfOrder));
    }

    /**
     * 删除客户订单
     */
    @ApiOperation("删除客户订单")
    @Log(title = "客户订单删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(dfOrderService.removeBatchByIds(ids));
    }

    @ApiOperation("获取单据编号")
    @GetMapping("/getBillNo/{billPrefix}")
    public AjaxResult getBillNo(@PathVariable("billPrefix") String billPrefix) {
        String billNumber = dfOrderService.getBillNumber(billPrefix);
        return AjaxResult.success("获取成功", billNumber);
    }

    /**
     * 条件设置
     */
    private void condition(LambdaQueryWrapper<DfOrder> queryWrapper, DfOrder dfOrder) {


        //id
        if (Validator.isNotEmpty(dfOrder.getId())) {
            queryWrapper.eq(DfOrder::getId, dfOrder.getId());
        }

        //订单号
        if (Validator.isNotEmpty(dfOrder.getOrderNo())) {
            queryWrapper.like(DfOrder::getOrderNo, dfOrder.getOrderNo());
        }

        //客户id
        if (Validator.isNotEmpty(dfOrder.getUserId())) {
            queryWrapper.eq(DfOrder::getUserId, dfOrder.getUserId());
        }

        //经纪id
        if (Validator.isNotEmpty(dfOrder.getBrokerId())) {
            queryWrapper.eq(DfOrder::getBrokerId, dfOrder.getBrokerId());
        }

        //产品id
        if (Validator.isNotEmpty(dfOrder.getProductId())) {
            queryWrapper.eq(DfOrder::getProductId, dfOrder.getProductId());
        }

        //产品名称
        if (Validator.isNotEmpty(dfOrder.getProductName())) {
            queryWrapper.like(DfOrder::getProductName, dfOrder.getProductName());
        }

        if (Validator.isNotEmpty(dfOrder.getPhone())) {
            queryWrapper.like(DfOrder::getPhone, dfOrder.getPhone());
        }

        if (Validator.isNotEmpty(dfOrder.getUserName())) {
            queryWrapper.like(DfOrder::getUserName, dfOrder.getUserName());
        }

        //提交时间
        if (Validator.isNotEmpty(dfOrder.getSubmitTime())) {
            queryWrapper.eq(DfOrder::getSubmitTime, dfOrder.getSubmitTime());
        }

        if (Validator.isNotEmpty(dfOrder.getSubmitTimeBegin())) {
            queryWrapper.ge(DfOrder::getSubmitTime, dfOrder.getSubmitTimeBegin());
        }

        if (Validator.isNotEmpty(dfOrder.getSubmitTimeEnd())) {
            queryWrapper.le(DfOrder::getSubmitTime, dfOrder.getSubmitTimeEnd());
        }

        //申请额（万元）
        if (Validator.isNotEmpty(dfOrder.getApplyAmount())) {
            queryWrapper.eq(DfOrder::getApplyAmount, dfOrder.getApplyAmount());
        }

        //授信额（万元）
        if (Validator.isNotEmpty(dfOrder.getLimitAmount())) {
            queryWrapper.eq(DfOrder::getLimitAmount, dfOrder.getLimitAmount());
        }

        //放款额（万元）
        if (Validator.isNotEmpty(dfOrder.getLoanAmount())) {
            queryWrapper.eq(DfOrder::getLoanAmount, dfOrder.getLoanAmount());
        }

        //放款利率
        if (Validator.isNotEmpty(dfOrder.getLoanRate())) {
            queryWrapper.eq(DfOrder::getLoanRate, dfOrder.getLoanRate());
        }

        //贷款期限（月）
        if (Validator.isNotEmpty(dfOrder.getLoadMonth())) {
            queryWrapper.eq(DfOrder::getLoadMonth, dfOrder.getLoadMonth());
        }

        //是否首贷
        if (Validator.isNotEmpty(dfOrder.getIsFirst())) {
            queryWrapper.eq(DfOrder::getIsFirst, dfOrder.getIsFirst());
        }

        //可结算金额（万元）
        if (Validator.isNotEmpty(dfOrder.getSettleAmount())) {
            queryWrapper.eq(DfOrder::getSettleAmount, dfOrder.getSettleAmount());
        }

        //状态
        if (Validator.isNotEmpty(dfOrder.getStaus())) {
            queryWrapper.eq(DfOrder::getStaus, dfOrder.getStaus());
        }

        //备注
        if (Validator.isNotEmpty(dfOrder.getRemark())) {
            queryWrapper.eq(DfOrder::getRemark, dfOrder.getRemark());
        }

        //创建部门
        if (Validator.isNotEmpty(dfOrder.getCreateDept())) {
            queryWrapper.eq(DfOrder::getCreateDept, dfOrder.getCreateDept());
        }

        //创建人员
        if (Validator.isNotEmpty(dfOrder.getCreateBy())) {
            queryWrapper.eq(DfOrder::getCreateBy, dfOrder.getCreateBy());
        }

        //创建时间
        if (Validator.isNotEmpty(dfOrder.getCreateTime())) {
            queryWrapper.eq(DfOrder::getCreateTime, dfOrder.getCreateTime());
        }

        //修改人员
        if (Validator.isNotEmpty(dfOrder.getUpdateBy())) {
            queryWrapper.eq(DfOrder::getUpdateBy, dfOrder.getUpdateBy());
        }

        //修改时间
        if (Validator.isNotEmpty(dfOrder.getUpdateTime())) {
            queryWrapper.eq(DfOrder::getUpdateTime, dfOrder.getUpdateTime());
        }

        //删除标志（0代表存在 2代表删除）
        if (Validator.isNotEmpty(dfOrder.getDelFlag())) {
            queryWrapper.eq(DfOrder::getDelFlag, dfOrder.getDelFlag());
        }

        //租户id
        if (Validator.isNotEmpty(dfOrder.getTenantId())) {
            queryWrapper.eq(DfOrder::getTenantId, dfOrder.getTenantId());
        }

    }

}
