package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.MD5Util;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.BsAgent;
import com.hfkj.entity.SecUser;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.BsAgentService;
import com.hfkj.service.SecUserService;
import com.hfkj.sysenum.AgentStatusEnum;
import com.hfkj.sysenum.SecUserTypeEnum;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/agent")
@Api(value = "代理商")
public class BsAgentController {

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

    @Resource
    private UserCenter userCenter;

    @Resource
    private BsAgentService agentService;

    @Resource
    private SecUserService userService;

    @RequestMapping(value = "/insertAgent", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加代理商")
    public ResponseData insertAgent(@RequestBody JSONObject body) {
        try {
            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel.getBsCompany() == null) {
                log.error("BsCompanyController --> selectCompanyList() error!", "权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            if (body == null
                    || StringUtils.isBlank(body.getString("loginName"))
                    || StringUtils.isBlank(body.getString("password"))
                    || StringUtils.isBlank(body.getString("name"))
                    || StringUtils.isBlank(body.getString("contactPerson"))
                    || StringUtils.isBlank(body.getString("contactPersonPhone"))
            ) {
                log.error("BsCompanyController --> selectCompanyList() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            BsAgent agent = new BsAgent();
            agent.setCompanyId(userModel.getBsCompany().getId());
            agent.setCompanyName(userModel.getBsCompany().getName());
            agent.setName(body.getString("name"));
            agent.setContactPerson(body.getString("contactPerson"));
            agent.setContactPersonPhone(body.getString("contactPersonPhone"));
            agent.setAddress(body.getString("address"));

            SecUser user = new SecUser();
            user.setLoginName(body.getString("loginName"));
            user.setPassword(MD5Util.encode(body.getString("password").getBytes()));
            user.setCompanyId(userModel.getBsCompany().getId());

            agentService.insertAgent(agent,user);

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("BsAgentController --> insertAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updateAgent", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改代理商")
    public ResponseData updateAgent(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || body.getLong("agentId") == null
                    || StringUtils.isBlank(body.getString("name"))
                    || StringUtils.isBlank(body.getString("contactPerson"))
                    || StringUtils.isBlank(body.getString("contactPersonPhone"))
                    || StringUtils.isBlank(body.getString("contactPersonPhone"))
            ) {
                log.error("BsAgentController --> updateAgent() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询代理商
            BsAgent agent = agentService.getAgent(body.getLong("agentId"));
            if (agent == null) {
                log.error("BsAgentController --> updateAgent() error!", "未找到代理商信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到代理商信息");
            }
            agent.setName(body.getString("name"));
            agent.setContactPerson(body.getString("contactPerson"));
            agent.setContactPersonPhone(body.getString("contactPersonPhone"));
            agent.setAddress(body.getString("address"));
            agentService.updateAgent(agent);

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("BsAgentController --> updateAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/disableAgent", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "禁用代理商")
    public ResponseData disableAgent(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || body.getLong("agentId") == null
                    || body.getBoolean("disable") == null) {
                log.error("BsAgentController --> disableAgent() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询代理商
            BsAgent agent = agentService.getAgent(body.getLong("agentId"));
            if (agent == null) {
                log.error("BsAgentController --> disableAgent() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到代理商");
            }
            if (body.getBoolean("disable") == true) {
                agent.setStatus(AgentStatusEnum.status2.getNumber());
            } else {
                agent.setStatus(AgentStatusEnum.status1.getNumber());
            }
            agentService.updateAgent(agent);

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("BsAgentController --> disableAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/delAgent", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除代理商")
    public ResponseData delAgent(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getLong("agentId") == null) {
                log.error("BsAgentController --> delAgent() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            agentService.delAgent(body.getLong("agentId"));
            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("BsAgentController --> delAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/queryAgent", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询代理商")
    public ResponseData queryAgent(@RequestParam(value = "agentId", required = true) Long agentId) {
        try {
            Map<String, Object> map = new HashMap<>();

            BsAgent agent = agentService.getAgent(agentId);
            if (agent != null) {
                map.put("agentDetail", agent);

                SecUser account = userService.getMainAccount(SecUserTypeEnum.type2.getNumber(), agentId);
                if (account != null) {
                    account.setPassword(null);
                    map.put("agentAccount", account);
                } else {
                    map.put("agentAccount", null);
                }
                return ResponseMsgUtil.success(map);
            }
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error("BsAgentController --> queryAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/queryAgentList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询代理商列表")
    public ResponseData queryAgentList(@RequestParam(value = "companyId", required = false) Long companyId,
                                       @RequestParam(value = "name", required = false) String name,
                                       @RequestParam(value = "contactPerson", required = false) String contactPerson,
                                       @RequestParam(value = "contactPersonPhone", required = false) String contactPersonPhone,
                                       @RequestParam(value = "status", required = false) Integer status,
                                       @RequestParam(value = "pageNum", required = true) Integer pageNum,
                                       @RequestParam(value = "pageSize", required = true) Integer pageSize) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                log.error("BsAgentController --> delAgent() error!", "用户身份错误或已过期");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            Map<String, Object> param = new HashMap<>();
            if (userInfoModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type0.getNumber())) {
                param.put("companyId", companyId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type1.getNumber())) {
                param.put("companyId", userInfoModel.getBsCompany().getId());

            } else {
                log.error("BsAgentController --> delAgent() error!", "权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            param.put("name", name);
            param.put("contactPerson", contactPerson);
            param.put("contactPersonPhone", contactPersonPhone);
            param.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(agentService.listAgent(param)));
        } catch (Exception e) {
            log.error("BsAgentController --> queryAgentList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
