package com.yunzhi.marketing.controller;

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.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.entity.HelpActivity;
import com.yunzhi.marketing.entity.HelpInitiateRecord;
import com.yunzhi.marketing.entity.HelpRecord;
import com.yunzhi.marketing.entity.TaPerson;
import com.yunzhi.marketing.service.IHelpActivityService;
import com.yunzhi.marketing.service.IHelpInitiateRecordService;
import com.yunzhi.marketing.service.IHelpRecordService;
import com.yunzhi.marketing.service.ITaPersonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
    * 助力活动发起人员记录  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-10-17
 */
@RestController
@RequestMapping("/api")
public class HelpInitiateRecordController extends BaseController {

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

    @Autowired
    public IHelpInitiateRecordService taHelpInitiateRecordService;
    
    @Autowired
    private ITaPersonService taPersonService;
    
    @Autowired
    public IHelpRecordService helpRecordService;
    
    @Autowired
    public IHelpActivityService taHelpActivityService;
    
    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/helpInitiateRecord",method= RequestMethod.GET)
    public ResponseBean helpInitiateRecordList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                               @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<HelpInitiateRecord> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<HelpInitiateRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_date");

            IPage<HelpInitiateRecord> result = taHelpInitiateRecordService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("helpInitiateRecordList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param helpInitiateRecord 实体对象
     * @return
     */
    @RequestMapping(value="/helpInitiateRecord",method= RequestMethod.POST)
    public ResponseBean helpInitiateRecordAdd(@RequestBody HelpInitiateRecord helpInitiateRecord){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (taHelpInitiateRecordService.save(helpInitiateRecord)){
                responseBean.addSuccess(helpInitiateRecord);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("helpInitiateRecordAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

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

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/helpInitiateRecord/{id}",method= RequestMethod.GET)
    public ResponseBean helpInitiateRecordGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(taHelpInitiateRecordService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("helpInitiateRecordDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 微信端分页查询我发起的助力活动
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/wx/helpInitiateRecord",method= RequestMethod.GET)
    public ResponseBean wxhelpInitiateRecordList(@RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                                 @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest request){
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        ResponseBean responseBean = new ResponseBean();
        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 = taHelpInitiateRecordService.getInitiateRecord(pageNumber, pageSize,orgId,person.getPersonId());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("helpInitiateRecordList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    
    /**
     * 微信端保存发起活动对象
     * @param helpInitiateRecord 实体对象
     * @return
     */
    @RequestMapping(value="/wx/helpInitiateRecord",method= RequestMethod.POST)
    public ResponseBean wxHelpInitiateRecordAdd(@RequestBody HelpInitiateRecord helpInitiateRecord,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);
        Map<String,Object> map = new HashMap<>();
        HelpActivity helpActivity = taHelpActivityService.getById(helpInitiateRecord.getHelpActivityId());
        if(helpActivity.getActivityStatus().equals(CommConstant.ACTIVITY_STATUS_FINISH)){
            return ResponseBean.error("活动已结束", ResponseBean.ERROR_UNAVAILABLE);
        }
        if(helpActivity.getStatus().equals(CommConstant.STATUS_UNACCALIMED)){
            return ResponseBean.error("活动已失效", ResponseBean.ERROR_UNAVAILABLE);
        }
        try {
 
            //查看是否发起过助力
            QueryWrapper<HelpInitiateRecord> helpInitiateRecordQueryWrapper = new QueryWrapper<>();
            helpInitiateRecordQueryWrapper.eq("help_activity_id",helpInitiateRecord.getHelpActivityId());
            helpInitiateRecordQueryWrapper.eq("org_id",orgId);
            helpInitiateRecordQueryWrapper.eq("person_id",person.getPersonId());
            helpInitiateRecordQueryWrapper.ne("status",-1);
            HelpInitiateRecord recordServiceOne = taHelpInitiateRecordService.getOne(helpInitiateRecordQueryWrapper);
            if (null != recordServiceOne){
                map.put("helpInitiateRecord",recordServiceOne);
                QueryWrapper<HelpRecord> helpRecordQueryWrapper = new QueryWrapper<>();
                helpRecordQueryWrapper.eq("help_activity_id",helpInitiateRecord.getHelpActivityId());
                helpRecordQueryWrapper.eq("org_id",orgId);
                helpRecordQueryWrapper.eq("help_record_initiate_id",recordServiceOne.getHelpRecordInitiateId());
                List<HelpRecord> list = helpRecordService.list(helpRecordQueryWrapper);
                map.put("helpRecordList",list);
                responseBean.addSuccess(map);
                return responseBean;
            }
 
            helpInitiateRecord.setPersonId(person.getPersonId());
            helpInitiateRecord.setVerificationStatus(CommConstant.STATUS_UNACCALIMED);
            helpInitiateRecord.setCreateDate(LocalDateTime.now());
            helpInitiateRecord.setOrgId(orgId);
            helpInitiateRecord.setStatus(1);
            if (taHelpInitiateRecordService.save(helpInitiateRecord)){
                map.put("helpInitiateRecord",helpInitiateRecord);
                map.put("helpRecordList",new ArrayList<>());
                responseBean.addSuccess(map);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("helpInitiateRecordAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
