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.metadata.IPage;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.entity.TaShareChildRecord;
import com.huiju.estateagents.excel.ShareChildRecordExport;
import com.huiju.estateagents.excel.handler.CustomCellWriteHandler;
import com.huiju.estateagents.service.ITaPersonService;
import com.huiju.estateagents.service.ITaShareActivityService;
import com.huiju.estateagents.service.ITaShareChildRecordService;
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 TaShareChildRecordController extends BaseController {

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

    @Autowired
    private ITaShareChildRecordService iTaShareChildRecordService;
    
    @Autowired
    private ITaShareActivityService iTaShareActivityService;
    
    @Autowired
    private ITaPersonService taPersonService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taShareChildRecord",method= RequestMethod.GET)
    public ResponseBean taShareChildRecordList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                               @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                               @RequestParam(value ="groupActivityId",required = false) Integer groupActivityId,
                                               @RequestParam(value ="groupStatus",required = false) Integer groupStatus,
                                               @RequestParam(value ="recordId",required = false) Integer recordId,
                                               HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            IPage<TaShareChildRecord> result  = iTaShareChildRecordService.getList(pageNum, pageSize, groupActivityId, groupStatus, recordId, getOrgId(request));
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareChildRecordList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param taShareChildRecord 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taShareChildRecord",method= RequestMethod.POST)
    public ResponseBean taShareChildRecordAdd(@RequestBody TaShareChildRecord taShareChildRecord, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaShareChildRecordService.validateRule(taShareChildRecord);
            if (responseBean.getCode() != 0){
                return responseBean;
            }
            //0拼团成功 1拼团中 2拼团失败
            taShareChildRecord.setStatus(1);
            //0未核销 1已核销
            taShareChildRecord.setVerificationStatus(0);
            taShareChildRecord.setOrgId(getOrgId(request));
            if (iTaShareChildRecordService.save(taShareChildRecord)){
                responseBean.addSuccess(taShareChildRecord);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareChildRecordAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

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

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

    @GetMapping("/admin/taShareChildRecord/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");

            Integer orgId = getOrgId(request);

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

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

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

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            // finish 会帮忙关闭流
            excelWriter.finish();
        }
    }


    /**
     * 微信端成为团员
     * @param taShareChildRecord 实体对象
     * @return
     */
    @RequestMapping(value="/wx/taShareChildRecord",method= RequestMethod.POST)
    public ResponseBean wxShareChildRecordAdd(@RequestBody TaShareChildRecord taShareChildRecord, 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 = iTaShareChildRecordService.addChildRecord(taShareChildRecord,orgId,person);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareChildRecordAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
