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.query.StoreTurnTreatmentQuery;
import com.ssm.manage.query.StoreTurnTreatmentRequesttow;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmCashService;
import com.ssm.manage.service.SsmStoreTurnTreatmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.RequestMethod;
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.List;

@Api(value="会员疗程卡转店controller",tags={"会员疗程卡转店相关接口"})
@RestController
@RequestMapping("/demay/ssm/storeTurnTreatment")
@Slf4j
public class SsmStoreTurnTreatmentController {

    @Autowired
    private SsmStoreTurnTreatmentService ssmStoreTurnTreatmentService;

    @Autowired
    private SsmCashService ssmCashService;

    @ApiOperation(value = "添加门店员工转店申请查询", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public PageResponse page(@RequestBody StoreTurnTreatmentQuery storeConversion, HttpSession session) {
        PageResponse<StoreTurnTreatmentQuery> genericResponse = new PageResponse();
        PageInfo<StoreTurnTreatmentQuery> pageInfo = new PageInfo<>();
        try {
            pageInfo = ssmStoreTurnTreatmentService.selectPage(storeConversion);
        }catch (SmsException e){
            log.error("SsmStoreTurnTreatmentController page",e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmStoreConversionController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setPageInfo(pageInfo);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    @ApiOperation(value = "添加门店员工转店申请", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public GenericResponse add(@RequestBody List<StoreTurnTreatmentRequesttow> storeConversion, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        for (StoreTurnTreatmentRequesttow storeTurnTreatmentRequesttow : storeConversion) {
            if(storeTurnTreatmentRequesttow.getStoresId()==null){
                storeTurnTreatmentRequesttow.setStoresId(SessionHelp.getStoreId(session));
                storeTurnTreatmentRequesttow.setStoresName(SessionHelp.getStoreName(session));
                storeTurnTreatmentRequesttow.setStoresNum(SessionHelp.getStoreNum(session));
            }
        }
        String phone = SessionHelp.getLoginAccount(session);
        int i = 0;
        try {
            i = ssmStoreTurnTreatmentService.add(storeConversion,phone);
        }catch (SmsException e){
            log.error("SsmStoreTurnTreatmentController add",e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmStoreConversionController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    @ApiOperation(value = "取消门店员工转店申请", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public GenericResponse delete(@RequestBody List<StoreTurnTreatmentRequesttow> storeConversion, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        for (StoreTurnTreatmentRequesttow storeTurnTreatmentRequesttow : storeConversion) {
            if(storeTurnTreatmentRequesttow.getStoresId()==null){
                storeTurnTreatmentRequesttow.setStoresId(SessionHelp.getStoreId(session));
                storeTurnTreatmentRequesttow.setStoresName(SessionHelp.getStoreName(session));
                storeTurnTreatmentRequesttow.setStoresNum(SessionHelp.getStoreNum(session));
            }
        }
        String phone = SessionHelp.getLoginAccount(session);
        int i = 0;
        try {
            i = ssmStoreTurnTreatmentService.add(storeConversion,phone);
        }catch (SmsException e){
            log.error("SsmStoreTurnTreatmentController add",e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmStoreConversionController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    @ApiOperation(value = "添加门店员工转店申请（状态修改）", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping(value = "/updateStatu", method = RequestMethod.POST)
    public GenericResponse updateStatu(@RequestBody StoreTurnTreatmentQuery storeConversion, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        String phone = SessionHelp.getLoginAccount(session);
        int i = 0;
        try {
            i = ssmStoreTurnTreatmentService.updateStatu(storeConversion,phone);
        }catch (SmsException e){
            log.error("SsmStoreTurnTreatmentController update",e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmStoreConversionController.update:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    @ApiOperation(value = "单据导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/exportachis")
    public void exportachis(@RequestBody StoreTurnTreatmentQuery storeConversion) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是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/storeTurnTreatment.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<StoreTurnTreatmentQuery> list = ssmStoreTurnTreatmentService.exportachis(storeConversion);
//            List<Long> longList = list.stream().filter(item -> item.getStatu() == 2).map(StoreTurnTreatmentQuery::getCourseAccountId).collect(Collectors.toList());
//            List<Long> distinctList = new ArrayList<>(new HashSet<>(longList));
//            //查询近半年的消费
//            Date date = new Date();
            if(list!=null && list.size()>0) {
//            salesmen = ssmSalesmanService.selectList(salesman);
                //所有门店
                for (StoreTurnTreatmentQuery executives : list) {
                    if(executives.getStatu()==0){
                        executives.setStateString("新增");
                    }
                    if(executives.getStatu()==1){
                        executives.setStateString("送审");
                    }
                    if(executives.getStatu()==2){
                        executives.setStateString("已审核");
                    }
                    if(executives.getStatu()==3){
                        executives.setStateString("反审核");
                    }
                }
            }
            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(list, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmProjectTypeController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

}
