package com.huiju.estateagents.controller;

import ch.qos.logback.core.status.StatusUtil;
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.common.DateUtils;
import com.huiju.estateagents.common.JWTUtils;
import com.huiju.estateagents.entity.TaCheckin;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.service.ITaCheckinService;
import com.huiju.estateagents.service.ITaPersonService;
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.time.LocalDateTime;
import java.util.List;


/**
 * <p>
    *   前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-07-24
 */
@RestController
@RequestMapping("/api")
public class TaCheckinController extends BaseController {

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

    @Autowired
    public ITaCheckinService iTaCheckinService;
    @Autowired
    public ITaPersonService iTaPersonService;


    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/taCheckin/activity/{activity}",method= RequestMethod.GET)
    public ResponseBean taCheckinList(@PathVariable String activity,
                                      @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                      @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                      @RequestParam(value ="today",defaultValue = "false") Boolean today,
                                      @RequestParam(value = "newRecord", defaultValue = "false") Boolean newRecord,
                                      HttpServletResponse response){

        // 此接口允許跨域
        response.setHeader("Access-Control-Allow-Origin", "*");

        try {
            Integer status = !newRecord ? 1 : 0;
            LocalDateTime dayBegin = null;
            if (today) {
                String theDay = DateUtils.today();
                dayBegin = DateUtils.day2LocalDateime(theDay);
            }

            //使用分页插件
		    IPage<TaCheckin> pg = new Page<>(pageNum, pageSize);
            IPage<TaCheckin> result = iTaCheckinService.getCheckinCustomerList(pg,activity, status, dayBegin);

            if (newRecord) {
                for (int i = 0;i<result.getRecords().size();i++){
                    result.getRecords().get(i).setStatus(1);
                }

                if (result.getRecords().size() > 0) {
                    iTaCheckinService.updateBatchById(result.getRecords());
                }
            }

            return ResponseBean.success(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCheckinList -=- {}",e.toString());
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 保存对象
     * @param activity 实体对象
     * @return
     */
    @RequestMapping(value="/wx/taCheckin/activity/{activity}",method= RequestMethod.POST)
    public ResponseBean taCheckinAdd(@PathVariable String activity, HttpServletRequest request){
        String openid = getOpenId(request);
        List<TaPerson> taPersons = iTaPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);


        try {
            if(iTaCheckinService.isCustomerChecked(activity,person.getPersonId())>0){
                return ResponseBean.success("您已签到过此活动");
            }else {
                TaCheckin taCheckin = new TaCheckin();
                taCheckin.setStatus(0);
                taCheckin.setPersonId(person.getPersonId());
                taCheckin.setActivity(activity);
                taCheckin.setName(person.getNickname());
                taCheckin.setAvatar(person.getAvatarurl());
                taCheckin.setCheckinTime(LocalDateTime.now());
                if (iTaCheckinService.save(taCheckin)){
                    return ResponseBean.success(taCheckin);
                }else {
                    return ResponseBean.error("保存失败",ResponseBean.ERROR_UNAVAILABLE);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCheckinAdd -=- {}",e.toString());
            return ResponseBean.error("保存失败"+e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    @GetMapping("/wx/taCheckin/activity/{activityId}/isChecked")
    public ResponseBean isChecked(@PathVariable String activityId, HttpServletRequest request) {
        String openid = getOpenId(request);
        List<TaPerson> taPersons = iTaPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);

        boolean checked = iTaCheckinService.isCustomerChecked(activityId, person.getPersonId()) > 0;
        return ResponseBean.success(checked);
    }

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

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

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