package com.huiju.estateagents.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.entity.TaShareRecord;
import com.huiju.estateagents.excel.ShareRecordFailExport;
import com.huiju.estateagents.excel.ShareRecordSuccessExport;
import com.huiju.estateagents.excel.handler.CustomCellWriteHandler;
import com.huiju.estateagents.po.TaShareRecordPO;
import com.huiju.estateagents.service.ITaPersonService;
import com.huiju.estateagents.service.ITaShareRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
    * 拼团记录  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-10-18
 */
@RestController
@RequestMapping("/api")
public class TaShareRecordController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaShareRecordController.class);

    @Autowired
    public ITaShareRecordService iTaShareRecordService;
    
    @Autowired
    private ITaPersonService taPersonService;
    
    /**
     * 分页拼团成功列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taShareSuccessRecord",method= RequestMethod.GET)
    public ResponseBean taShareSuccessRecordList(@RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNum,
                                          @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                          @RequestParam(value ="phone",required = false) String phone,
                                          @RequestParam(value ="groupStatus",required = false) Integer groupStatus,
                                          @RequestParam(value ="groupActivityId",required = false) Integer groupActivityId,
                                          HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            IPage<TaShareRecord> result = iTaShareRecordService.getSuccessList(pageNum, pageSize, phone, groupStatus, groupActivityId, getOrgId(request));
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareRecordList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 分页拼团进行中和失败列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taShareFailAndProcessingRecord",method= RequestMethod.GET)
    public ResponseBean taShareFailAndProcessingRecordList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                          @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                          @RequestParam(value ="phone",required = false) String phone,
                                          @RequestParam(value ="groupStatus",required = false) Integer groupStatus,
                                          @RequestParam(value ="groupActivityId",required = false) Integer groupActivityId,
                                          HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            IPage<TaShareRecordPO> result = iTaShareRecordService.getFailAndProcessingList(pageNum, pageSize, phone, groupStatus, groupActivityId, getOrgId(request));
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareRecordList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 保存拼团中的对象
     * @param taShareRecord 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taShareRecord",method= RequestMethod.POST)
    public ResponseBean taShareRecordAdd(@RequestBody TaShareRecord taShareRecord, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();

        try {
            responseBean = iTaShareRecordService.validateRule(taShareRecord);
            if (responseBean.getCode() != 0){
                return responseBean;
            }
            //0拼团成功 1拼团中 2拼团失败
            taShareRecord.setStatus(1);
            //0未核销 1已核销
            taShareRecord.setVerificationStatus(0);
            taShareRecord.setOrgId(getOrgId(request));
            if (iTaShareRecordService.save(taShareRecord)){
                responseBean.addSuccess(taShareRecord);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareRecordAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/taShareRecord/{id}", method= RequestMethod.DELETE)
    public ResponseBean taShareRecordDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iTaShareRecordService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareRecordDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taShareRecord 实体对象
     * @return
     */
    @RequestMapping(value="/taShareRecord/{id}",method= RequestMethod.PUT)
    public ResponseBean taShareRecordUpdate(@PathVariable Integer id,
                                        @RequestBody TaShareRecord taShareRecord){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaShareRecordService.updateById(taShareRecord)){
                responseBean.addSuccess(taShareRecord);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareRecordUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/taShareRecord/{id}",method= RequestMethod.GET)
    public ResponseBean taShareRecordGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaShareRecordService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareRecordDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    @RequestMapping(value="/admin/taShareRecord/verificate",method= RequestMethod.PUT)
    public ResponseBean taShareVerificateRecord(@RequestParam(value = "groupActivityId", required = false) Integer groupActivityId,
                                                @RequestParam(value = "verifyCode", required = false) String verificateCode,
                                                @RequestParam(value = "recordId", required = false) String recordId){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaShareRecordService.verifyCode(groupActivityId, verificateCode, recordId);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareVerificateRecord -=- {}",e.toString());
            responseBean.addError("核销失败");
        }
        return responseBean;
    }

    @GetMapping("/admin/taShareRecord/export")
    public void gethelpRecordExport(HttpServletRequest request,
                                    HttpServletResponse response,
                                    @RequestParam(value = "recordId", required = false) Integer recordId,
                                    @RequestParam(value = "groupStatus", required = false) Integer groupStatus,
                                    @RequestParam(value = "groupActivityId", required = false) Integer groupActivityId) throws IOException {

        ExcelWriter excelWriter = null;
        try {
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=拼团活动发起人.xlsx");

            if (groupStatus == 0) {
                Integer orgId = getOrgId(request);

                Integer pageCode = 0;
                Integer pageSize = 100;
                // 总页数
                Integer pageCount = 0;

                /**
                 * 拼团活动参与者
                 */
                // 设置读取的class
                excelWriter = EasyExcel.write(response.getOutputStream(), ShareRecordSuccessExport.class).registerWriteHandler(new CustomCellWriteHandler()).build();
                // 设置 sheet, 同一个sheet只需要设置一次
                WriteSheet writeSheet = EasyExcel.writerSheet("拼团成功").build();
                Integer count = iTaShareRecordService.getShareRecord(recordId, groupStatus);
                pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
                List<ShareRecordSuccessExport> publicList = null;
                do {
                    publicList = iTaShareRecordService.getShareRecordSuccessExportList(pageCode * pageSize, pageSize, recordId, groupStatus, groupActivityId);
                    excelWriter.write(publicList, writeSheet);

                    pageCode++;
                } while (pageCode <= pageCount);
            } else {
                Integer orgId = getOrgId(request);

                Integer pageCode = 0;
                Integer pageSize = 100;
                // 总页数
                Integer pageCount = 0;

                /**
                 * 拼团活动参与者
                 */
                // 设置读取的class
                excelWriter = EasyExcel.write(response.getOutputStream(), ShareRecordFailExport.class).registerWriteHandler(new CustomCellWriteHandler()).build();
                // 设置 sheet, 同一个sheet只需要设置一次
                WriteSheet writeSheet = EasyExcel.writerSheet("拼团成功").build();
                Integer count = iTaShareRecordService.getShareRecord(recordId, groupStatus);
                pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
                List<ShareRecordFailExport> publicList = null;
                do {
                    publicList = iTaShareRecordService.getShareRecordFailExportList(pageCode * pageSize, pageSize, recordId, groupStatus, groupActivityId);
                    excelWriter.write(publicList, writeSheet);

                    pageCode++;
                } while (pageCode <= pageCount);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // finish 会帮忙关闭流
            excelWriter.finish();
        }
    }
    /**
     * 微信端分页获取团长记录
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/wx/taShareRecord",method= RequestMethod.GET)
    public ResponseBean wxShareRecordList(@RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                                 @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return responseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        try {
            responseBean = iTaShareRecordService.getShareRecordList(pageNumber, pageSize, orgId, person);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareRecordList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 保存拼团中的对象
     * @param taShareRecord 实体对象
     * @return
     */
    @RequestMapping(value="/wx/taShareRecord",method= RequestMethod.POST)
    public ResponseBean wxShareRecordAdd(@RequestBody TaShareRecord taShareRecord, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return responseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        try {
            responseBean = iTaShareRecordService.saveShareRecord(taShareRecord,orgId,person);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareRecordAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

}
