package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.bweb.config.SysConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.QRCodeGenerator;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.MemberValidateUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.HighAgent;
import com.hai.entity.SecUser;
import com.hai.model.HighAgentModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighAgentService;
import com.hai.service.SecUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: 袁野
 * @Description:
 * @Date: 2021/3/25 17:19
 */
@Controller
@RequestMapping(value = "/highAgent")
@Api(value = "代理商接口")
public class HighAgentController {

    private static Logger log = LoggerFactory.getLogger(HighMerchantStoreController.class);

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighAgentService highAgentService;

    @Resource
    private SecUserService secUserService;

    @RequestMapping(value = "/insertChildAgent", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增子级代理商")
    public ResponseData insertChildAgent(@RequestBody JSONObject body) {
        try {
            //发布人员
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                log.error("HighAgentController -> insertAgent() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            if (body == null ||
                    StringUtils.isBlank(body.getString("agentName")) ||
                    StringUtils.isBlank(body.getString("agentPhone")) ||
                    StringUtils.isBlank(body.getString("agentAddress"))
            ) {
                log.error("HighAgentController -> insertAgent() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 校验账户手机号
            if (!MemberValidateUtil.validatePhone(body.getString("agentPhone"))) {
                log.error("BsStudentController --> updateMerchant() error!", "请输入正确的手机号");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.PHONE_NUM_IS_ERROR, "");
            }

            // 校验账号用户名是否存在
            if (secUserService.findByLoginName(body.getString("agentPhone")) != null) {
                log.error("HighAgentController --> insertAgent() error!", "手机号已存在，请更换！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_LOGIN_NAME_IS_EXIST_ERROR, "");
            }

            HighAgent agent = new HighAgent();
            agent.setParentId(userInfoModel.getHighAgent().getId());
            agent.setParentName(userInfoModel.getHighAgent().getAgentName());
            agent.setType(userInfoModel.getHighAgent().getType());
            agent.setAgentName(body.getString("agentName"));
            agent.setAgentAddress(body.getString("agentAddress"));
            agent.setAgentPhone(body.getString("agentPhone"));
            agent.setAgentKey(String.valueOf(System.currentTimeMillis()));
            agent.setAgentUser(body.getString("agentName"));

            agent.setStatus(1); // 状态：0：不可用，1：可用
            agent.setCreateTime(new Date());
            agent.setOperatorId(userInfoModel.getSecUser().getId());
            agent.setOperatorName(userInfoModel.getSecUser().getUserName());
            highAgentService.insertChildAgent(agent);
            return ResponseMsgUtil.success("新增成功");

        } catch (Exception e) {
            log.error("HighAgentController --> insertChildAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/changeAgentStatus", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "变更代理商状态")
    public ResponseData changeAgentStatus(@RequestParam(value =  "agentId" , required = true) Long agentId,
                                          @RequestParam(value =  "status" , required = true) Integer status) {
        try {
            HighAgent highAgent = highAgentService.findByAgentMsgId(agentId);
            if (highAgent == null) {
                log.error("HighAgentController --> changeAgentStatus() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_USER_ERROR, "");
            }
            highAgent.setStatus(status);
            highAgentService.updateAgentDetail(highAgent);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighAgentController --> changeAgentStatus() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getChildAgentList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询子级代理商列表")
    public ResponseData getChildAgentList(@RequestParam(value =  "agentId" , required = true) Long agentId,
                                          @RequestParam(value =  "agentPhone" , required = false) String agentPhone,
                                          @RequestParam(value =  "agentName" , required = false) String agentName,
                                          @RequestParam(value =  "status" , required = false) Integer status,
                                          @RequestParam(value =  "pageNum" , required = true) Integer pageNum,
                                          @RequestParam(value =  "pageSize" , required = true) Integer pageSize) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("parentAgentId", agentId);
            param.put("agentPhone", agentPhone);
            param.put("agentName", agentName);
            param.put("status", status);

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highAgentService.getListAgentMsg(param)));

        } catch (Exception e) {
            log.error("HighAgentController --> changeAgentStatus() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/insertAgent", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增代理商")
    public ResponseData insertAgent(@RequestBody HighAgentModel highAgentModel, HttpServletRequest request) {
        try {
            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
//            if (userInfoModel.getBsCompany() == null) {
//                log.error("HighAgentController -> insertAgent() error!","该主角色没有权限");
//                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
//            }

            if (StringUtils.isBlank(highAgentModel.getAgentName())
                    || StringUtils.isBlank(highAgentModel.getAgentAddress())
                    || StringUtils.isBlank(highAgentModel.getAgentUser())
                    || StringUtils.isBlank(highAgentModel.getAgentPhone())
                    || StringUtils.isBlank(highAgentModel.getSecUser().getPassword())
                    || StringUtils.isBlank(highAgentModel.getSecUser().getLoginName())
            ) {
                log.error("HighAgentController -> insertAgent() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 校验账号用户名是否存在
            if (secUserService.findByLoginName(highAgentModel.getSecUser().getLoginName()) != null) {
                log.error("HighAgentController --> insertAgent() error!", "用户名已存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_LOGIN_NAME_IS_EXIST_ERROR, "");
            }

            if (highAgentService.findByAgentName(highAgentModel.getAgentName())) {
                log.error("HighAgentController --> insertAgent() error!", "代理商名称已存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.AGENT_NAME, "");
            }

            highAgentModel.setAgentKey(String.valueOf(System.currentTimeMillis()));
            highAgentModel.setStatus(1); // 状态：0：不可用，1：可用
            highAgentModel.setCreateTime(new Date());
            highAgentModel.setOperatorId(userInfoModel.getSecUser().getId());
            highAgentModel.setOperatorName(userInfoModel.getSecUser().getUserName());
            highAgentService.insertAgentMsg(highAgentModel);

            return ResponseMsgUtil.success("新增成功");

        } catch (Exception e) {
            log.error("HighAgentController --> insertAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updateAgent", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改代理商")
    public ResponseData updateAgent(@RequestBody HighAgentModel highAgentModel, HttpServletRequest request) {
        try {

            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
//            if (userInfoModel.getBsCompany() == null) {
//                log.error("HighAgentController -> insertAgent() error!","该主角色没有权限");
//                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
//            }

            if (highAgentModel.getId() == null
                    || StringUtils.isBlank(highAgentModel.getAgentName())
                    || StringUtils.isBlank(highAgentModel.getAgentAddress())
                    || StringUtils.isBlank(highAgentModel.getAgentUser())
                    || StringUtils.isBlank(highAgentModel.getAgentPhone())
                    || StringUtils.isBlank(highAgentModel.getSecUser().getPassword())
                    || StringUtils.isBlank(highAgentModel.getSecUser().getLoginName())
            ) {
                log.error("HighAgentController -> insertAgent() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            HighAgent highAgent = highAgentService.findByAgentMsgId(highAgentModel.getId());

            // 校验账号用户名是否存在
            if (secUserService.findByLoginName(highAgentModel.getSecUser().getLoginName()) != null && !highAgentModel.getId().equals(highAgent.getId())) {
                log.error("HighAgentController --> insertAgent() error!", "用户名已存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_LOGIN_NAME_IS_EXIST_ERROR, "");
            }

            if (highAgentService.findByAgentName(highAgentModel.getAgentName()) && !highAgentModel.getId().equals(highAgent.getId())) {
                log.error("HighAgentController --> insertAgent() error!", "代理商名称已存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.AGENT_NAME, "");
            }

            highAgentModel.setAgentKey(highAgent.getAgentKey());
            highAgentModel.setStatus(1); // 状态：0：不可用，1：可用
            highAgentModel.setCreateTime(new Date());
            highAgentModel.setOperatorId(userInfoModel.getSecUser().getId());
            highAgentModel.setOperatorName(userInfoModel.getSecUser().getUserName());
            highAgentService.updateAgentMsg(highAgentModel);

            return ResponseMsgUtil.success("修改成功");

        } catch (Exception e) {
            log.error("HighAgentController --> insertAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/generateRechargeAgentQrCode", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "生成【代理商】二维码")
    public ResponseData generateRechargeAgentQrCode(@RequestParam(value = "agentId", required = true) Long agentId) {
        try {

            HighAgent highAgent = highAgentService.findByAgentMsgId(agentId);
            // 代理商类型  1：卡券代理商  2：充值代理商
            if (highAgent == null) {
                log.error("HighAgentController --> generateRechargeAgentQrCode() error!", "此代理商暂无法生成二维码");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "此代理商暂无法生成二维码");
            }
            // 生成二维码
            String url = SysConst.getSysConfig().getAgentQrCodeWxUrl();
            String qrCodeImg = "rechargeAgentQrCode/" + highAgent.getId()+".png";
            String qrCodeUrl = "/home/project/hsg/filesystem/" + qrCodeImg;
            QRCodeGenerator.generateQRCodeImage(url+highAgent.getId(), 350, 350, qrCodeUrl);
            highAgent.setExt1(qrCodeImg);
            highAgentService.updateAgentDetail(highAgent);
            return ResponseMsgUtil.success(qrCodeImg);
        } catch (Exception e) {
            log.error("HighAgentController --> generateRechargeAgentQrCode() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getListAgent", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询代理商列表")
    public ResponseData getListAgent(
            @RequestParam(value = "agentName", required = false) String agentName,
            @RequestParam(value = "agentPhone", required = false) String agentPhone,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "type", required = false) Integer type,
            @RequestParam(name = "pageNum", required = true) Integer pageNum,
            @RequestParam(name = "pageSize", required = true) Integer pageSize, HttpServletRequest request
    ) {
        try {

            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
//            if (userInfoModel.getBsCompany() == null) {
//                log.error("HighAgentController -> insertAgent() error!","该主角色没有权限");
//                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
//            }

            Map<String, Object> map = new HashMap<>();

            if (StringUtils.isNotBlank(agentName)) {
                map.put("agentName", agentName);
            }
            if (StringUtils.isNotBlank(agentPhone)) {
                map.put("agentPhone", agentPhone);
            }
            if (status != null) {
                map.put("status", Integer.toString(status));
            }

            if (type != null) {
                map.put("type", Integer.toString(type));
            }

            map.put("operatorId" , Long.toString(userInfoModel.getSecUser().getId()));

            PageHelper.startPage(pageNum, pageSize);

            List<HighAgent> highAgents = highAgentService.getListAgentMsg(map);

            return   ResponseMsgUtil.success(new PageInfo<>(highAgents));
        } catch (Exception e) {
            log.error("HighAgentController --> getListUser() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/findByAgentId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询详情")
    public ResponseData findById(@RequestParam(value = "agentId", required = true) Long agentId) {
        try {

            HighAgentModel highAgentModel = new HighAgentModel();
            HighAgent highAgent = highAgentService.findByAgentMsgId(agentId);

            BeanUtils.copyProperties(highAgent, highAgentModel);

            // 查询商户主账号
            SecUser mainAccount = secUserService.getMainAccount(4, highAgent.getId());
            if (mainAccount != null) {
                highAgentModel.setSecUser(mainAccount);
            }

            return ResponseMsgUtil.success(highAgentModel);

        } catch (Exception e) {
            log.error("HighUserController --> findByUserId() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/forbiddenUser", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "禁用启用账号")
    public ResponseData forbiddenUser(@RequestParam(value =  "agentId" , required = true) Long agentId) {
        try {
            HighAgent highAgent = highAgentService.findByAgentMsgId(agentId);

            if (highAgent == null) {
                log.error("HighUserController --> forbiddenUser() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_USER_ERROR, "");
            }

            if (highAgent.getStatus() == 1) {
                highAgent.setStatus(0);
            } else {
                highAgent.setStatus(1);
            }

            HighAgentModel highAgentModel = new HighAgentModel();

            BeanUtils.copyProperties(highAgent, highAgentModel);

            highAgentService.updateAgentMsg(highAgentModel);

            return ResponseMsgUtil.success("禁用成功");

        } catch (Exception e) {
            log.error("BsPositionController --> addPosition() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
