package com.huiju.estateagents.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.entity.TaPersonBuilding;
import com.huiju.estateagents.entity.TaQrcode;
import com.huiju.estateagents.service.ITaQrcodeService;
import org.apache.commons.lang3.StringUtils;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 二维码管理表 前端控制器
 * </p>
 *
 * @author fxf
 * @since 2020-05-20
 */
@RestController
@RequestMapping("/api")
public class TaQrcodeController extends BaseController {

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

    @Autowired
    public ITaQrcodeService iTaQrcodeService;

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/admin/listQrCode", method = RequestMethod.GET)
    public ResponseBean listQrCodeByCondition(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                              @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                              String targetType, String targetName, Integer channelId, String buildingId,
                                              HttpServletRequest request) {
        logger.info("接收参数：targetType：{}，targetName：{}，channelId：{}，buildingId：{}",
                targetType, targetName, channelId, buildingId);
        ResponseBean responseBean = new ResponseBean();
        try {
            List<TaPersonBuilding> personBuildingList = getTaPersonBuildingListByUserId(request);
            responseBean = iTaQrcodeService.listQrCodeByCondition(pageNum, pageSize, targetType, targetName, channelId, buildingId, getUserId(request), getOrgId(request), personBuildingList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taQrcodeList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     *
     * @param taQrcode 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/taQrcode", method = RequestMethod.POST)
    public ResponseBean saveQrcode(@RequestBody TaQrcode taQrcode, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            // 校验参数
            if (StringUtils.isBlank(taQrcode.getTargetId()) || StringUtils.isBlank(taQrcode.getTargetType())) {
                responseBean.addError("参数错误");
                return responseBean;
            }
            responseBean = iTaQrcodeService.saveQrcode(taQrcode, getUserId(request), getOrgId(request));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("saveQrcode -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

    /**
     * 批量删除
     */
    @ResponseBody
    @RequestMapping(value = "/admin/qrCode/batchDelete", method = RequestMethod.DELETE)
    public ResponseBean batchDelete(@RequestBody List<TaQrcode> taQrcodeList) {
        ResponseBean responseBean = new ResponseBean();
        try {

            taQrcodeList.stream().forEach((record) -> {
                record.setStatus(CommConstant.STATUS_DELETE);
            });

            responseBean.addSuccess(iTaQrcodeService.updateBatchById(taQrcodeList));

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taQrcodeDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


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

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

    /**
     * 获取二维码统计信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/qrCode/getStatisticData", method = RequestMethod.GET)
    public ResponseBean getStatisticData(Integer qrCodeId, HttpServletRequest request) {
        logger.info("getStatisticData 接收参数：qrCodeId：{}", qrCodeId);
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaQrcodeService.getStatisticData(qrCodeId, getOrgId(request));
            logger.info("getStatisticData 返回结果：{}", JSONObject.toJSONString(responseBean));
        } catch (Exception e) {
            logger.error("getStatisticData 异常：", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 获取二维码统计信息记录
     *
     * @param pageNum
     * @param pageSize
     * @param qrCodeId
     * @param type     1：访问人数，2：访问次数，3：新增注册用户数
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/qrCode/getStatisticRecord", method = RequestMethod.GET)
    public ResponseBean getStatisticRecord(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                           Integer qrCodeId, Integer type, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaQrcodeService.getStatisticRecord(type, pageNum, pageSize, qrCodeId, getOrgId(request));
        } catch (Exception e) {
            logger.error("getStatisticRecord 异常：", e);
            responseBean.addError("fail");
        }
        return responseBean;
    }

    @RequestMapping(value = "/admin/qrCode/getStatisticRecordExport", method = RequestMethod.GET)
    public void getStatisticRecordExport(@RequestParam(value = "qrCodeId") Integer qrCodeId,
                                         @RequestParam(value = "type") Integer type, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            iTaQrcodeService.getStatisticRecordExport(type, qrCodeId, getOrgId(request), response);
        } catch (Exception e) {
            logger.error("getStatisticRecordExport 异常：", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap();
            map.put("code", ResponseBean.ERROR_UNAVAILABLE);
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

}


