package com.sifang.modules.account.controller;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.dao.TraderAccountDao;
import com.sifang.modules.account.entity.CrmTraderAccount;
import com.sifang.modules.account.service.TraderAccountService;
import com.sifang.modules.account.service.TraderAccountSettleDetailService;
import com.sifang.modules.customer.Service.AccountSetService;
import com.sifang.modules.customer.constant.AccountSetConstants;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.excel.AccountDetailExcel;
import com.sifang.modules.customer.excel.FileExportUtil;
import com.sifang.modules.customer.utils.DeliverOrderUtils;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.entity.ExamineInfo;
import com.sifang.modules.flowpath.service.BondApplyService;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.Arith;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Controller
@RequestMapping(value = "${adminPath}/account")
public class TraderAccountController extends BaseController {

    @Autowired
    private TraderAccountService accountService;

    @Autowired
    private TraderAccountSettleDetailService settleDetailService;

    @Autowired
    private TraderService traderService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private AccountSetService accountSetService;

    @Autowired
    private TraderAccountDao traderAccountDao;

    @Autowired
    private BondApplyService bondApplyService;
    @Autowired
    private PartnerService partnerService;

    /**
     * 可铺货账户-账户明细
     */
    @RequestMapping(value = "toKphAccountDetail")
    public String toAccountDetail(HttpServletRequest request, Model model){
        //代理商列表
        List<Record> traderList = traderService.getTopTrader2();
        model.addAttribute("traderList", traderList);
        return "modules/yangguang/account/kph/accountDetailList";
    }

    /**
     * 可铺货账户-账户明细接口请求
     */
    @ResponseBody
    @RequestMapping(value = "ajaxForAccountDetail")
    public Object ajaxForKphAccount(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        LayuiPage layuiPage = new LayuiPage(request);
        if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            map.put("traderId",trader.getId());
        }else if(User.USER_TYPE_ADVISOR.equals(user.getUserType())){
            String traderId = CrmUtils.getUserRelId(user);
            CrmTrader trader = traderService.getById(traderId);
            map.put("traderId",trader.getId());
        }if(User.USER_TYPE_WXG.equals(user.getUserType())){
            //平台人员
            //获取当前人员所负责代理商
            Record rd = CrmUtils.getByUserId(user);
            String trader_id=rd.getStr("trader_id");
            if(StringUtil.isNotBlank(trader_id)){
                map.put("traderIds",trader_id);
            }
        }
        accountService.listTraderAccount(map, layuiPage);
        return layuiPage.renderJson();
    }

    //查看详情
    @RequestMapping(value = "bondAccountListDetail")
    public String bondAccountListDetail(HttpServletRequest request,Model model){
        String traderId=request.getParameter("traderId");
        Map<String, String> map = getParams(request);
        List<Record> details=bondApplyService.getDetailByTraderId(map);
        model.addAttribute("details",details);
        if(details.size()>0){
            model.addAttribute("apply",details.get(0));
        }
        return "modules/flowpath/bondAccountListDetail";
    }

    /**
     * 可铺货变动明细
     */
    @RequestMapping(value = "toKphBdDetail")
    public Object toKphBdDetail(Model model){
        User user = UserUtils.getUser();
        if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            CrmTraderAccount account = accountService.findByTraderId(trader.getId());
            model.addAttribute("account", account);
        }
        //代理商列表
        List<Record> traderList = traderService.getTopTrader2();
        model.addAttribute("traderList", traderList);
        model.addAttribute("user", user);
        return "modules/yangguang/account/kph/changeDetailList";
    }

    /**
     * 待结算账户-账户明细
     */
    @RequestMapping(value = "toDjsAccountDetail")
    public String toDjsAccount(Model model){
        //代理商列表
        List<Record> traderList = traderService.getTopTrader2();
        model.addAttribute("traderList", traderList);
        return "modules/yangguang/account/djs/accountDetailList";
    }

    /**
     * 待结算账户-变动明细
     */
    @RequestMapping(value = "toDjsChangeDetail")
    public String toDjsChangeDetail(Model model){
        User user = UserUtils.getUser();
        if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            CrmTraderAccount account = accountService.findByTraderId(trader.getId());
            model.addAttribute("account", account);
            model.addAttribute("trader", trader);
        }
        //代理商列表
        List<Record> traderList = traderService.getTopTrader2();
        model.addAttribute("traderList", traderList);
        model.addAttribute("user", user);
        return "modules/yangguang/account/djs/changeDetailList";
    }

    //待结算账户  变动明细列表数据
    @ResponseBody
    @RequestMapping(value = "djsAccountChangeLst")
    public String djsAccountChangeLst(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            map.put("traderId",trader.getId());
        }else if(User.USER_TYPE_ADVISOR.equals(user.getUserType())){
            String traderId = CrmUtils.getUserRelId(user);
            CrmTrader trader = traderService.getById(traderId);
            map.put("traderId",trader.getId());
        }if(User.USER_TYPE_WXG.equals(user.getUserType())){
            //平台人员
            //获取当前人员所负责代理商
            Record rd = CrmUtils.getByUserId(user);
            String trader_id=rd.getStr("trader_id");
            if(StringUtil.isNotBlank(trader_id)){
                map.put("traderId",trader_id);
            }
        }
        LayuiPage page = new LayuiPage(request);
        accountService.djsAccountChangeList(page,map);
        return page.renderJson();
    }

    /**
     * 待结算账户-结算明细
     */
    @RequestMapping(value = "toDjsSettleDetail")
    public String toDjsSettleDetail(Model model){
        User user = UserUtils.getUser();
        if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            model.addAttribute("trader", trader);
        }
        List<Record> projectList = memberService.getProjectLists();;
        model.addAttribute("projectList", projectList);
        //代理商列表
        List<Record> traderList = traderService.getTopTrader2();
        model.addAttribute("traderList", traderList);
        model.addAttribute("user", user);
        model.addAttribute("formId", FormUtils.CASH_OUT_APPLY);
        List<Record> twoTrader=traderService.getTwoTrader(user.getTraderId());
        model.addAttribute("twoTrader",twoTrader);
        model.addAttribute("paterns", partnerService.partnerList());
        return "modules/yangguang/account/djs/settleDetailList";
    }

    /**
     * 结算明细请求
     */
    @ResponseBody
    @RequestMapping(value = "ajaxForSettleDetail")
    public Object ajaxForSettleDetail(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        LayuiPage layuiPage = new LayuiPage(request);
        settleDetailService.listSettleDetail(map, layuiPage);
        return layuiPage.renderJson();
    }

    /**
     * 质保金账户-账户明细
     */
    @RequestMapping(value = "toZbjAccountDetail")
    public String toZbjAccount(Model model){
        //代理商列表
        List<Record> traderList = traderService.getTopTrader2();
        model.addAttribute("traderList", traderList);
        return "modules/yangguang/account/zbj/accountDetailList";
    }

    /**
     * 质保金账户-变动明细
     */
    @RequestMapping(value = "toZbjChangeDetail")
    public String toZbjChangeDetail(Model model){
        User user = UserUtils.getUser();
        if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            CrmTraderAccount account = accountService.findByTraderId(trader.getId());
            model.addAttribute("account", account);
            model.addAttribute("trader", trader);
        }
        //代理商列表
        List<Record> traderList = traderService.getTopTrader2();
        model.addAttribute("traderList", traderList);
        model.addAttribute("user", user);
        return "modules/yangguang/account/zbj/changeDetailList";
    }

    //质保金账户--变动明细 列表数据
    @ResponseBody
    @RequestMapping(value = "zbjAccountChangeLst")
    public String zbjAccountChangeLst(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            map.put("traderId",trader.getId());
        }else if(User.USER_TYPE_ADVISOR.equals(user.getUserType())){
            String traderId = CrmUtils.getUserRelId(user);
            CrmTrader trader = traderService.getById(traderId);
            map.put("traderId",trader.getId());
        }if(User.USER_TYPE_WXG.equals(user.getUserType())){
            //平台人员
            //获取当前人员所负责代理商
            Record rd = CrmUtils.getByUserId(user);
            String trader_id=rd.getStr("trader_id");
            if(StringUtil.isNotBlank(trader_id)){
                map.put("traderId",trader_id);
            }
        }
        LayuiPage page = new LayuiPage(request);
        accountService.zbjAccountChangeLst(page,map);
        return page.renderJson();
    }


    /**
     * 质保金账户-结算明细
     */
    @RequestMapping(value = "toZbjSettleDetail")
    public String toZbjSettleDetail(Model model){
        User user = UserUtils.getUser();
        if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            model.addAttribute("trader", trader);
        }
        List<Record> projectList = memberService.getProjectLists();
        model.addAttribute("projectList", projectList);
        //代理商列表
        List<Record> traderList = traderService.getTopTrader2();
        model.addAttribute("traderList", traderList);
        model.addAttribute("user", user);
        model.addAttribute("formId", FormUtils.CASH_OUT_APPLY);
        List<Record> twoTrader=traderService.getTwoTrader(user.getTraderId());
        model.addAttribute("twoTrader",twoTrader);
        return "modules/yangguang/account/zbj/settleDetailList";
    }

    /**
     * 保证金账户-账户明细
     */
    @RequestMapping(value = "toBondAccountDetail")
    public String toBondAccountDetail(Model model){
        //代理商列表
        List<Record> traderList = traderService.getTopTrader2();
        model.addAttribute("traderList", traderList);
        return "modules/yangguang/account/bzj/bondAccountList";
    }

    /**
     * 保证金账户-变动明细
     */
    @RequestMapping(value = "toBondChangeDetail")
    public String toBondChangeDetail(Model model){
        User user = UserUtils.getUser();
        if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            CrmTraderAccount account = accountService.findByTraderId(trader.getId());
            if(account!=null){
                BigDecimal yeAmount = Arith.add(account.getBzjAmount(),
                        account.getYkBzjAmount()).setScale(2, RoundingMode.HALF_UP);
                model.addAttribute("yeAmount",yeAmount);
            }
            Record accountRecord= accountService.getBondDetail(trader.getId());
            model.addAttribute("account", accountRecord);
            model.addAttribute("trader", trader);
        }
        //代理商列表
        List<Record> traderList = traderService.getTopTrader2();
        model.addAttribute("traderList", traderList);
        model.addAttribute("user", user);
        return "modules/yangguang/account/bzj/bondChangeDetailList";
    }

    /**
     * 计算代理商的授信额度
    */
    @ResponseBody
    @RequestMapping(value = "budgetForCreditBalance")
    public Result budgetForCreditBalance(BigDecimal totalAmount,String entryIds,String type){
        User user = UserUtils.getUser();
        String traderId = CrmUtils.getUserRelId(user);
        //计算代理商的授信额
      //  CrmTraderAccount account = accountService.findByTraderId(traderId);

        //1.判断代理商是否是首次备货
        long count = DeliverOrderUtils.findOrderCount(traderId);
        BigDecimal CreditLimit;
       /* if("1".equals(type)){*/

            if(count>0){
                //非首次
               /* Record set =accountSetService.findTraderSxeProportion(traderId, AccountSetConstants.TYPE_AMOUNT_TOP);
                if(set==null){
                    return Result.fail("201","无授信额计算规则");
                }
                //累计发货量
                BigDecimal yfhAmount =  DeliverOrderUtils.findTraderAmount(traderId);

                //累计已安装量
                BigDecimal yazAmount = BigDecimal.ZERO;
                //未安装量 == 已发货量-已安装量*1.5/1000
                BigDecimal yazbs =  yazAmount.multiply(new BigDecimal("1.5")).divide(new BigDecimal(1000),4, BigDecimal.ROUND_HALF_UP);
                //累计已并网量
                BigDecimal ybwAmount = BigDecimal.ZERO;
                //未安装量 == 已发货量-已安装量*1.5/1000
                BigDecimal ybwbs =  ybwAmount.multiply(new BigDecimal("1.5")).divide(new BigDecimal(1000),4, BigDecimal.ROUND_HALF_UP);

                BigDecimal notAzamount = yfhAmount.subtract(yazbs);

                BigDecimal notBwamount = yfhAmount.subtract(ybwbs);
                //min(实缴保证金金额+保证金*2倍-累计未安装量，保证金*5倍-累计未并网量
              BigDecimal bzjAmoount= account.getBzjAmount().add(account.getBondAmountLimit().multiply(set.getBigDecimal("amount"))).subtract(notAzamount);
              BigDecimal bwtotal=  account.getBondAmountLimit().multiply(set.getBigDecimal("capacity_multiple")).subtract(notBwamount);

                if (bzjAmoount.compareTo(bwtotal) == -1) {
                    CreditLimit =  bzjAmoount;
                }else if (bzjAmoount.compareTo(bwtotal) == 1) {
                    CreditLimit =  bwtotal;
                }else{
                    CreditLimit =  bwtotal;
                }*/
                CreditLimit =  accountService.countLimit(traderId,"1");
            }else{

                CreditLimit =  accountService.countLimit(traderId,"0");
            /*    Record set =accountSetService.findTraderSxeProportion(traderId, AccountSetConstants.TYPE_STAND_PRICE);
               if(set==null){
                   return Result.fail("201","无授信额计算规则");
               }
                //获取所有电站的设计容量
                BigDecimal design_capacity = DeliverOrderUtils.findCustomerEntrydesign(entryIds);
                BigDecimal entryAmount = design_capacity.multiply(set.getBigDecimal("capacity_ratio")).multiply(set.getBigDecimal("capacity_multiple"));

                //保证金*系数
                BigDecimal bzjAmoount = account.getBondAmountLimit().multiply(set.getBigDecimal("amount"));

                if (entryAmount.compareTo(bzjAmoount) == 0){
                    CreditLimit =  account.getBzjAmount().add(bzjAmoount);
                }else if (entryAmount.compareTo(bzjAmoount) == -1) {
                    CreditLimit =  account.getBzjAmount().add(entryAmount);
                }else if (entryAmount.compareTo(bzjAmoount) == 1) {
                    CreditLimit =  account.getBzjAmount().add(bzjAmoount);
                }
*/
            }

       /* }else{
            CreditLimit = account.getBzjAmount();
        }*/
        if (CreditLimit == null) {
           CreditLimit = BigDecimal.ZERO;
        }
        Result result = new Result();
        result.setData(CreditLimit);
        if (CreditLimit.compareTo(totalAmount) == -1) {
            result.setCode("202");
            return result;
        }
        result.setCode("200");
        return result;
    }
    /**
     * 计算代理商的授信额度
     */
    @ResponseBody
    @RequestMapping(value = "budgetForCreditBalance2")
    public Result budgetForCreditBalance2(BigDecimal totalAmount,String traderId,BigDecimal predictAmount){
        //计算代理商的授信额
        //1.判断代理商是否是首次备货
        long count = DeliverOrderUtils.findOrderCount(traderId);
        BigDecimal CreditLimit;
        if(count>0){
            CreditLimit =  accountService.countLimit(traderId,"1");
        }else{
            CreditLimit =  accountService.countLimit(traderId,"0");
        }
        if (CreditLimit == null) {
            CreditLimit = BigDecimal.ZERO;
        }
        Result result = new Result();
        BigDecimal actualCreditLimit = CreditLimit.add(predictAmount);
        result.setData(actualCreditLimit);
        if (actualCreditLimit.compareTo(totalAmount) == -1) {
            result.setCode("202");
            return result;
        }
        result.setCode("200");
        return result;
    }

    //代理商端--授信账户
    @RequestMapping("toSxAccount")
    public  String toSxAccount(HttpServletRequest request,Model model){
        User user = UserUtils.getUser();
        String traderId="";
        if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            traderId=trader.getId();
        }else if(User.USER_TYPE_ADVISOR.equals(user.getUserType())){
            traderId = CrmUtils.getUserRelId(user);
        }
        Map<String,String> params=new HashMap<>();
        params.put("traderId",traderId);
        params.put("formType","1");
        LayuiPage layuiPage = new LayuiPage(request);
        List<Record> accountList = traderAccountDao.listTraderAccount(params, layuiPage);
        Record account = null;
        if(accountList!=null && accountList.size()>0){
            account=accountList.get(0);
            BigDecimal bzjAmount=(account.getBigDecimal("bzjAmount").add(account.getBigDecimal("yk_bzj_amount")));
            BigDecimal bzjLimitAmount=account.getBigDecimal("bondAmountLimit");
            model.addAttribute("bzjAmount",bzjAmount);
            model.addAttribute("bzjLimitAmount",bzjLimitAmount);
        }
        model.addAttribute("account",account);
        model.addAttribute("traderId",traderId);
        Record edSetSc=traderAccountDao.getEdSetRecord(traderId,"1");
        Record edSetHx=traderAccountDao.getEdSetRecord(traderId,"2");
        model.addAttribute("edSetSc",edSetSc);
        model.addAttribute("edSetHx",edSetHx);
        return "modules/yangguang/account/kph/sxAccountDetail";
    }

    /**
     * 计算代理商的发货额度/后续发货额度  type 0 首次 type >0 后续发货额度
     * 首次发货额度：实缴保证金金额+min(通过踏勘审核的进件量*1.2倍，保证金*2倍）/
     * 发货额度：min(实缴保证金金额+保证金*2倍-累计未安装量，保证金*5倍-累计未并网量）
     */
    @ResponseBody
    @RequestMapping(value = "countLimit")
    public Result countLimit(HttpServletRequest request){
        String traderId=request.getParameter("traderId");
        String type=request.getParameter("type");
//        BigDecimal result=accountService.countLimit(traderId,type);
        Map<String, Object> map = accountService.countLimit2(traderId, type);
        if("0".equals(type)){
            Record edSetSc=traderAccountDao.getEdSetRecord(traderId,"1");
            map.put("edSet",edSetSc);
        }else {
            Record edSetHx=traderAccountDao.getEdSetRecord(traderId,"2");
            map.put("edSet",edSetHx);
        }
        Result re=Result.ok();
        re.setData(map);
        return  re;
    }

    @RequestMapping(value = "toEditAmountPage")
    public String toEditAmountPage(String amount,String traderId,String type,Model model){
        model.addAttribute("amount", amount);
        model.addAttribute("traderId", traderId);
        model.addAttribute("type", type);
        return "modules/yangguang/account/kph/editAmountPage";
    }
    @ResponseBody
    @RequestMapping(value = "editAmount")
    public Result editAmount(HttpServletRequest request){
        String traderId=request.getParameter("traderId");
        String type=request.getParameter("type");
        String amount = request.getParameter("amount");
        traderAccountDao.editAmount(traderId, type, amount);
        return  Result.ok();
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response){
        Map<String, String> map = new HashMap<>();
        String traderId = request.getParameter("traderId");
        if (StringUtil.isNotBlank(traderId)){
            map.put("traderId",traderId);
        }
        User user = UserUtils.getUser();
        if(User.USER_TYPE_WXG.equals(user.getUserType())){
            //平台人员
            //获取当前人员所负责代理商
            Record rd = CrmUtils.getByUserId(user);
            String trader_id=rd.getStr("trader_id");
            if(StringUtil.isNotBlank(trader_id)){
                map.put("traderIds",trader_id);
            }
        }
        List<Record> records = accountService.getListForExportExcel(map);
        List<AccountDetailExcel> list = new ArrayList<>();
        for (Record record : records) {
            AccountDetailExcel excel = new AccountDetailExcel();
            excel.setTraderName(record.getStr("traderName"));
            excel.setBzjAmount(record.getBigDecimal("bzjAmount"));
            excel.setYkBzjAmount(record.getBigDecimal("yk_bzj_amount"));
            excel.setTotalOne(record.getBigDecimal("bzjAmount").add(record.getBigDecimal("yk_bzj_amount")));
            excel.setBondAmountLimit(record.getBigDecimal("bondAmountLimit"));
            excel.setYkTklTotalCapacity(record.getBigDecimal("yk_tkl_total_capacity"));
            excel.setDeliverTotalAmount(record.getBigDecimal("deliverTotalAmount"));
            excel.setYkDeliverTotalCapacity(record.getBigDecimal("yk_deliver_total_capacity"));
            excel.setTotalTwo(record.getBigDecimal("deliverTotalAmount").add(record.getBigDecimal("yk_deliver_total_capacity")));
            excel.setYazTotalCapacity(record.getBigDecimal("yazTotalCapacity"));
            excel.setYkYazTotalCapacity(record.getBigDecimal("yk_yaz_total_capacity"));
            excel.setTotalThree(record.getBigDecimal("yazTotalCapacity").add(record.getBigDecimal("yk_yaz_total_capacity")));
            excel.setYbwTotalCapacity(record.getBigDecimal("ybwTotalCapacity"));
            excel.setYkYbwTotalCapacity(record.getBigDecimal("yk_ybw_total_capacity"));
            excel.setTotalFour(record.getBigDecimal("ybwTotalCapacity").add(record.getBigDecimal("yk_ybw_total_capacity")));
            list.add(excel);
        }
        FileExportUtil.exportAccountExcel(list,response, DateUtils.getDate("yyyy-MM-dd"));
    }
}
