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.ssm.manage.response.GenericResponse;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.manage.entity.*;
import com.ssm.manage.excelEntity.ExcelRefundCash;
import com.ssm.manage.query.RefundCashReqest;
import com.ssm.manage.query.RefundOrderResquest;
import com.ssm.manage.response.RefundCashResponse;
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/ssm/refCash")
@Slf4j
public class SsmRefundCashController {
    @Autowired
    private SsmRefundCashService ssmRefundCashService;

    @Autowired
    private SsmRefundOrderService ssmRefundOrderService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmPayService ssmPayService;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmProjectService ssmProjectService;

    @ApiOperation(value = "消费退明细查询  门店端-疗程退-消费退明细查询", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/list")
    public GenericResponse selectList(@RequestBody RefundCashReqest refundCashReqest, HttpSession session) {
        GenericResponse<RefundCashResponse> genericResponse = new GenericResponse<>();
        if(refundCashReqest.getStoreId()==null)
        refundCashReqest.setStoreId(SessionHelp.getStoreId(session));
        List<RefundCashResponse> list = new ArrayList<>();
        try {
            list = ssmRefundCashService.selectList(refundCashReqest);
        } catch (Exception e) {
            log.error("SsmRefundCashController.selectList", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "单据导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/refundCash/exportachis")
    public void exportachis(@RequestBody RefundCashReqest refundCashReqest, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
//        courseListRequest.setStoreId(SessionHelp.getStoreId(session));

        String fileName = "projectType";
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            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/refundCash.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelRefundCash> excelBaseProjectTypeList = new ArrayList<>();
            List<RefundCash> list = ssmRefundCashService.selectListNew(refundCashReqest);
            if(list!=null && list.size()>0){
            RefundOrderResquest refundOrderList1 = new RefundOrderResquest();
            refundOrderList1.setType(2);
            refundOrderList1.setStrDate(refundCashReqest.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(RefundCash::getId).collect(Collectors.toList());
            List<Salesman> salesmanList = ssmSalesmanService.selectList(courseIds);
            for (RefundCash executives : list) {
                ExcelRefundCash excelBaseProjectType = new ExcelRefundCash();
                BeanUtils.copyProperties(executives, excelBaseProjectType);
                RefundOrderList refundOrderList = null;
                for (RefundOrderList orderList : refundOrderLists) {
                    if (executives.getRefundNum().equals(orderList.getRefundNum())) {
                        refundOrderList = orderList;
                    }
                }
                excelBaseProjectType.setStoreName(refundOrderList.getStoreName());
                excelBaseProjectType.setRefundNum(refundOrderList.getRefundNum());
                excelBaseProjectType.setRefundDate(refundOrderList.getRefundDate());
                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());
                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() != null && excelBaseProjectType.getCashNumber() == 1) {
                    excelBaseProjectType.setIsMember("是");
                } else {
                    excelBaseProjectType.setIsMember("否");
                }
                if (excelBaseProjectType.getRefundReason().equals("undefined")) {
                    excelBaseProjectType.setRefundReason("");
                }
                //设置项目编码
                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 hundred = new BigDecimal("100");
                //美容师所有业绩
                BigDecimal largeAchievementAmount = excelBaseProjectType.getLargeAchievementAmount().add(excelBaseProjectType.getCardLargeAchievementAmount());
                //美容师所有提成
                BigDecimal largeCommissionAmount = excelBaseProjectType.getLargeCommissionAmount().add(excelBaseProjectType.getCardLargeCommissionAmount());
                //美发师所有业绩
                BigDecimal zhonggongAchievementAmount = excelBaseProjectType.getZhonggongAchievementAmount().add(excelBaseProjectType.getCardZhonggongAchievementAmount());
                //美发师所有提成
                BigDecimal zhonggongCommissionAmount = excelBaseProjectType.getZhonggongCommissionAmount().add(excelBaseProjectType.getCardZhonggongCommissionAmount());
                //技师所有业绩
                BigDecimal technicianAchievementAmount = excelBaseProjectType.getTechnicianAchievementAmount().add(excelBaseProjectType.getCardTechnicianAchievementAmount());
                //技师所有提成
                BigDecimal technicianCommissionAmount = excelBaseProjectType.getTechnicianCommissionAmount().add(excelBaseProjectType.getCardTechnicianCommissionAmount());
                //助理所有业绩
                BigDecimal smallAchievementAmount = excelBaseProjectType.getSmallAchievementAmount().add(excelBaseProjectType.getCardSmallAchievementAmount());
                //助理所有提成
                BigDecimal smallCommissionAmount = excelBaseProjectType.getSmallCommissionAmount().add(excelBaseProjectType.getCardSmallCommissionAmount());

                //美容师
                if (excelBaseProjectType.getServiceLargeOneStaffId() != null) {
                    excelBaseProjectType.setServiceLargeOneAchievementAmount(largeAchievementAmount.multiply(excelBaseProjectType.getServiceLargeOneRatio().divide(hundred)));
                    excelBaseProjectType.setServiceLargeOneCommissionAmount(largeCommissionAmount.multiply(excelBaseProjectType.getServiceLargeOneRatio().divide(hundred)));
                }
                if (excelBaseProjectType.getServiceLargeTwoStaffId() != null) {
                    excelBaseProjectType.setServiceLargeTwoAchievementAmount(largeAchievementAmount.multiply(excelBaseProjectType.getServiceLargeTwoRatio().divide(hundred)));
                    excelBaseProjectType.setServiceLargeTwoCommissionAmount(largeCommissionAmount.multiply(excelBaseProjectType.getServiceLargeTwoRatio().divide(hundred)));
                }
                if (excelBaseProjectType.getServiceLargeThreeStaffId() != null) {
                    excelBaseProjectType.setServiceLargeThreeAchievementAmount(largeAchievementAmount.multiply(excelBaseProjectType.getServiceLargeThreeRatio().divide(hundred)));
                    excelBaseProjectType.setServiceLargeThreeCommissionAmount(largeCommissionAmount.multiply(excelBaseProjectType.getServiceLargeThreeRatio().divide(hundred)));
                }
                //美发师
                if (excelBaseProjectType.getServiceZhonggongOneStaffId() != null) {
                    excelBaseProjectType.setServiceZhonggongOneAchievementAmount(zhonggongAchievementAmount.multiply(excelBaseProjectType.getServiceZhonggongOneRatio().divide(hundred)));
                    excelBaseProjectType.setServiceZhonggongOneCommissionAmount(zhonggongCommissionAmount.multiply(excelBaseProjectType.getServiceZhonggongOneRatio().divide(hundred)));
                }
                if (excelBaseProjectType.getServiceZhonggongTwoStaffId() != null) {
                    excelBaseProjectType.setServiceZhonggongTwoAchievementAmount(zhonggongAchievementAmount.multiply(excelBaseProjectType.getServiceZhonggongTwoRatio().divide(hundred)));
                    excelBaseProjectType.setServiceZhonggongTwoCommissionAmount(zhonggongCommissionAmount.multiply(excelBaseProjectType.getServiceZhonggongTwoRatio().divide(hundred)));
                }
                if (excelBaseProjectType.getServiceZhonggongThreeStaffId() != null) {
                    excelBaseProjectType.setServiceZhonggongThreeAchievementAmount(zhonggongAchievementAmount.multiply(excelBaseProjectType.getServiceZhonggongThreeRatio().divide(hundred)));
                    excelBaseProjectType.setServiceZhonggongThreeCommissionAmount(zhonggongCommissionAmount.multiply(excelBaseProjectType.getServiceZhonggongThreeRatio().divide(hundred)));
                }
                //技师
                if (excelBaseProjectType.getServiceTechnicianOneStaffId() != null) {
                    excelBaseProjectType.setServiceTechnicianOneAchievementAmount(technicianAchievementAmount.multiply(excelBaseProjectType.getServiceTechnicianOneRatio().divide(hundred)));
                    excelBaseProjectType.setServiceTechnicianOneCommissionAmount(technicianCommissionAmount.multiply(excelBaseProjectType.getServiceTechnicianOneRatio().divide(hundred)));
                }
                if (excelBaseProjectType.getServiceTechnicianTwoStaffId() != null) {
                    excelBaseProjectType.setServiceTechnicianTwoAchievementAmount(technicianAchievementAmount.multiply(excelBaseProjectType.getServiceTechnicianTwoRatio().divide(hundred)));
                    excelBaseProjectType.setServiceTechnicianTwoCommissionAmount(technicianCommissionAmount.multiply(excelBaseProjectType.getServiceTechnicianTwoRatio().divide(hundred)));
                }
                if (excelBaseProjectType.getServiceTechnicianThreeStaffId() != null) {
                    excelBaseProjectType.setServiceTechnicianThreeAchievementAmount(technicianAchievementAmount.multiply(excelBaseProjectType.getServiceTechnicianThreeRatio().divide(hundred)));
                    excelBaseProjectType.setServiceTechnicianThreeCommissionAmount(technicianAchievementAmount.multiply(excelBaseProjectType.getServiceTechnicianThreeRatio().divide(hundred)));
                }
                //助理
                if (excelBaseProjectType.getServiceSmallOneStaffId() != null) {
                    excelBaseProjectType.setServiceSmallOneAchievementAmount(smallAchievementAmount.multiply(excelBaseProjectType.getServiceSmallOneRatio().divide(hundred)));
                    excelBaseProjectType.setServiceSmallOneCommissionAmount(smallCommissionAmount.multiply(excelBaseProjectType.getServiceSmallOneRatio().divide(hundred)));
                }
                if (excelBaseProjectType.getServiceSmallTwoStaffId() != null) {
                    excelBaseProjectType.setServiceSmallTwoAchievementAmount(smallAchievementAmount.multiply(excelBaseProjectType.getServiceSmallTwoRatio().divide(hundred)));
                    excelBaseProjectType.setServiceSmallTwoCommissionAmount(smallCommissionAmount.multiply(excelBaseProjectType.getServiceSmallTwoRatio().divide(hundred)));
                }
                if (excelBaseProjectType.getServiceSmallThreeStaffId() != null) {
                    excelBaseProjectType.setServiceSmallThreeAchievementAmount(smallAchievementAmount.multiply(excelBaseProjectType.getServiceSmallThreeRatio().divide(hundred)));
                    excelBaseProjectType.setServiceSmallThreeCommissionAmount(smallCommissionAmount.multiply(excelBaseProjectType.getServiceSmallThreeRatio().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();
        }

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
    }
}
