package cn.qg.qaplatform.controller.xyqb;

import cn.qg.qaplatform.config.SwitchDataSource;
import cn.qg.qaplatform.entity.businessflow.ApplyList;
import cn.qg.qaplatform.entity.vo.XjfqGenProcessVo;
import cn.qg.qaplatform.entity.workflow.WhiteListConfigNew;
import cn.qg.qaplatform.entity.xyqb.ApplyQuotaRecord;
import cn.qg.qaplatform.entity.xyqbuser.User;
import cn.qg.qaplatform.entity.vo.XyqbApplyDataVo;
import cn.qg.qaplatform.enums.ChannelEnum;
import cn.qg.qaplatform.enums.FundEnum;
import cn.qg.qaplatform.enums.LoanStatus;
import cn.qg.qaplatform.mapper.xyqb.XyqbMapper;
import cn.qg.qaplatform.service.businessFlow.ApplyListService;
import cn.qg.qaplatform.service.workflow.WhiteListConfigNewService;
import cn.qg.qaplatform.service.xyqb.ApplyQuotaRecordService;
import cn.qg.qaplatform.service.xyqb.XyqbService;
import cn.qg.qaplatform.service.xyqbUser.UserService;
import cn.qg.qaplatform.utils.EnumUtils;
import cn.qg.qaplatform.utils.JsonResult;
import cn.qg.qaplatform.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 现金分期相关接口
 */
@CrossOrigin
@RestController
@RequestMapping("/xyqb")
public class XyqbController {

    @Autowired
    ApplyListService applyListService;

    @Autowired
    ApplyQuotaRecordService applyQuotaRecordService;

    @Autowired
    UserService userService;

    @Autowired
    XyqbMapper xyqbMapper;

    @Autowired
    WhiteListConfigNewService whiteListConfigNewService;

    @Autowired
    XyqbService xyqbService;

    /**
     * @return 获取所有借款用户状态
     */
    @ApiOperation(value = "获取所有借款状态")
    @GetMapping("/getLoanStatus")
    public Result getLoanUserDataStatus() {
        List<Map<String, Object>> allUserLoanStatusList = new ArrayList<>();
        for (LoanStatus loanStatus:LoanStatus.values()) {
            Map<String, Object> tempMap = new HashMap<>();
            tempMap.put("value", loanStatus.getStatus());
            tempMap.put("label", loanStatus.getDesc());
            allUserLoanStatusList.add(tempMap);
        }
        return Result.buildSuccessResult(allUserLoanStatusList);
    }

    /**
     * 现金分期捞数据接口
     * @param status 用户状态（0-注册未申请，1-授信中，2-审核通过，3-审核拒绝，4-审核通过未提现，5-放款成功，6-放款失败，7-多订单）
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return 所有借款用户数据
     */
    @GetMapping("/getLoanUser")
    public Result getLoanUserData(@RequestParam(value = "namespace") String namespace,
                                      @RequestParam(value = "status") Integer status,
                                      @RequestParam(value = "channel" ) Integer channel,
                                      @RequestParam(value = "fundId") Integer fundId,
                                      @RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "10") Integer pageSize) {
        if (status == 0) {
            // 获取所有未申请的uuid
            SwitchDataSource.dataSourceSwitch(namespace, "business_flow");
            QueryWrapper<ApplyList> applyListQueryWrapper = new QueryWrapper<>();
            applyListQueryWrapper.eq("apply_status", status);
            if (channel != null) {
                applyListQueryWrapper.eq("channel_id", channel);
            }
            List<ApplyList> applyLists = applyListService.list(applyListQueryWrapper);
            List<String> uuidList = new ArrayList<>();
            applyLists.forEach(applyList -> {
                uuidList.add(applyList.getUuid());
            });
            // 根据uuid获取用户信息
            SwitchDataSource.dataSourceSwitch(namespace, "xyqb_user");
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.in("uuid", uuidList);
            IPage<User> iPage = new Page<>(pageNum, pageSize);
            IPage userIPage = userService.page(iPage, userQueryWrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("total",userIPage.getTotal());
            map.put("list", userIPage.getRecords());
            return Result.buildSuccessResult(map);
        }
        if (status == 1 || status == 2 || status == 3) {
            SwitchDataSource.dataSourceSwitch(namespace, "xyqb");
            QueryWrapper<ApplyQuotaRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("apply_status", status);
            if (channel != null) {
                queryWrapper.eq("apply_from", channel);
            }
            List<ApplyQuotaRecord> applyQuotaRecords = applyQuotaRecordService.list(queryWrapper);
            List<String> uuidList = new ArrayList<>();
            applyQuotaRecords.forEach(applyQuotaRecord -> {
                uuidList.add(applyQuotaRecord.getUuid());
            });
            SwitchDataSource.dataSourceSwitch(namespace,  "xyqb_user");
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.in("uuid", uuidList);
            IPage<User> iPage = new Page<>(pageNum, pageSize);
            IPage userIPage = userService.page(iPage, userQueryWrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("total",userIPage.getTotal());
            map.put("list", userIPage.getRecords());
            return Result.buildSuccessResult(map);
        }
        if (status == 4) {
            // 获取审核通过未提现的userId列表
            SwitchDataSource.dataSourceSwitch(namespace, "xyqb");
            List<String> userIds = xyqbMapper.queryAuthAndUnWithdraw(channel, fundId);
            // 查询对应用户的具体信息，并进行分页处理
            SwitchDataSource.dataSourceSwitch(namespace,  "xyqb_user");
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.in("id", userIds);
            IPage<User> iPage = new Page<>(pageNum, pageSize);
            IPage userIPage = userService.page(iPage, userQueryWrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("total",userIPage.getTotal());
            map.put("list", userIPage.getRecords());
            return Result.buildSuccessResult(map);
        }
        if (status == 5 || status == 6) {
            // 获取放款成功/放款失败的userId列表
            SwitchDataSource.dataSourceSwitch(namespace, "xyqb");
            List<String> userIds = new ArrayList<>();
            if (status == 5) {
                userIds = xyqbMapper.getLoanStatusUserIdList(15, channel, fundId);
            }
            if (status == 6) {
                userIds = xyqbMapper.getLoanStatusUserIdList(23, channel, fundId);
            }// 查询对应用户的具体信息，并进行分页处理
            SwitchDataSource.dataSourceSwitch(namespace,  "xyqb_user");
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.in("id", userIds);
            IPage<User> iPage = new Page<>(pageNum, pageSize);
            IPage userIPage = userService.page(iPage, userQueryWrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("total",userIPage.getTotal());
            map.put("list", userIPage.getRecords());
            return Result.buildSuccessResult(map);
        }

        if (status == 7) {
            SwitchDataSource.dataSourceSwitch("fe", "workflow");
            List<WhiteListConfigNew> whiteListConfigNews = whiteListConfigNewService.list();
            List<String> uuidList = new ArrayList<>();
            whiteListConfigNews.forEach(whiteListConfigNew -> {
                uuidList.add(whiteListConfigNew.getUuid());
            });
            // 根据uuid获取用户信息
            SwitchDataSource.dataSourceSwitch(namespace, "xyqb_user");
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.in("uuid", uuidList);
            IPage<User> iPage = new Page<>(pageNum, pageSize);
            IPage userIPage = userService.page(iPage, userQueryWrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("total",userIPage.getTotal());
            map.put("list", userIPage.getRecords());
            return Result.buildSuccessResult(map);
        }
        return Result.buildErrorStateResult("借款状态暂不支持！", false);
    }

    /**
     * 现金分期造数据接口
     * status: 0 - 审核通过, 1 - 审核拒绝, 2 - 放款中, 3 - 放款成功, 4 - 放款失败
     * @param xyqbApplyDataVo
     * @return
     */
    @PostMapping("/genLoanUser")
    public Result genXjfqLoanUser(@RequestBody XyqbApplyDataVo xyqbApplyDataVo) {
        try {
            boolean result = false;
            if (xyqbApplyDataVo.getChannel().equals(ChannelEnum.XYQB.getChannelId())) {
                result = xyqbService.genLoanUser(xyqbApplyDataVo);
            }
            return Result.buildSuccessResult(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.buildErrorStateResult("数据生成失败！", false);
        }
    }

    /**
     * 查询用户状态
     * @param namespace
     * @param phoneNo
     * @return
     */
    @GetMapping("/userStatus")
    public JsonResult queryUserStatus(@RequestParam String namespace,
                                      @RequestParam String phoneNo) {
        XjfqGenProcessVo xjfqGenProcessVo = xyqbService.queryUserStatus(namespace, phoneNo);
        return JsonResult.success(xjfqGenProcessVo);
    }

    /**
     * 支持的资方和渠道
     * @return
     */
    @GetMapping("/supportChannelAndFund")
    public Result getSupportedLoanUserData() {
        Map<String, List> map = new HashMap();
        List supportChannel = EnumUtils.enumToListMap(ChannelEnum.class);
        List supportFund = EnumUtils.enumToListMap(FundEnum.class);
        map.put("channelList", supportChannel);
        map.put("fundList", supportFund);
        return Result.buildSuccessResult(map);
    }

    /**
     * 渠道映射资方
     * @param channel
     * @return
     */
    @GetMapping("/channelMappedFund")
    public Result mapFund(@RequestParam Integer channel) {
        List<Map<String, Object>> supportFund = EnumUtils.enumToListMap(FundEnum.class);
        List<Map> resultFundList = new LinkedList<>();
        if (channel == 1) {
            for (Map<String, Object> temp: supportFund) {
                if (temp.get("fundId").equals(480) || temp.get("fundId").equals(1030) || temp.get("fundId").equals(1040)) {
                    resultFundList.add(temp);
                }
            }
        }
        if (channel == 159886) {
            for (Map<String, Object> temp: supportFund) {
                if (temp.get("fundId").equals(1010)) {
                    resultFundList.add(temp);
                }
            }
        }
        return Result.buildSuccessResult(resultFundList);
    }

    /**
     * 资方对应的渠道
     * @param fundId 资方id
     * @return
     */
    @GetMapping("/fundMappedChannel")
    public Result mapChannel(@RequestParam Integer fundId) {
        List<Map<String, Object>> supportChannel = EnumUtils.enumToListMap(ChannelEnum.class);
        List<Map> resultChannelList = new LinkedList<>();
        if (fundId == 480 || fundId == 1030  || fundId == 1040) {
            for (Map<String, Object> temp: supportChannel) {
                if (temp.get("channelId").equals(1)) {
                    resultChannelList.add(temp);
                }
            }
        }

        if (fundId == 1010) {
            for (Map<String, Object> temp: supportChannel) {
                if (temp.get("channelId").equals(159886)) {
                    resultChannelList.add(temp);
                }
            }
        }
        return Result.buildSuccessResult(resultChannelList);
    }

    /**
     * @param namespace 环境
     * @param fundCorpId 资方id
     * @return
     * @throws Exception
     */
    @GetMapping("/assign/fund")
    public Result assignFund(String namespace, Integer fundCorpId) throws Exception {
        return Result.buildSuccessResult(xyqbService.assignFund(namespace, fundCorpId));
    }
}
