package com.ssm.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
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.entity.BaseZengkaRequest;
import com.ssm.manage.excelEntity.ExcelZengka;
import com.ssm.manage.response.BaseZengkaResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmBaseZengkaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
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.util.*;
import java.util.stream.Collectors;

@Api(value="门店充值卡赠送表controller",tags={"门店充值卡赠送相关接口"})
@RestController
@RequestMapping("/demay/ssm/baseZengka")
@Slf4j
public class SsmBaseZengkaController {

    @Autowired
    private SsmBaseZengkaService ssmBaseZengkaService;

    @ApiOperation(value = "查询全部员工排班",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody BaseZengkaRequest baseZengkaRequest, HttpSession session){
        PageResponse<BaseZengkaResponse> pageResponse = new PageResponse<>();
        PageInfo<BaseZengkaResponse> pageInfo = new PageInfo<>();
        Long storeId = SessionHelp.getStoreId(session);
        if(storeId==null){
            pageResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return pageResponse;
        }
        baseZengkaRequest.setStoreId(storeId);
        try {
            pageInfo = ssmBaseZengkaService.selectPage(baseZengkaRequest);
        }catch (Exception e){
            log.error("SsmCashController.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")
    public GenericResponse add(@RequestBody BaseZengkaRequest baseZengkaRequest, HttpSession session){
        GenericResponse<BaseZengka> genericResponse = new GenericResponse<>();
        if (StringUtils.isBlank(baseZengkaRequest.getRechargeTypeNum())){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"充值卡种项目类别");
            return genericResponse;
        }
        Long storeId = SessionHelp.getStoreId(session);
        if(storeId==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        String storeName = SessionHelp.getStoreName(session);
        String key = SessionHelp.getLoginAccount(session);
        baseZengkaRequest.setStoreId(storeId);
        baseZengkaRequest.setStoreName(storeName);
        int i = 0;
        try {
            i = ssmBaseZengkaService.add(baseZengkaRequest,key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.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("/update")
    public GenericResponse update(@RequestBody BaseZengkaRequest baseZengkaRequest, HttpSession session){
        GenericResponse<BaseZengka> genericResponse = new GenericResponse<>();
        if (StringUtils.isBlank(baseZengkaRequest.getRechargeTypeNum())){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"项目类别编码");
            return genericResponse;
        }
        Map<String,BaseZengkaIssue> hashSet = new HashMap<>();
        List<BaseZengkaIssue> baseZengkaIssues = baseZengkaRequest.getBaseZengkaIssues();
        for (BaseZengkaIssue baseZengkaIssue : baseZengkaIssues) {
            hashSet.put(baseZengkaIssue.getMemberCard(),baseZengkaIssue);
        }
        if(baseZengkaIssues.size() != hashSet.size()){
            genericResponse.setCodeAndMsg(ResponseCode.MEMBER_ID_REPAT);
            return genericResponse;
        }
        String key = SessionHelp.getLoginAccount(session);
        int i = 0;
        try {
            i = ssmBaseZengkaService.update(baseZengkaRequest,key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.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("/updateState")
    public GenericResponse updateState(@RequestBody BaseZengkaRequest baseZengkaRequest, HttpSession session){
        GenericResponse<BaseZengka> genericResponse = new GenericResponse<>();
        String key = SessionHelp.getLoginAccount(session);
        Long storeId = SessionHelp.getStoreId(session);
        if(storeId==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        int i = 0;
        try {
            i = ssmBaseZengkaService.updateState1(baseZengkaRequest,key,storeId);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.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("/export")
    public void export(@RequestBody BaseZengkaRequest baseZengkaRequest, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        baseZengkaRequest.setStoreId(SessionHelp.getStoreId(session));
        baseZengkaRequest.setStoreName(SessionHelp.getStoreName(session));
        BaseZengka baseZengka = new BaseZengka();
        try {
            BeanUtils.copyProperties(baseZengkaRequest, baseZengka);
            List<BaseZengka> list = ssmBaseZengkaService.select(baseZengka);
            List<ExcelZengka> excelZengkaList = new ArrayList<>();
            for (BaseZengka init : list) {
                ExcelZengka excelZengka = new ExcelZengka();
                BeanUtils.copyProperties(init, excelZengka);
                if (init.getState() == 0){
                    excelZengka.setState("新增");
                }else if (init.getState() == 1){
                    excelZengka.setState("送审中");
                }else if (init.getState() == 2){
                    excelZengka.setState("已回收");
                }else if (init.getState() == 3){
                    excelZengka.setState("已审核");
                }else if (init.getState() == 4){
                    excelZengka.setState("反审核中");
                }
                excelZengkaList.add(excelZengka);
            }
            String fileName = "zengkaInit";
            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/zengkaInit1.xlsx");
            excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
            List<BaseZengkaIssue> list1=ssmBaseZengkaService.seleZengkaIssueNew(list);
            for(int i=0;i<list1.size();i++){
                int num=i+1;
                List<BaseZengkaIssue> lists=new ArrayList<>();
                List<BaseZengkaIssue> list2= (List<BaseZengkaIssue>) list1.get(i);
                for(BaseZengkaIssue baseZengkaIssue:list2){
                    BaseZengkaIssue baseZengkaIssue1=new BaseZengkaIssue();
                    BeanUtils.copyProperties(baseZengkaIssue,baseZengkaIssue1);

                    lists.add(baseZengkaIssue1);
                }
                excelWriter.fill(new FillWrapper("excelZengkaList"+num, lists),fillConfig, writeSheet);
//                excelWriter.fill( lists,fillConfig, writeSheet);
            }
            excelWriter.fill(new FillWrapper("list", excelZengkaList), writeSheet);
//            excelWriter.fill(excelZengkaList, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmProjectTypeController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }


    @ApiOperation(value = "单据导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/exportachis")
    public void exportachis(@RequestBody BaseZengkaRequest baseZengkaRequest) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
//        courseListRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            List<BaseZengkaRequest> list = ssmBaseZengkaService.selectList(baseZengkaRequest);
            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/zengkaInit1.xlsx");
            List<ExcelZengka> excelBaseProjectTypeList = new ArrayList<>();
            List<BaseZengka> collect = list.stream().map(item -> {
                BaseZengka baseZengka = new BaseZengka();
                BeanUtils.copyProperties(item, baseZengka);
                return baseZengka;
            }).collect(Collectors.toList());
            List<BaseZengkaIssue> list1=ssmBaseZengkaService.seleZengkaIssueNew(collect);
            for (BaseZengkaRequest zengka : list) {

                for (BaseZengkaIssue excelZengka1 : list1) {
                    if(zengka.getId()==excelZengka1.getZengkaId() || zengka.getId().toString().equals(excelZengka1.getZengkaId().toString())){
                        ExcelZengka excelZengka = new ExcelZengka();
                        BeanUtils.copyProperties(zengka,excelZengka);
                        excelZengka.setMemberCard(excelZengka1.getMemberCard());
                        excelZengka.setMemberNum(excelZengka1.getMemberNum());
                        if (zengka.getState() == 0){
                            excelZengka.setState("新增");
                        }else if (zengka.getState() == 1){
                            excelZengka.setState("送审中");
                        }else if (zengka.getState() == 2){
                            excelZengka.setState("已回收");
                        }else if (zengka.getState() == 3){
                            excelZengka.setState("已审核");
                        }else if (zengka.getState() == 4){
                            excelZengka.setState("反审核中");
                        }
                        excelBaseProjectTypeList.add(excelZengka);
                    }
                }
            }

            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            excelWriter = EasyExcel.write(out).withTemplate(inputStream).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();
        }
    }
}
