package com.huyi.service.creditLine.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huyi.service.base.entity.ZcFinanceContract;
import com.huyi.service.base.entity.ZcFinanceInf;
import com.huyi.service.base.entity.ZcFinanceProComRel;
import com.huyi.service.base.entity.ZcFinanceQuotaConRel;
import com.huyi.service.base.service.IZcFinanceContractService;
import com.huyi.service.base.service.IZcFinanceInfService;
import com.huyi.service.base.service.IZcFinanceProComRelService;
import com.huyi.service.base.service.IZcFinanceQuotaConRelService;
import com.huyi.service.creditLine.service.CreditLineService;
import com.keao.tianhu.starter.mybatis.plus.entity.QueryRequest;
import com.tianhu.common.core.constant.SalaryConstants;
import com.tianhu.common.core.domain.R;
import com.tianhu.common.core.utils.*;
import com.tianhu.common.core.web.controller.BaseController;
import com.tianhu.common.core.web.domain.AjaxResult;
import com.tianhu.common.log.annotation.Log;
import com.tianhu.common.log.enums.BusinessType;
import com.tianhu.common.security.annotation.PreAuthorize;
import com.tianhu.common.security.service.TokenService;
import com.tianhu.system.api.domain.SysUser;
import com.tianhu.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;


/**
 * 授信额度Controller
 *
 * @author pxh
 * @date 2021-02-04
 */

@RestController
@RequestMapping("/creditLine")
public class CreditLineController extends BaseController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private CreditLineService creditLineService;
    @Autowired
    private IZcFinanceInfService zcFinanceInfService;
    @Autowired
    private IZcFinanceProComRelService iZcFinanceProComRelService;
    @Autowired
    private IZcFinanceQuotaConRelService iZcFinanceQuotaConRelService;
    @Autowired
    private IZcFinanceContractService iZcFinanceContractService;
     /**
     * 查询授信额度列表
     */
    @PreAuthorize(hasPermi = "credit:line:list")
    @GetMapping("/list")
    public R list(//企业名称
                  @RequestParam(required=false) String scyName,
                  //授信额度范围
                  @RequestParam (required=false) String AmountA,
                  //授信额度范围
                  @RequestParam (required=false) String AmountB,
                  //状态(00:有效 01:失效)
                  @RequestParam (required=false) String zfpcrStatus,
                  //开始日期
                  @RequestParam (required = false) Map startTime,
                  //结束日期
                  @RequestParam (required = false) Map endTime,QueryRequest request) {
        //查询当前操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        //获取企业
        String companyId = use.getCompanyId();
        Map map = new HashMap();
        if (!SalaryConstants.OPEX.equals(companyId)) {
            map.put("companyId", companyId);
        }
        //企业名称
        map.put("scyName",scyName);
        //授信额度范围
        map.put("AmountA",CommonUtil.objToBigDecimal(AmountA));
        map.put("AmountB",CommonUtil.objToBigDecimal(AmountB));
        //状态状态(00:有效 01:失效)
        map.put("zfpcrStatus",zfpcrStatus);
        //开始日期区间
        map.put("startTimeA",startTime.get("startTime[0]"));
        map.put("startTimeB",startTime.get("startTime[1]"));
        //结束日期区间
        map.put("endTimeA",endTime.get("endTime[0]"));
        map.put("endTimeB",endTime.get("endTime[1]"));
        IPage<Map> list = creditLineService.selectCreditLineList(map, request);
        List listAll = list.getRecords();
        for (int j = 0; j < listAll.size(); j++) {
            Map<String,String>  m = (Map<String, String>) listAll.get(j);
            //授信额度
            String zfpcrAmount = m.get("zfpcrAmount");
            //融资产品
            String zfpcrProductId = m.get("zfpcrProductId");
            //通过融资产品查询融信表申请金额
            QueryWrapper<ZcFinanceInf> queryWrapper = new QueryWrapper<>();
            //融资产品id
            queryWrapper.eq("zfi_product_id",zfpcrProductId);
            //状态(00:待确权 01:待签收 02:已生效 03:已失效 04:融资中 05:已融资)
            queryWrapper.and(i -> i.ne("zfi_status","00").or().ne("zfi_status","03"));
            queryWrapper.select("IFNULL(CAST(ROUND(SUM(zfi_amount),2)AS CHAR),'0.00') AS zfiAmount");
            ZcFinanceInf zcFinanceInf = zcFinanceInfService.getOne(queryWrapper);
            //申请金额(已用)
            String zfiAmount = "0.00";
            if (zcFinanceInf != null){
                zfiAmount  = zcFinanceInf.getZfiAmount();
            }
            //可用额度(授信额度 - 申请金额)
            String usableAmount = AmtUtil.subtract(zfpcrAmount,zfiAmount,2);
            //已使用额度
            m.put("zfiAmount",zfiAmount);
            //可用额度
            m.put("usableAmount",usableAmount);
        }
        return R.ok(list);
    }

    /**
     * 授信额度信息详情
     */
    @PreAuthorize(hasPermi = "credit:line:query")
    @GetMapping(value = "/{zfpcrId}")
    public AjaxResult getInfo(@PathVariable("zfpcrId") String zfpcrId)
    {
        Map result = new HashMap();
        //授信信息
        Map map = new HashMap();
        map.put("zfpcrId",zfpcrId);
        List<Map> list = creditLineService.selectCreditLineDetail(map);
        //授信合同信息
        LambdaQueryWrapper<ZcFinanceQuotaConRel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZcFinanceQuotaConRel::getZfqcrCreditId,zfpcrId);
        List<ZcFinanceQuotaConRel> quotaConRelList = iZcFinanceQuotaConRelService.findZcFinanceQuotaConRels(queryWrapper);
        List id = new ArrayList();
        for (int i = 0; i < quotaConRelList.size(); i++) {
            String contractId = quotaConRelList.get(i).getZfqcrContractId();
            id.add(contractId);
        }
        if (id.size() > 0) {
            LambdaQueryWrapper<ZcFinanceContract> contractWrapper = new LambdaQueryWrapper<>();
            contractWrapper.in(ZcFinanceContract::getZfcId, id);
            List<ZcFinanceContract> contractList = iZcFinanceContractService.findZcFinanceContracts(contractWrapper);
            result.put("ticketList",contractList);
        }
        result.put("list",list);
        return AjaxResult.success(result);
    }

    /**
     * 新增授信管理
     * @param map
     * @return
     * @throws Exception
     */
    @PreAuthorize(hasPermi = "credit:line::add")
    @Log(title = "授信管理", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String,Object> map)throws Exception
    {
        //获取此操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser user = userInfo.getSysUser();
        String userId = user.getUserId() + "";
        //融资产品
        String zfpcrProductId = CommonUtil.objToString(map.get("zfpcrProductId"));
        //授信企业名称
        String zfpcrCompanyId = CommonUtil.objToString(map.get("zfpcrCompanyId"));
        //授信额度
        String zfpcrAmount = CommonUtil.objToString(map.get("zfpcrAmount"));
        //利率
        String zfpcrRate =  CommonUtil.objToString(map.get("zfpcrRate"));
        //有效期
        String zfpcrDateType =  CommonUtil.objToString(map.get("zfpcrDateType"));
        //日期范围
        List<String> dateTime = (List<String>) map.get("dateTime");
        //开始日期
        String zfpcrStartDate = dateTime.get(0);
        //结束日期
        String zfpcrEndDate = dateTime.get(1);
        //融资网点
        String zfpcrAddress =  CommonUtil.objToString(map.get("zfpcrAddress"));
        //是否收取手续费(0:不收取, 1收取)
        String zfpcrCharge = CommonUtil.objToString(map.get("zfpcrCharge"));
        //平台服务费收取费率
        String zfpcrChargeRate = CommonUtil.objToString(map.get("zfpcrChargeRate"));
        //核心企业还款账户账号
        String zfpcrAccount = CommonUtil.objToString(map.get("zfpcrAccount"));
        //融资放款方式
        String zfpcrLoanType = CommonUtil.objToString(map.get("zfpcrLoanType"));
        //记账簿托管方式
        String zfpcrBookkeepingType = CommonUtil.objToString(map.get("zfpcrLoanType"));
        String regex = "^\\d\\.([0-9]{1,2}|[0-9][0-9])$|^[0-9]\\d{0,1}(\\.\\d{1,2}){0,1}$|^100(\\.0{1,2}){0,1}$";
        Pattern pattern = Pattern.compile(regex);
        //融资产品
        if(CommonUtil.isEmpty(zfpcrProductId)){
            throw new Exception("融资产品不能为空");
        }
        //授信企业名称
        if(CommonUtil.isEmpty(zfpcrCompanyId)){
            throw new Exception("授信企业名称不能为空");
        }
        //授信额度
        if(CommonUtil.isNotEmpty(zfpcrAmount)) {
            if(AmtUtil.isMoney(zfpcrAmount) == false) {
                throw new Exception("请输入正确的授信额度");
            }
        }else {
            throw new Exception("授信额度不能为空");
        }
        //利率
        if(CommonUtil.isNotEmpty(zfpcrRate)) {
            if(!pattern.matcher(zfpcrRate).matches()) {
                throw new Exception("请输入正确的利率");
            }
        }else {
            throw new Exception("利率不能为空");
        }
        //有效期
        if(CommonUtil.isEmpty(zfpcrDateType)){
            throw new Exception("有效期不能为空");
        }
        //时间范围
        if ("1".equals(zfpcrDateType)){
            //时间范围
            if(dateTime.size() == 0){
                throw new Exception("时间范围不能为空");
            }
        }
        //是否收取手续费(0:不收取, 1收取)
        if(CommonUtil.isEmpty(zfpcrCharge)){
            throw new Exception("是否收取手续费不能为空");
        }
        //平台服务费收取费率
        if("1".equals(zfpcrCharge)){
            if(CommonUtil.isNotEmpty(zfpcrChargeRate)) {
                if(!pattern.matcher(zfpcrChargeRate).matches()) {
                    throw new Exception("请输入正确的平台服务费收取费率");
                }
            }else {
                throw new Exception("平台服务费收取费率不能为空");
            }
        }
        //核心企业还款账户账号
        if(CommonUtil.isEmpty(zfpcrAccount)){
            throw new Exception("核心企业还款账户账号不能为空");
        }
        //融资放款方式
        if(CommonUtil.isEmpty(zfpcrLoanType)){
            throw new Exception("融资放款方式不能为空");
        }
        //记账簿托管方式
        if(CommonUtil.isEmpty(zfpcrBookkeepingType)){
            throw new Exception("记账簿托管方式不能为空");
        }
        //合同信息
        List<Map<String, String>> tableData = (List<Map<String, String>>) map.get("ticketList");
        if (tableData.size() == 0 ){
            throw new Exception("请选择合同信息");
        }
        //执行新增
        ZcFinanceProComRel zcFinanceProComRel = new ZcFinanceProComRel();
        //主键
        String zfpcrId = IdUtils.fastSimpleUUID();
        zcFinanceProComRel.setZfpcrId(zfpcrId);
        //融资产品
        zcFinanceProComRel.setZfpcrProductId(zfpcrProductId);
        //授信企业名称
        zcFinanceProComRel.setZfpcrCompanyId(zfpcrCompanyId);
        //授信额度
        zcFinanceProComRel.setZfpcrAmount(zfpcrAmount);
        //原授信额度(如果授信额度没做修改,原授信额度不变
        zcFinanceProComRel.setZfpcrOldAmount(zfpcrAmount);
        //利率
        zcFinanceProComRel.setZfpcrRate(zfpcrRate);
        //有效期
        zcFinanceProComRel.setZfpcrDateType(zfpcrDateType);
        //开始日期
        zcFinanceProComRel.setZfpcrStartDate(zfpcrStartDate);
        //结束日期
        zcFinanceProComRel.setZfpcrEndDate(zfpcrEndDate);
        //融资网点
        zcFinanceProComRel.setZfpcrAddress(zfpcrAddress);
        //是否收取手续费(0:不收取, 1收取)
        zcFinanceProComRel.setZfpcrCharge(zfpcrCharge);
        //平台服务费收取费率
        zcFinanceProComRel.setZfpcrChargeRate(zfpcrChargeRate);
        //核心企业还款账户账号
        zcFinanceProComRel.setZfpcrAccount(zfpcrAccount);
        //融资放款方式
        zcFinanceProComRel.setZfpcrLoanType(zfpcrLoanType);
        //记账簿托管方式
        zcFinanceProComRel.setZfpcrBookkeepingType(zfpcrBookkeepingType);
        //状态(00:有效 01:失效)
        zcFinanceProComRel.setZfpcrStatus("00");
        //创建人
        zcFinanceProComRel.setCreateBy(userId);
        //创建时间
        zcFinanceProComRel.setCreateTime(DateUtils.getNowDate());
        iZcFinanceProComRelService.createZcFinanceProComRel(zcFinanceProComRel);
        //新增授信合同关联表
        for (int i = 0; i < tableData.size(); i++) {
            String zfcId = tableData.get(i).get("zfcId");
            ZcFinanceQuotaConRel zcFinanceQuotaConRel = new ZcFinanceQuotaConRel();
            //合同id
            zcFinanceQuotaConRel.setZfqcrContractId(zfcId);
            //授信id
            zcFinanceQuotaConRel.setZfqcrCreditId(zfpcrId);
            iZcFinanceQuotaConRelService.createZcFinanceQuotaConRel(zcFinanceQuotaConRel);
        }
        return AjaxResult.success();
    }

    /**
     * 修改授信管理
     * @param map
     * @return
     * @throws Exception
     */
    @PreAuthorize(hasPermi = "credit:line:edit")
    @Log(title = "授信管理", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    @PutMapping
    public AjaxResult update(@RequestBody Map<String,Object> map)throws Exception
    {
        //主键
        String zfpcrId = CommonUtil.objToString(map.get("zfpcrId"));
        //获取此操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser user = userInfo.getSysUser();
        String userId = user.getUserId() + "";
        //融资产品
        String zfpcrProductId = CommonUtil.objToString(map.get("zfpcrProductId"));
        //授信企业名称
        String zfpcrCompanyId = CommonUtil.objToString(map.get("zfpcrCompanyId"));
        //授信额度
        String zfpcrAmount = CommonUtil.objToString(map.get("zfpcrAmount"));
        //原授信额度
        String zfpcrOldAmount = CommonUtil.objToString(map.get("zfpcrOldAmount"));
        //利率
        String zfpcrRate =  CommonUtil.objToString(map.get("zfpcrRate"));
        //有效期
        String zfpcrDateType =  CommonUtil.objToString(map.get("zfpcrDateType"));
        //日期范围
        List<String> dateTime = (List<String>) map.get("dateTime");
        //开始日期
        String zfpcrStartDate = dateTime.get(0);
        //结束日期
        String zfpcrEndDate = dateTime.get(1);
        //融资网点
        String zfpcrAddress =  CommonUtil.objToString(map.get("zfpcrAddress"));
        //是否收取手续费(0:不收取, 1收取)
        String zfpcrCharge = CommonUtil.objToString(map.get("zfpcrCharge"));
        //平台服务费收取费率
        String zfpcrChargeRate = CommonUtil.objToString(map.get("zfpcrChargeRate"));
        //核心企业还款账户账号
        String zfpcrAccount = CommonUtil.objToString(map.get("zfpcrAccount"));
        //融资放款方式
        String zfpcrLoanType = CommonUtil.objToString(map.get("zfpcrLoanType"));
        //记账簿托管方式
        String zfpcrBookkeepingType = CommonUtil.objToString(map.get("zfpcrLoanType"));
        String regex = "^\\d\\.([0-9]{1,2}|[0-9][0-9])$|^[0-9]\\d{0,1}(\\.\\d{1,2}){0,1}$|^100(\\.0{1,2}){0,1}$";
        Pattern pattern = Pattern.compile(regex);
        //融资产品
        if(CommonUtil.isEmpty(zfpcrProductId)){
            throw new Exception("融资产品不能为空");
        }
        //授信企业名称
        if(CommonUtil.isEmpty(zfpcrCompanyId)){
            throw new Exception("授信企业名称不能为空");
        }
        //授信额度
        if(CommonUtil.isNotEmpty(zfpcrAmount)) {
            if(AmtUtil.isMoney(zfpcrAmount) == false) {
                throw new Exception("请输入正确的授信额度");
            }
        }else {
            throw new Exception("授信额度不能为空");
        }
        //利率
        if(CommonUtil.isNotEmpty(zfpcrRate)) {
            if(!pattern.matcher(zfpcrRate).matches()) {
                throw new Exception("请输入正确的利率");
            }
        }else {
            throw new Exception("利率不能为空");
        }
        //有效期
        if(CommonUtil.isEmpty(zfpcrDateType)){
            throw new Exception("有效期不能为空");
        }
        //时间范围
        if ("1".equals(zfpcrDateType)){
            //时间范围
            if(dateTime.size() == 0){
                throw new Exception("时间范围不能为空");
            }
        }
        //是否收取手续费(0:不收取, 1收取)
        if(CommonUtil.isEmpty(zfpcrCharge)){
            throw new Exception("是否收取手续费不能为空");
        }
        //平台服务费收取费率
        if("1".equals(zfpcrCharge)){
            if(CommonUtil.isNotEmpty(zfpcrChargeRate)) {
                if(!pattern.matcher(zfpcrChargeRate).matches()) {
                    throw new Exception("请输入正确的平台服务费收取费率");
                }
            }else {
                throw new Exception("平台服务费收取费率不能为空");
            }
        }
        //核心企业还款账户账号
        if(CommonUtil.isEmpty(zfpcrAccount)){
            throw new Exception("核心企业还款账户账号不能为空");
        }
        //融资放款方式
        if(CommonUtil.isEmpty(zfpcrLoanType)){
            throw new Exception("融资放款方式不能为空");
        }
        //记账簿托管方式
        if(CommonUtil.isEmpty(zfpcrBookkeepingType)){
            throw new Exception("记账簿托管方式不能为空");
        }
        //合同信息
        List<Map<String, String>> tableData = (List<Map<String, String>>) map.get("ticketList");
        if (tableData.size() == 0 ){
            throw new Exception("请选择合同信息");
        }
        //执行修改
        ZcFinanceProComRel zcFinanceProComRel = new ZcFinanceProComRel();
        //主键
        zcFinanceProComRel.setZfpcrId(zfpcrId);
        //融资产品
        zcFinanceProComRel.setZfpcrProductId(zfpcrProductId);
        //授信企业名称
        zcFinanceProComRel.setZfpcrCompanyId(zfpcrCompanyId);
        //授信额度
        zcFinanceProComRel.setZfpcrAmount(zfpcrAmount);
        //原授信额度(如果授信额度没做修改,原授信额度不变
        if (!zfpcrAmount.equals(zfpcrOldAmount)) {
            zcFinanceProComRel.setZfpcrOldAmount(zfpcrOldAmount);
        }
        //利率
        zcFinanceProComRel.setZfpcrRate(zfpcrRate);
        //有效期
        zcFinanceProComRel.setZfpcrDateType(zfpcrDateType);
        //开始日期
        zcFinanceProComRel.setZfpcrStartDate(zfpcrStartDate);
        //结束日期
        zcFinanceProComRel.setZfpcrEndDate(zfpcrEndDate);
        //融资网点
        zcFinanceProComRel.setZfpcrAddress(zfpcrAddress);
        //是否收取手续费(0:不收取, 1收取)
        zcFinanceProComRel.setZfpcrCharge(zfpcrCharge);
        //平台服务费收取费率
        zcFinanceProComRel.setZfpcrChargeRate(zfpcrChargeRate);
        //核心企业还款账户账号
        zcFinanceProComRel.setZfpcrAccount(zfpcrAccount);
        //融资放款方式
        zcFinanceProComRel.setZfpcrLoanType(zfpcrLoanType);
        //记账簿托管方式
        zcFinanceProComRel.setZfpcrBookkeepingType(zfpcrBookkeepingType);
        //修改人
        zcFinanceProComRel.setUpdateBy(userId);
        //修改时间
        zcFinanceProComRel.setUpdateTime(DateUtils.getNowDate());
        iZcFinanceProComRelService.updateZcFinanceProComRel(zcFinanceProComRel);
        //查询原合同信息详情并删除
        LambdaQueryWrapper<ZcFinanceQuotaConRel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZcFinanceQuotaConRel::getZfqcrCreditId,zfpcrId);
        List<ZcFinanceQuotaConRel> list = iZcFinanceQuotaConRelService.findZcFinanceQuotaConRels(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            LambdaQueryWrapper<ZcFinanceQuotaConRel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ZcFinanceQuotaConRel::getZfqcrCreditId,list.get(i).getZfqcrCreditId());
            iZcFinanceQuotaConRelService.deleteZcFinanceQuotaConRel(lambdaQueryWrapper);
        }
        //新增授信合同
        // 关联表
        for (int i = 0; i < tableData.size(); i++) {
            String zfcId = tableData.get(i).get("zfcId");
            ZcFinanceQuotaConRel zcFinanceQuotaConRel = new ZcFinanceQuotaConRel();
            //合同id
            zcFinanceQuotaConRel.setZfqcrContractId(zfcId);
            //授信id
            zcFinanceQuotaConRel.setZfqcrCreditId(zfpcrId);
            iZcFinanceQuotaConRelService.createZcFinanceQuotaConRel(zcFinanceQuotaConRel);
        }
        return AjaxResult.success();
    }
    /**
     * 状态修改
     */
    @PreAuthorize(hasPermi = "credit:line:update")
    @Log(title = "授信管理", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody Map<String, String> map) throws Exception
    {
        //授信id
        String zfpcrId = map.get("zfpcrId");
        //已使用金额
        String zfiAmount = map.get("zfiAmount");
        //授信状态
        String zfpcrStatus = map.get("zfpcrStatus");
        ZcFinanceProComRel zcFinanceProComRel = new ZcFinanceProComRel();
        //授信id
        zcFinanceProComRel.setZfpcrId(zfpcrId);
        //判断状态(如果是冻结操作判断是否符合冻结条件
        if ("00".equals(zfpcrStatus)) {
            if ("0.00".equals(zfiAmount)) {
                zcFinanceProComRel.setZfpcrStatus("01");
                iZcFinanceProComRelService.updateZcFinanceProComRel(zcFinanceProComRel);
            }else {
                throw new Exception("此授信正在使用无法冻结");
            }
        }else {
            zcFinanceProComRel.setZfpcrStatus("00");
            iZcFinanceProComRelService.updateZcFinanceProComRel(zcFinanceProComRel);
        }
        return AjaxResult.success();
    }
}

