package com.huyi.service.financeProduct.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huyi.service.base.entity.ZcFinanceContract;
import com.huyi.service.base.entity.ZcFinanceProComRel;
import com.huyi.service.base.entity.ZcFinanceProConRel;
import com.huyi.service.base.entity.ZcFinanceProduct;
import com.huyi.service.base.service.IZcFinanceContractService;
import com.huyi.service.base.service.IZcFinanceProComRelService;
import com.huyi.service.base.service.IZcFinanceProConRelService;
import com.huyi.service.base.service.IZcFinanceProductService;
import com.huyi.service.financeProduct.service.IOwnFinanceProductService;
import com.keao.tianhu.core.entity.R;
import com.keao.tianhu.starter.mybatis.plus.entity.QueryRequest;
import com.tianhu.common.core.utils.CommonUtil;
import com.tianhu.common.core.utils.DateUtils;
import com.tianhu.common.core.utils.IdUtils;
import com.tianhu.common.core.utils.StringUtils;
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.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 融资产品controller
 *
 * @author ch
 * @date 2021-8-16
 */

@RestController
@RequestMapping("/financeProduct")
public class FinanceProductControllers extends BaseController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IOwnFinanceProductService ownFinanceProductService;
    @Autowired
    private IZcFinanceProConRelService zcFinanceProConRelService;
    @Autowired
    private IZcFinanceProductService zcFinanceProductService;
    @Autowired
    private IZcFinanceProComRelService zcFinanceProComRelService;
    @Autowired
    private IZcFinanceContractService zcFinanceContractService;

    @GetMapping("/list")
    public AjaxResult list(String zfpName, String scyName, String begin,String end, QueryRequest request) {
        //查询当前操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        //获取企业
//        String companyId = use.getCompanyId();
        Map map = new HashMap(16);
//        if(CommonUtil.isNotEmpty(companyId)){
//            map.put("companyId",companyId);
//        }
        //产品名称
        if(CommonUtil.isNotEmpty(zfpName)){
            map.put("zfpName",zfpName);
        }
        //资方
        if(CommonUtil.isNotEmpty(scyName)){
            map.put("scyName",scyName);
        }
//        if(CommonUtil.isNotEmpty(begin) && CommonUtil.isNotEmpty(end)){
//            if(CommonUtil.compare(begin,end) ==1){
//                return AjaxResult.error("请输入正确的最短账期范围");
//            }
//        }
        //最短账期范围
        if(CommonUtil.isNotEmpty(begin)){
            map.put("begin",CommonUtil.objToBigDecimal(begin));
        }
        //最短账期范围
        if(CommonUtil.isNotEmpty(end)){
            map.put("end",CommonUtil.objToBigDecimal(end));
        }
        IPage<Map> list = ownFinanceProductService.selectFinanceProductList(map,request);
        return AjaxResult.success(list);
    }

    /**
     * 获取融资产品信息详细信息
     */
    @PreAuthorize(hasPermi = "service:financeProduct:query")
    @GetMapping(value = "/{zfpId}")
    public AjaxResult getInfo(@PathVariable("zfpId") String zfpId)
    {
        Map map = new HashMap();
        map.put("zfpId",zfpId);
        Map resultMap = ownFinanceProductService.selectUserName(map);
        ZcFinanceProduct zcFinanceProduct = zcFinanceProductService.getById(zfpId);
        resultMap.put("zcFinanceProduct",zcFinanceProduct);
        //授信合同信息
        LambdaQueryWrapper<ZcFinanceProConRel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZcFinanceProConRel::getZfpcrProductId,zfpId);
        List<ZcFinanceProConRel> zcFinanceProConRel = zcFinanceProConRelService.findZcFinanceProConRels(queryWrapper);
        List id = new ArrayList();
        for (int i = 0; i < zcFinanceProConRel.size(); i++) {
            String contractId = zcFinanceProConRel.get(i).getZfpcrContractId();
            id.add(contractId);
        }
        if (id.size() > 0) {
            LambdaQueryWrapper<ZcFinanceContract> contractWrapper = new LambdaQueryWrapper<>();
            contractWrapper.in(ZcFinanceContract::getZfcId, id);
            List<ZcFinanceContract> contractList = zcFinanceContractService.findZcFinanceContracts(contractWrapper);
            resultMap.put("contractList1",contractList);
        }
        return AjaxResult.success(resultMap);
    }

    /**
     * 新增融资产品
     * @param map
     * @return
     * @throws Exception
     */
    @PreAuthorize(hasPermi = "service:financeProduct:add")
    @Log(title = "融资产品", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor=Exception.class)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String,Object> map) throws Exception {
        //获取当前用户
        LoginUser userInf = tokenService.getLoginUser();
        String user = CommonUtil.objToString(userInf.getSysUser().getUserId());
        //创建融资产品对象
        ZcFinanceProduct zcFinanceProduct = new ZcFinanceProduct();
        //产品名称
        String zfpName = CommonUtil.objToString(map.get("zfpName"));
        if(CommonUtil.isEmpty(zfpName)){
            return AjaxResult.error("产品名称不能为空");
        }
        //产品类型
        String zfpType = CommonUtil.objToString(map.get("zfpType"));
        //经办人意愿方式
        String zfpAuthType = CommonUtil.objToString(map.get("zfpAuthType"));
        //资方
        String zfpManagementId = CommonUtil.objToString(map.get("zfpManagementId"));
        if(CommonUtil.isEmpty(zfpManagementId)){
            return AjaxResult.error("资金方不能为空");
        }
        //是否可拆转融
        String zfpSplit = CommonUtil.objToString(map.get("zfpSplit"));
        if(CommonUtil.isEmpty(zfpSplit)){
            return AjaxResult.error("请选择是否可拆转融（二期处理）");
        }
        //最小融资金额
        String zfpMinimumAmount = CommonUtil.objToString(map.get("zfpMinimumAmount"));
        if(CommonUtil.isEmpty(zfpMinimumAmount)){
            return AjaxResult.error("最小融资金额不能为空");
        }
        //最短融资账期
        String zfpShortestPeriod = CommonUtil.objToString(map.get("zfpShortestPeriod"));
        if(CommonUtil.isEmpty(zfpShortestPeriod)){
            return AjaxResult.error("最短融资账期不能为空");
        }else{
            if(CommonUtil.compare(zfpShortestPeriod,"14") == -1){
                return AjaxResult.error("最短融资账期最短14天");
            }
        }
        //服务费是否可退
        String zfpCharge = CommonUtil.objToString(map.get("zfpCharge"));
        if(CommonUtil.isEmpty(zfpCharge)){
            return AjaxResult.error("请选择服务费是否可退");
        }
        //是否有追索权
        String zfpRecourse = CommonUtil.objToString(map.get("zfpRecourse"));
        if(CommonUtil.isEmpty(zfpRecourse)){
            return AjaxResult.error("请选择是否有追索权");
        }
        //电子凭证类型
        String zfpVoucherType = CommonUtil.objToString(map.get("zfpVoucherType"));
        if(CommonUtil.isEmpty(zfpVoucherType)){
            return AjaxResult.error("电子凭证类型不能为空");
        }
        //是否需核心企业开户
        String zfpCoreAccount = CommonUtil.objToString(map.get("zfpCoreAccount"));
        if(CommonUtil.isEmpty(zfpCoreAccount)){
            return AjaxResult.error("请选择是否需核心企业开户");
        }
        //是否需融资企业开户
        String supplierAccount = CommonUtil.objToString(map.get("zfpSupplierAccount"));
        if(CommonUtil.isEmpty(zfpCoreAccount)){
            return AjaxResult.error("请选择是否需融资企业开户");
        }
        //记账簿托管方式
        String zfpBookkeeping = CommonUtil.objToString(map.get("zfpBookkeeping"));
        if(CommonUtil.isEmpty(zfpBookkeeping)){
            return AjaxResult.error("记账簿托管方式不能为空");
        }
        //是否支持部分融资
        String zfpPart = CommonUtil.objToString(map.get("zfpPart"));
        if(CommonUtil.isEmpty(zfpPart)){
            return AjaxResult.error("请选择是否支持部分融资");
        }
        //融资到期方式
        String zfpExpire = CommonUtil.objToString(map.get("zfpExpire"));
        //资方融资费率
        String zfpRate = CommonUtil.objToString(map.get("zfpRate"));
        //资方是否支持返佣
        String zfpProfit = CommonUtil.objToString(map.get("zfpProfit"));
        //资方返佣方式
        String zfpProfitType = CommonUtil.objToString(map.get("zfpProfitType"));
        //资方返佣费率
        String zfpProfitRate = CommonUtil.objToString(map.get("zfpProfitRate"));
        //是否需平台审批
        String zfpPlatform = CommonUtil.objToString(map.get("zfpPlatform"));
        //主键
        String zfpId = IdUtils.fastUUID();
        //创建时间
        String createTime = DateUtils.dateTimeNow();
        //产品编号
        String zfpNumber = "";
        if("0".equals(zfpType)){
            zfpNumber += "F";
        }else {
            zfpNumber += "L";
        }
        if("0".equals(zfpPlatform)){
            zfpNumber += "P";
        }else {
            zfpNumber += "A";
        }
        zfpNumber += createTime;
        //合同信息
        List<Map<String, String>> tableData = (List<Map<String, String>>) map.get("contractList");
//        if (tableData.size() == 0 ){
//            return AjaxResult.error("请选择合同");
//        }
        //新增融资产品合同关联表
        for (int i = 0; i < tableData.size(); i++) {
            String zfcId = tableData.get(i).get("zfcId");
            ZcFinanceProConRel zcFinanceProConRel = new ZcFinanceProConRel();
            zcFinanceProConRel.setZfpcrProductId(zfpId);
            zcFinanceProConRel.setZfpcrProductId(zfcId);
            zcFinanceProConRelService.createZcFinanceProConRel(zcFinanceProConRel);
        }
        //新增融资产品字段
        zcFinanceProduct.setZfpId(zfpId);
        zcFinanceProduct.setZfpNumber(zfpNumber);
        zcFinanceProduct.setZfpName(zfpName);
        zcFinanceProduct.setZfpType(zfpType);
        zcFinanceProduct.setZfpAuthType(zfpAuthType);
        //产品状态 01:启用 00:停用
        zcFinanceProduct.setZfpStatus("01");
        zcFinanceProduct.setZfpManagementId(zfpManagementId);
        zcFinanceProduct.setZfpSplit(zfpSplit);
        zcFinanceProduct.setZfpMinimumAmount(zfpMinimumAmount);
        zcFinanceProduct.setZfpShortestPeriod(zfpShortestPeriod);
        zcFinanceProduct.setZfpCharge(zfpCharge);
        zcFinanceProduct.setZfpRecourse(zfpRecourse);
        zcFinanceProduct.setZfpVoucherType(zfpVoucherType);
        zcFinanceProduct.setZfpCoreAccount(zfpCoreAccount);
        zcFinanceProduct.setZfpSupplierAccount(supplierAccount);
        zcFinanceProduct.setZfpBookkeeping(zfpBookkeeping);
        zcFinanceProduct.setZfpPart(zfpPart);
        zcFinanceProduct.setZfpExpire(zfpExpire);
        zcFinanceProduct.setZfpRate(zfpRate);
        zcFinanceProduct.setZfpProfit(zfpProfit);
        zcFinanceProduct.setZfpProfitType(zfpProfitType);
        zcFinanceProduct.setZfpProfitRate(zfpProfitRate);
        zcFinanceProduct.setZfpPlatform(zfpPlatform);
        zcFinanceProduct.setCreateTime(DateUtils.getNowDate());
        zcFinanceProduct.setCreateBy(user);
        zcFinanceProductService.createZcFinanceProduct(zcFinanceProduct);
        return AjaxResult.success();
    }

    /**
     * 修改融资产品信息
     */
    @PreAuthorize(hasPermi = "service:financeProduct:edit")
    @Log(title = "融资产品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Map map)throws Exception
    {
        //获取当前用户
        LoginUser userInf = tokenService.getLoginUser();
        String user = CommonUtil.objToString(userInf.getSysUser().getUserId());
        //产品编号
        String zfpNumber = CommonUtil.objToString(map.get("zfpNumber"));
        if(CommonUtil.isEmpty(zfpNumber)){
            return AjaxResult.error("产品编号不能为空");
        }
        //编号原时间戳
        String time = zfpNumber.substring(2);
        //产品名称
        String zfpName = CommonUtil.objToString(map.get("zfpName"));
        if(CommonUtil.isEmpty(zfpName)){
            return AjaxResult.error("产品名称不能为空");
        }
        //资方
        String zfpManagementId = CommonUtil.objToString(map.get("zfpManagementId"));
        if(CommonUtil.isEmpty(zfpManagementId)){
            return AjaxResult.error("资金方不能为空");
        }
        //是否可拆转融
        String zfpSplit = CommonUtil.objToString(map.get("zfpSplit"));
        if(CommonUtil.isEmpty(zfpSplit)){
            return AjaxResult.error("请选择是否可拆转融（二期处理）");
        }
        //产品类型
        String zfpType = CommonUtil.objToString(map.get("zfpType"));
        //经办人意愿方式
        String zfpAuthType = CommonUtil.objToString(map.get("zfpAuthType"));
        //最小融资金额
        String zfpMinimumAmount = CommonUtil.objToString(map.get("zfpMinimumAmount"));
        if(CommonUtil.isEmpty(zfpMinimumAmount)){
            return AjaxResult.error("最小融资金额不能为空");
        }
        //最短融资账期
        String zfpShortestPeriod = CommonUtil.objToString(map.get("zfpShortestPeriod"));
        if(CommonUtil.isEmpty(zfpShortestPeriod)){
            return AjaxResult.error("最短融资账期不能为空");
        }else{
            if(CommonUtil.compare(zfpShortestPeriod,"14") == -1){
                return AjaxResult.error("最短融资账期最短14天");
            }
        }
        //服务费是否可退
        String zfpCharge = CommonUtil.objToString(map.get("zfpCharge"));
        if(CommonUtil.isEmpty(zfpCharge)){
            return AjaxResult.error("请选择服务费是否可退");
        }
        //是否有追索权
        String zfpRecourse = CommonUtil.objToString(map.get("zfpRecourse"));
        if(CommonUtil.isEmpty(zfpRecourse)){
            return AjaxResult.error("请选择是否有追索权");
        }
        //电子凭证类型
        String zfpVoucherType = CommonUtil.objToString(map.get("zfpVoucherType"));
        if(CommonUtil.isEmpty(zfpVoucherType)){
            return AjaxResult.error("电子凭证类型不能为空");
        }
        //是否需核心企业开户
        String zfpCoreAccount = CommonUtil.objToString(map.get("zfpCoreAccount"));
        if(CommonUtil.isEmpty(zfpCoreAccount)){
            return AjaxResult.error("请选择是否需核心企业开户");
        }
        //是否需融资企业开户
        String zfpSupplierAccount = CommonUtil.objToString(map.get("zfpSupplierAccount"));
        if(CommonUtil.isEmpty(zfpCoreAccount)){
            return AjaxResult.error("请选择是否需融资企业开户");
        }
        //记账簿托管方式
        String zfpBookkeeping = CommonUtil.objToString(map.get("zfpBookkeeping"));
        if(CommonUtil.isEmpty(zfpBookkeeping)){
            return AjaxResult.error("记账簿托管方式不能为空");
        }
        //是否支持部分融资
        String zfpPart = CommonUtil.objToString(map.get("zfpPart"));
        if(CommonUtil.isEmpty(zfpPart)){
            return AjaxResult.error("请选择是否支持部分融资");
        }
        //融资到期方式
        String zfpExpire = CommonUtil.objToString(map.get("zfpExpire"));
        //资方融资费率
        String zfpRate = CommonUtil.objToString(map.get("zfpRate"));
        //资方是否支持返佣
        String zfpProfit = CommonUtil.objToString(map.get("zfpProfit"));
        //资方返佣方式
        String zfpProfitType = CommonUtil.objToString(map.get("zfpProfitType"));
        //资方返佣费率
        String zfpProfitRate = CommonUtil.objToString(map.get("zfpProfitRate"));
        //是否需平台审批
        String zfpPlatform = CommonUtil.objToString(map.get("zfpPlatform"));
        //主键
        String zfpId = CommonUtil.objToString(map.get("zfpId"));
        //产品编号
        String heard = "";
        if("0".equals(zfpType)){
            heard += "F";
        }else {
            heard += "L";
        }
        if("0".equals(zfpPlatform)){
            heard += "P";
        }else {
            heard += "A";
        }
        zfpNumber = heard + time;
        //查询原产品关联合同
        LambdaQueryWrapper<ZcFinanceProConRel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZcFinanceProConRel::getZfpcrProductId,zfpId);
        List<ZcFinanceProConRel> original = zcFinanceProConRelService.findZcFinanceProConRels(queryWrapper);
        //删除原关联合同
        for(ZcFinanceProConRel proConRel:original){
            zcFinanceProConRelService.removeById(proConRel.getZfpcrProductId());
        }
        //合同信息
        List<Map<String, String>> tableData = (List<Map<String, String>>) map.get("contractList1");
        if (tableData.size() == 0 ){
            return AjaxResult.error("请选择合同");
        }
        //新增融资产品合同关联表
        for (int i = 0; i < tableData.size(); i++) {
            String zfcId = tableData.get(i).get("zfcId");
            ZcFinanceProConRel zcFinanceProConRel = new ZcFinanceProConRel();
            zcFinanceProConRel.setZfpcrProductId(zfpId);
            zcFinanceProConRel.setZfpcrProductId(zfcId);
            zcFinanceProConRelService.createZcFinanceProConRel(zcFinanceProConRel);
        }
        ZcFinanceProduct zcFinanceProduct = new ZcFinanceProduct();
        //执行修改
        zcFinanceProduct.setZfpId(zfpId);
        zcFinanceProduct.setZfpNumber(zfpNumber);
        zcFinanceProduct.setZfpName(zfpName);
        zcFinanceProduct.setZfpManagementId(zfpManagementId);
        zcFinanceProduct.setZfpSplit(zfpSplit);
        zcFinanceProduct.setZfpType(zfpType);
        zcFinanceProduct.setZfpAuthType(zfpAuthType);
        zcFinanceProduct.setZfpMinimumAmount(zfpMinimumAmount);
        zcFinanceProduct.setZfpShortestPeriod(zfpShortestPeriod);
        zcFinanceProduct.setZfpCharge(zfpCharge);
        zcFinanceProduct.setZfpRecourse(zfpRecourse);
        zcFinanceProduct.setZfpVoucherType(zfpVoucherType);
        zcFinanceProduct.setZfpCoreAccount(zfpCoreAccount);
        zcFinanceProduct.setZfpSupplierAccount(zfpSupplierAccount);
        zcFinanceProduct.setZfpBookkeeping(zfpBookkeeping);
        zcFinanceProduct.setZfpPart(zfpPart);
        zcFinanceProduct.setZfpExpire(zfpExpire);
        zcFinanceProduct.setZfpRate(zfpRate);
        zcFinanceProduct.setZfpProfit(zfpProfit);
        zcFinanceProduct.setZfpProfitType(zfpProfitType);
        zcFinanceProduct.setZfpProfitRate(zfpProfitRate);
        zcFinanceProduct.setZfpPlatform(zfpPlatform);
        zcFinanceProduct.setUpdateTime(DateUtils.getNowDate());
        zcFinanceProduct.setUpdateBy(user);
        zcFinanceProductService.updateZcFinanceProduct(zcFinanceProduct);
        return AjaxResult.success();
    }

    /**
     * 修改产品启用状态
     * @param zfpId
     * @return
     */
    @PreAuthorize(hasPermi = "service:financeProduct:change")
    @Log(title = "产品状态", businessType = BusinessType.UPDATE)
    @PutMapping("/change/{zfpId}")
    public AjaxResult changState(@PathVariable String zfpId){
        //查询产品原状态
        ZcFinanceProduct zcFinanceProduct =  zcFinanceProductService.getById(zfpId);
        String state = zcFinanceProduct.getZfpStatus();
        //如果是启用改为停用
        if("01".equals(state)){
            //查询产品是否关联授信
            LambdaQueryWrapper<ZcFinanceProComRel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZcFinanceProComRel::getZfpcrProductId,zfpId);
            int count = zcFinanceProComRelService.count(queryWrapper);
            //若已关联提示不可停用
            if(count > 0){
                return AjaxResult.error("不可停用!");
            }else {
                zcFinanceProduct.setZfpStatus("00");
            }
        }else {
            //反之改为启用
            zcFinanceProduct.setZfpStatus("01");
        }
        //执行修改
        zcFinanceProductService.updateZcFinanceProduct(zcFinanceProduct);
        return AjaxResult.success();
    }

}
