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.alibaba.fastjson.JSONArray;
import com.ssm.manage.response.GenericResponse;
import com.ssm.core.util.EasyExcelUtil;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.manage.entity.BaseGrouponList;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.excelEntity.ExcelGroupPurchaseList;
import com.ssm.manage.query.BaseGrouponCardRequest;
import com.ssm.manage.query.BaseGrouponListRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmBaseGrouponListService;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Api(value="团购卡名单controller",tags={"团购卡名单controller相关接口"})
@RestController
@RequestMapping("/demay/ssm/baseGrouponList")
@Slf4j
public class SsmBaseGrouponListController {

    @Autowired
    private SsmBaseGrouponListService ssmBaseGrouponListService;

    @ApiOperation(value = "查询团购人名单(传团购单据Id)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/select")
    public GenericResponse select(@RequestBody BaseGrouponListRequest baseGrouponListRequest, HttpSession session){
        GenericResponse<List<BaseGrouponList>> genericResponse = new GenericResponse<>();
        BaseGrouponList baseGrouponList = new BaseGrouponList();
        baseGrouponList.setGrouponCardId(baseGrouponListRequest.getGrouponCardId());
        List<BaseGrouponList> select = ssmBaseGrouponListService.select(baseGrouponList);
        genericResponse.setData(select);
        return genericResponse;
    }

    @ApiOperation(value = "添加团购人名单",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/add")
    public GenericResponse add(@RequestBody BaseGrouponCardRequest baseGrouponCardRequest, HttpSession session){
        GenericResponse<BaseGrouponList> genericResponse = new GenericResponse<>();
        int count = 0;
        if (null == baseGrouponCardRequest.getId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"第"+count+"条团购人信息团购单Id为空");
            return genericResponse;
        }
        List<BaseGrouponList> baseGrouponLists = JSONArray.parseArray(baseGrouponCardRequest.getBaseGrouponLists(),BaseGrouponList.class);
        for (BaseGrouponList baseGrouponListRequest :baseGrouponLists ) {
            count++;
            if(null == baseGrouponListRequest.getMobilePhone()){
                genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"第"+count+"条团购人手机号码为空");
                return genericResponse;
            }
            if(null == baseGrouponListRequest.getMemberName()){
                genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"第"+count+"条团购人名称为空");
                return genericResponse;
            }
//            if(null == baseGrouponListRequest.getCashPassword()){
//                genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"第"+count+"条团购人支付密码为空");
//                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);
        baseGrouponCardRequest.setStoreId(storeId);
        baseGrouponCardRequest.setStoreName(storeName);
        int i = 0;
        try {
            i = ssmBaseGrouponListService.add(baseGrouponCardRequest,baseGrouponCardRequest.getId());
        }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 BaseGrouponCardRequest baseGrouponCardRequest, HttpSession session){
        GenericResponse<BaseGrouponList> genericResponse = new GenericResponse<>();
        int count = 0;
        if (null == baseGrouponCardRequest.getId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"第"+count+"条团购人信息团购单Id为空");
            return genericResponse;
        }
        List<BaseGrouponList> baseGrouponLists = JSONArray.parseArray(baseGrouponCardRequest.getBaseGrouponLists(),BaseGrouponList.class);
        for (BaseGrouponList baseGrouponListRequest :baseGrouponLists ) {
            count++;

            if(null == baseGrouponListRequest.getMobilePhone()){
                genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"第"+count+"条团购人手机号码为空");
                return genericResponse;
            }
            if(null == baseGrouponListRequest.getMemberName()){
                genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"第"+count+"条团购人名称为空");
                return genericResponse;
            }
//            if(null == baseGrouponListRequest.getCashPassword()){
//                genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"第"+count+"条团购人支付密码为空");
//                return genericResponse;
//            }
        }


        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String key = SessionHelp.getLoginAccount(session);
        baseGrouponCardRequest.setStoreId(storeId);
        baseGrouponCardRequest.setStoreName(storeName);
        int i = 0;
        try {
            i = ssmBaseGrouponListService.update(baseGrouponCardRequest,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("/download")
    public void download(HttpSession session, HttpServletResponse response) {

        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        try {
            String fileName = "recType";
            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();
            //ClassPathResource classPathResource = new ClassPathResource("static/live_room_data3.xls");
            //InputStream inputStream = classPathResource.getInputStream();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/groupPurchaseList.xlsx");

            List<ExcelGroupPurchaseList> list = new ArrayList<>();
            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("SsmRechargeTypeController.download:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

    @ApiOperation(value = "门店充值类别批量导入  门店端-充值类别列表-门店充值类别批量导入", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/import")
    public GenericResponse recTypeImport(MultipartFile multipartFile,Long grouponCardId, HttpSession session) {
        GenericResponse genericResponse = new 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);
        List<ExcelGroupPurchaseList> list = null;
        if(null ==grouponCardId){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"团购单Id不能为空");
            return genericResponse;
        }
        try {
            list = EasyExcelUtil.simpleWrite(multipartFile, ExcelGroupPurchaseList.class);
        } catch (SmsException e) {
            log.error("SsmRechargeTypeController.recTypeImport:",e);
            return genericResponse;
        }

        List<BaseGrouponList> rechargeTypeList = new ArrayList<>();
        for (ExcelGroupPurchaseList excelRechargeType : list) {
            BaseGrouponList rechargeType = new BaseGrouponList();
            BeanUtils.copyProperties(excelRechargeType, rechargeType);
            if(null == rechargeType.getMobilePhone()){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,"有列手机号码存在空");
                return genericResponse;
            }
            if(null == rechargeType.getMemberName()){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,"有列团购人名称存在空");
                return genericResponse;
            }
            if(excelRechargeType.getMobilePhone().trim().length()!=11){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,excelRechargeType.getMobilePhone()+"手机号码格式错误");
                return genericResponse;
            }
            rechargeTypeList.add(rechargeType);
        }
        List<BaseGrouponList> unusualList = new ArrayList<>();
        try {
            unusualList = ssmBaseGrouponListService.insertBatch(rechargeTypeList,grouponCardId);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmRechargeTypeController.recTypeImport:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

        if (!unusualList.isEmpty()) {
            genericResponse.setRows(unusualList);
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;

    }
}
