package com.ssm.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.github.pagehelper.PageInfo;
import com.ssm.manage.response.GenericResponse;
import com.ssm.manage.response.PageResponse;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.manage.entity.*;
import com.ssm.manage.excelEntity.ExcelRefundRecharge;
import com.ssm.manage.extendEntity.RecDocList;
import com.ssm.manage.query.RefundOrderResquest;
import com.ssm.manage.query.RefundRechargeRequest;
import com.ssm.manage.response.RefundRechargeResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api(value = "充值退controller", tags = {"充值退相关接口"})
@RestController
@RequestMapping("/demay/refundRec")
@Slf4j
public class SsmRefundRechargeController {

    @Autowired
    private SsmRefundOrderService ssmRefundOrderService;
    @Autowired
    private SsmSalesmanService ssmSalesmanService;
    @Autowired
    private SsmProjectService ssmProjectService;
    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;
    @Autowired
    private SsmRefundRechargeService ssmRefundRechargeService;

    @ApiOperation(value = "分页查询  门店端-充值类别-分页查询充值类别", httpMethod = "POST", response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody RefundRechargeRequest refundRechargeRequest, HttpSession session) {
        PageResponse<RefundRechargeResponse> pageResponse = new PageResponse<>();
        PageInfo<RefundRechargeResponse> pageInfo = new PageInfo<>();
        //refundRechargeRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            pageInfo = ssmRefundRechargeService.selectPage(refundRechargeRequest);
        } catch (Exception e) {
            log.error("SsmRefundRechargeController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "充值退账户对应单据查询  (门店端-退款单-充值退账户对应单据查询)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/recDocList")
    public GenericResponse recDocList(@RequestBody RefundRechargeRequest rechargeRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        rechargeRequest.setStoreId(storeId);
        rechargeRequest.setStoreName(storeName);
        List<RecDocList> lists = new ArrayList<>();
        try {
            lists = ssmRefundRechargeService.recDocList(rechargeRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmRefundRechargeController.recDocList:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setRows(lists);
        genericResponse.setCodeAndMsg(ResponseCode.OK);

        return genericResponse;
    }

    @ApiOperation(value = "充值退账户对应历史单据查询 金额反算使用  (门店端-退款单-充值退账户对应历史单据查询 金额反算使用)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/refundRechargeMoney")
    public GenericResponse refundRechargeList(@RequestBody RefundRechargeRequest rechargeRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        rechargeRequest.setStoreId(storeId);
        rechargeRequest.setStoreName(storeName);
//        List<RechargeList> lists = new ArrayList<>();
        BigDecimal refundMoney = BigDecimalUtils.bigDecimal("0");
        try {
            refundMoney = ssmRefundRechargeService.refundRechargeMoney(rechargeRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmRefundRechargeController.refundRechargeMoney:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setData(refundMoney);
        genericResponse.setCodeAndMsg(ResponseCode.OK);

        return genericResponse;
    }
    @ApiOperation(value = "单据导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/refundRecharge/exportachis")
    public void exportachis(@RequestBody RefundRechargeRequest refundRechargeRequest, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
//        courseListRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            String fileName = "projectType";
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");
            out = response.getOutputStream();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/refundRecharge.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelRefundRecharge> excelBaseProjectTypeList = new ArrayList<>();
            List<RefundRecharge> list = ssmRefundRechargeService.selectListNew(refundRechargeRequest);
            if(list!=null && list.size()>0) {
                RefundOrderResquest refundOrderList1 = new RefundOrderResquest();
                refundOrderList1.setType(0);
                refundOrderList1.setStrDate(refundRechargeRequest.getStrDate());
                List<RefundOrderList> refundOrderLists = ssmRefundOrderService.selectNew(refundOrderList1);
//            salesmen = ssmSalesmanService.selectList(salesman);
                //所有门店

                List<BaseStore> select = ssmBaseStoreService.select(null);
                //所有项目id
//            List<Long> projectIds = list.stream().filter(courseList -> courseList.getProjectId() != null).map(RefundCash::getProjectId).collect(Collectors.toList());
//            List<BaseProject> projectList = ssmProjectService.selectList(projectIds);
                //所有单据号
//            List<String> courseNums = list.stream().map(RepayTradeList::getRepayNum).collect(Collectors.toList());
//            List<PayList> payListList = ssmPayService.selectList(courseNums);
                //查询管理层和高管
                List<Long> courseIds = list.stream().map(RefundRecharge::getId).collect(Collectors.toList());
                List<Salesman> salesmanList = ssmSalesmanService.selectList(courseIds);
                for (RefundRecharge executives : list) {
                    ExcelRefundRecharge excelBaseProjectType = new ExcelRefundRecharge();
                    BeanUtils.copyProperties(executives, excelBaseProjectType);
                    RefundOrderList refundOrderList = null;
                    for (RefundOrderList orderList : refundOrderLists) {
                        if (executives.getRefundNum().equals(orderList.getRefundNum())) {
                            refundOrderList = orderList;
                        }
                    }
                    excelBaseProjectType.setMemberName(refundOrderList.getMemberName());
                    excelBaseProjectType.setMobilePhone(refundOrderList.getMobilePhone());
                    excelBaseProjectType.setPayee(refundOrderList.getPayee());
                    excelBaseProjectType.setRefundType(refundOrderList.getRefundType());
                    excelBaseProjectType.setRefundAccount(refundOrderList.getRefundAccount());
                    excelBaseProjectType.setCashNum(refundOrderList.getSourceDocNum());
                    excelBaseProjectType.setRefundReason(refundOrderList.getRefundReason());
                    excelBaseProjectType.setRefundMoney(refundOrderList.getRefundMoney());
                    excelBaseProjectType.setCompensation(refundOrderList.getCompensation());
                    if (refundOrderList.getState() == 0) {
                        excelBaseProjectType.setStateNew("新建");
                    } else if (refundOrderList.getState() == 1) {
                        excelBaseProjectType.setStateNew("送审");
                    } else if (refundOrderList.getState() == 2) {
                        excelBaseProjectType.setStateNew("回收");
                    } else if (refundOrderList.getState() == 3) {
                        excelBaseProjectType.setStateNew("已审核");
                    } else if (refundOrderList.getState() == 4) {
                        excelBaseProjectType.setStateNew("反审核");
                    } else if (refundOrderList.getState() == 5) {
                        excelBaseProjectType.setStateNew("作废");
                    }
//                if(excelBaseProjectType.getCashNumber()==1){
//                    excelBaseProjectType.setIsMember("是");
//                }else {
//                    excelBaseProjectType.setIsMember("否");
//                }
                    //设置项目编码
//                if(executives.getProjectId()!=null){
//                    for (BaseProject baseProject : projectList) {
//                        if( executives.getProjectId()==baseProject.getId() || executives.getProjectId().equals(baseProject.getId())){
//                            excelBaseProjectType.setProjectNum(baseProject.getProjectNum());
//                        }
//                    }
//                }
                    //设置门店编码
                    for (BaseStore baseStore : select) {
                        if (baseStore.getId() == excelBaseProjectType.getStoreId() || baseStore.getId().equals(excelBaseProjectType.getStoreId())) {
                            excelBaseProjectType.setStoreNum(baseStore.getStoreNum());
                        }
                    }
//                //设置支付方式
//                for (PayList payList : payListList) {
//                    if(payList.getDocId().equals(executives.getCashNum())){
//                        excelBaseProjectType.setPayType(excelBaseProjectType.getPayType() + payList.getPayName()+":"+payList.getPayMoney()+"元-");
//                    }
//                }
                    //设置高管和管理层
                    List<Salesman> guanliceng = salesmanList.stream().filter(item -> (item.getOrderId().equals(executives.getId().toString())) && (item.getStaffType() == 1 || item.getStaffType().equals("1"))).collect(Collectors.toList());
                    List<Salesman> gaoguan = salesmanList.stream().filter(item -> (item.getOrderId().equals(executives.getId().toString())) && (item.getStaffType() == 0 || item.getStaffType().equals("0"))).collect(Collectors.toList());
                    if (guanliceng != null && guanliceng.size() > 0) {
                        for (int i = 0; i < guanliceng.size(); i++) {
                            if (i == 0) {
                                excelBaseProjectType.setSalmenOneNumber(guanliceng.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmenOneName(guanliceng.get(i).getStaffName());
                                excelBaseProjectType.setSalmenOneRatio(guanliceng.get(i).getRatio().toString());
                            }
                            if (i == 1) {
                                excelBaseProjectType.setSalmenTwoNumber(guanliceng.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmenTwoName(guanliceng.get(i).getStaffName());
                                excelBaseProjectType.setSalmenTwoRatio(guanliceng.get(i).getRatio().toString());
                            }
                            if (i == 2) {
                                excelBaseProjectType.setSalmenThreeNumber(guanliceng.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmenThreeName(guanliceng.get(i).getStaffName());
                                excelBaseProjectType.setSalmenThreeRatio(guanliceng.get(i).getRatio().toString());
                            }
                            if (i == 3) {
                                excelBaseProjectType.setSalmenFourNumber(guanliceng.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmenFourName(guanliceng.get(i).getStaffName());
                                excelBaseProjectType.setSalmenFourRatio(guanliceng.get(i).getRatio().toString());
                            }
                        }
                    }
                    if (gaoguan != null && gaoguan.size() > 0) {
                        for (int i = 0; i < gaoguan.size(); i++) {
                            if (i == 0) {
                                excelBaseProjectType.setSalmensOneNumber(gaoguan.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmensOneName(gaoguan.get(i).getStaffName());
                                excelBaseProjectType.setSalmensOneRatio(gaoguan.get(i).getRatio().toString());
                            }
                            if (i == 1) {
                                excelBaseProjectType.setSalmensTwoNumber(gaoguan.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmensTwoName(gaoguan.get(i).getStaffName());
                                excelBaseProjectType.setSalmensTwoRatio(gaoguan.get(i).getRatio().toString());
                            }
                            if (i == 2) {
                                excelBaseProjectType.setSalmensThreeNumber(gaoguan.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmensThreeName(gaoguan.get(i).getStaffName());
                                excelBaseProjectType.setSalmensThreeRatio(gaoguan.get(i).getRatio().toString());
                            }
                            if (i == 3) {
                                excelBaseProjectType.setSalmensFourNumber(gaoguan.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmensFourName(gaoguan.get(i).getStaffName());
                                excelBaseProjectType.setSalmensFourRatio(gaoguan.get(i).getRatio().toString());
                            }
                        }
                    }

                    //设置销售人员业绩和提成
                    BigDecimal achievementAmount = excelBaseProjectType.getAchievementAmount();
                    BigDecimal commissionAmount = excelBaseProjectType.getCommissionAmount();
                    BigDecimal hundred = new BigDecimal("100");
                    if (excelBaseProjectType.getSaleOneStaffId() != null) {
                        excelBaseProjectType.setSaleOneAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleOneRatio().divide(hundred)));
                        excelBaseProjectType.setSaleOneCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleOneRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleTwoStaffId() != null) {
                        excelBaseProjectType.setSaleTwoAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleTwoRatio().divide(hundred)));
                        excelBaseProjectType.setSaleTwoCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleTwoRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleThreeStaffId() != null) {
                        excelBaseProjectType.setSaleThreeAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleThreeRatio().divide(hundred)));
                        excelBaseProjectType.setSaleThreeCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleThreeRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleFourStaffId() != null) {
                        excelBaseProjectType.setSaleFourAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleFourRatio().divide(hundred)));
                        excelBaseProjectType.setSaleFourCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleFourRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleFiveStaffId() != null) {
                        excelBaseProjectType.setSaleFiveAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleFiveRatio().divide(hundred)));
                        excelBaseProjectType.setSaleFiveCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleFiveRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleSixStaffId() != null) {
                        excelBaseProjectType.setSaleSixAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleSixRatio().divide(hundred)));
                        excelBaseProjectType.setSaleSixCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleSixRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleSevenStaffId() != null) {
                        excelBaseProjectType.setSaleSevenAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleSevenRatio().divide(hundred)));
                        excelBaseProjectType.setSaleSevenCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleSevenRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleEightStaffId() != null) {
                        excelBaseProjectType.setSaleEightAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleEightRatio().divide(hundred)));
                        excelBaseProjectType.setSaleEightCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleEightRatio().divide(hundred)));
                    }

                    excelBaseProjectTypeList.add(excelBaseProjectType);
                }
            }
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            //EasyExcel.write(out, LiveRoomData.class).sheet("模板").doWrite(list);
            excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
            //FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(excelBaseProjectTypeList, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmProjectTypeController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }
}
