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.manage.entity.*;
import com.ssm.manage.excelEntity.ExcelPromotion;
import com.ssm.manage.query.DocPromotionRequest;
import com.ssm.manage.query.SysRoleStoreRequest;
import com.ssm.manage.response.DocPromotionResponse;
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/docPromotion")
@Slf4j
public class SsmDocPromotionController {
    @Autowired
    private SsmDocPromotionService ssmDocPromotionService;
    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;
    @Autowired
    private SsmPayService ssmPayService;
    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @ApiOperation(value = "分页查询  门店端-促销活动单-分页查询促销活动单", httpMethod = "POST", response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody DocPromotionRequest docPromotionRequest, HttpSession session) {
        PageResponse<DocPromotionResponse> pageResponse = new PageResponse<>();
        PageInfo<DocPromotionResponse> pageInfo = new PageInfo<>();
        docPromotionRequest.setStoreId(SessionHelp.getStoreId(session));
        if(SessionHelp.getStoreId(session)==null){
            pageResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return pageResponse;
        }
        try {
            pageInfo = ssmDocPromotionService.selectPage(docPromotionRequest);
        } catch (Exception e) {
            log.error("SsmDocPromotionController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }
    @Autowired
    private SsmSysRoleStoreService ssmSysRoleStoreService;

    @ApiOperation(value = "分页查询  门店端-促销活动单-分页查询促销活动单（新）", httpMethod = "POST", response = PageResponse.class)
    @RequestMapping("/pageNew")
    public PageResponse selectPageNew(@RequestBody DocPromotionRequest docPromotionRequest, HttpSession session) {
        PageResponse<DocPromotionResponse> pageResponse = new PageResponse<>();
        PageInfo<DocPromotionResponse> pageInfo = new PageInfo<>();
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(SessionHelp.getStoreId(session));
        if(baseStore.getParentId()==null) {
            if (null == docPromotionRequest.getStoreList() || docPromotionRequest.getStoreList().size() == 0) {
                //自动查询
                docPromotionRequest.setSelectType(0);
                SysRoleStoreRequest sysStoreRole = new SysRoleStoreRequest();
                sysStoreRole.setRoleId(docPromotionRequest.getRoleId());
                PageInfo<SysRoleStore> sysRoleStorePageInfo = ssmSysRoleStoreService.selectPage(sysStoreRole);
                List<Long> collect = sysRoleStorePageInfo.getList().stream().map(item -> item.getStoreId()).collect(Collectors.toList());
                docPromotionRequest.setStoreList(collect);
                if (SessionHelp.getStoreId(session) == null) {
                    pageResponse.setCodeAndMsg(ResponseCode.MSG, "登录失效，请退出重新登录！");
                    return pageResponse;
                }
                docPromotionRequest.setStoreId(SessionHelp.getStoreId(session));
            } else {
                //指定查询
                docPromotionRequest.setSelectType(0);
            }
        }else {
            docPromotionRequest.setSelectType(1);
            docPromotionRequest.setStoreId(SessionHelp.getStoreId(session));
        }

        try {
            pageInfo = ssmDocPromotionService.selectPageNew(docPromotionRequest);
        } catch (Exception e) {
            log.error("SsmDocPromotionController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @RequestMapping("/pageDetail")
    public PageResponse pageDetail(@RequestBody DocPromotionRequest docPromotionRequest, HttpSession session) {
        PageResponse<DocPromotionResponse> pageResponse = new PageResponse<>();
        PageInfo<DocPromotionResponse> pageInfo = new PageInfo<>();
        docPromotionRequest.setStoreId(SessionHelp.getStoreId(session));
        if(SessionHelp.getStoreId(session)==null){
            pageResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return pageResponse;
        }
        try {
            pageInfo = ssmDocPromotionService.pageDetail(docPromotionRequest);
        } catch (Exception e) {
            log.error("SsmDocPromotionController.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("/add")
//    @RequestMapping("/addPromotionRechargeList")
    public GenericResponse add(@RequestBody DocPromotionRequest docPromotionRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        docPromotionRequest.setStoreId(storeId);
        docPromotionRequest.setStoreName(storeName);
        docPromotionRequest.setStaffPhone(staffPhone);
        docPromotionRequest.setSession(session);
        int i = 0;
        if(!"".equals(docPromotionRequest.getProjectArray()) && null != docPromotionRequest.getProjectArray()){
            String substring = docPromotionRequest.getProjectArray().substring(0, docPromotionRequest.getProjectArray().length() - 1);
            docPromotionRequest.setProjectArray(substring);
        }
        try {
            if(docPromotionRequest.getCollectionCashAmount()==null||docPromotionRequest.getCollectionCashAmount().longValue()<0||docPromotionRequest.getCollectionRechargeAmount().longValue()<0){
                throw new SmsException("010000","操作失败，不能输入负数");
            }
            i = ssmDocPromotionService.addDoc(docPromotionRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmDocPromotionController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }
    @ApiOperation(value = "促销活动单添加  (门店端-促销活动单-促销活动单添加)", httpMethod = "POST", response = GenericResponse.class)
//    @RequestMapping("/add")
    @RequestMapping("/addPromotionRechargeList")
    public GenericResponse addPromotionRechargeList(@RequestBody DocPromotionRequest docPromotionRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        docPromotionRequest.setStoreId(storeId);
        docPromotionRequest.setStoreName(storeName);
        docPromotionRequest.setStaffPhone(staffPhone);
        docPromotionRequest.setSession(session);
        int i = 0;
        if(!"".equals(docPromotionRequest.getProjectArray()) && null != docPromotionRequest.getProjectArray()){
            String substring = docPromotionRequest.getProjectArray().substring(0, docPromotionRequest.getProjectArray().length() - 1);
            docPromotionRequest.setProjectArray(substring);
        }
        try {
            if(docPromotionRequest.getCollectionCashAmount()==null||docPromotionRequest.getCollectionCashAmount().longValue()<0||docPromotionRequest.getCollectionRechargeAmount().longValue()<0){
                throw new SmsException("010000","操作失败，不能输入负数");
            }
            i = ssmDocPromotionService.addPromotionRechargeList(docPromotionRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmDocPromotionController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "疗程单作废  (门店端-疗程单-疗程单作废)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/cancel")
//    @RequestMapping("/cancelPromotionRecharge")
    public GenericResponse cancel(@RequestBody DocPromotionRequest docPromotionRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        docPromotionRequest.setStoreId(storeId);
        docPromotionRequest.setStoreName(storeName);
        docPromotionRequest.setStaffPhone(staffPhone);
        int i = 0;
        try {
            i = ssmDocPromotionService.cancel(docPromotionRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmDocPromotionController.cancel:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "疗程单作废  (门店端-疗程单-疗程单作废)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/cancelPromotionRecharge")
//    @RequestMapping("/cancel")
    public GenericResponse cancelPromotionRecharge(@RequestBody DocPromotionRequest docPromotionRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        docPromotionRequest.setStoreId(storeId);
        docPromotionRequest.setStoreName(storeName);
        docPromotionRequest.setStaffPhone(staffPhone);
        int i = 0;
        try {
            i = ssmDocPromotionService.cancelPromotionRecharge(docPromotionRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmDocPromotionController.cancel:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "促销活动单业务员修改  (门店端-促销活动单-促销活动单业务员修改)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/updateStaff")
    public GenericResponse updateStaff(@RequestBody DocPromotionRequest docPromotionRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        docPromotionRequest.setStoreId(storeId);
        docPromotionRequest.setStoreName(storeName);
        docPromotionRequest.setStaffPhone(staffPhone);
        docPromotionRequest.setSession(session);
        int i = 0;
        try {
            i = ssmDocPromotionService.updateStaff(docPromotionRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmDocPromotionController.updateStaff:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }
    @ApiOperation(value = "单据导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/docPromotion/exportachis")
    public void exportachis(@RequestBody DocPromotionRequest docPromotionRequest, 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/docPromotion.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelPromotion> excelBaseProjectTypeList = new ArrayList<>();
            List<DocPromotion> list = ssmDocPromotionService.selectList(docPromotionRequest);
            if(list!=null && list.size()>0) {
//            salesmen = ssmSalesmanService.selectList(salesman);
                //所有门店
                List<BaseStore> select = ssmBaseStoreService.select(null);
                //所有项目id
//            List<Long> projectIds = list.stream().filter(courseList -> courseList.getProjctId() != null).map(CourseList::getProjctId).collect(Collectors.toList());
//            List<BaseProject> projectList = ssmProjectService.selectList(projectIds);
                //所有单据号
                List<String> courseNums = list.stream().map(item -> item.getId().toString()).collect(Collectors.toList());
                List<PayList> payListList = ssmPayService.selectList(courseNums);
                //查询管理层和高管
                List<Long> courseIds = list.stream().map(DocPromotion::getId).collect(Collectors.toList());
                List<Salesman> salesmanList = ssmSalesmanService.selectList(courseIds);
                for (DocPromotion executives : list) {
                    ExcelPromotion excelBaseProjectType = new ExcelPromotion();
                    BeanUtils.copyProperties(executives, excelBaseProjectType);
                    excelBaseProjectType.setPayType("");
                    if (excelBaseProjectType.getIsCancel() == 0) {
                        excelBaseProjectType.setIsCancelNew("正常");
                    } else {
                        excelBaseProjectType.setIsCancelNew("作废");
                    }
                    //设置门店编码
                    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.getId().toString())) {
                            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().add(excelBaseProjectType.getCardAchievementAmount());
                    BigDecimal commissionAmount = excelBaseProjectType.getCommissionAmount().add(excelBaseProjectType.getCardCommissionAmount());
                    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)));
                    }


                    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();
        }
    }
}
