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.BsSalesman;
import com.hfkj.entity.SecUser;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.BsMerService;
import com.hfkj.service.BsSalesmanService;
import com.hfkj.service.SecUserService;
import com.hfkj.sysenum.SalesmanStatusEnum;
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 = "/salesman")
@Api(value = "代理商")
public class BsSalesmanController {

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

    @Resource
    private UserCenter userCenter;

    @Resource
    private BsSalesmanService salesmanService;

    @Resource
    private BsMerService merService;

    @Resource
    private SecUserService userService;

    @RequestMapping(value = "/insertSalesman", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加业务员")
    public ResponseData insertSalesman(@RequestBody JSONObject body) {
        try {
            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel.getAgent() == null) {
                log.error("BsSalesmanController --> insertSalesman() 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("phone"))
            ) {
                log.error("BsSalesmanController --> insertSalesman() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            BsSalesman salesman = new BsSalesman();
            salesman.setCompanyId(userModel.getAgent().getCompanyId());
            salesman.setCompanyName(userModel.getAgent().getCompanyName());
            salesman.setAgentId(userModel.getAgent().getId());
            salesman.setAgentName(userModel.getAgent().getName());
            salesman.setName(body.getString("name"));
            salesman.setPhone(body.getString("phone"));

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

            salesmanService.insertSalesman(salesman,user);

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

    @RequestMapping(value = "/updateSalesman", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改业务员")
    public ResponseData updateSalesman(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || body.getLong("salesmanId") == null
                    || StringUtils.isBlank(body.getString("name"))
                    || StringUtils.isBlank(body.getString("phone"))
            ) {
                log.error("BsSalesmanController --> updateSalesman() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询业务员
            BsSalesman salesman = salesmanService.getSalesman(body.getLong("salesmanId"));
            if (salesman == null) {
                log.error("BsSalesmanController --> updateSalesman() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到业务员");
            }
            salesman.setName(body.getString("name"));
            salesman.setPhone(body.getString("phone"));
            salesmanService.updateSalesman(salesman);

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

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

            // 查询业务员
            BsSalesman salesman = salesmanService.getSalesman(body.getLong("salesmanId"));
            if (salesman == null) {
                log.error("BsSalesmanController --> disableSalesman() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到代理商");
            }
            if (body.getBoolean("disable") == true) {
                salesman.setStatus(SalesmanStatusEnum.status2.getNumber());
            } else {
                salesman.setStatus(SalesmanStatusEnum.status1.getNumber());
            }
            salesmanService.updateSalesman(salesman);

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

    @RequestMapping(value = "/delSalesman", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除业务员")
    public ResponseData delSalesman(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getLong("salesmanId") == null) {
                log.error("BsAgentController --> disableSalesman() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            salesmanService.delSalesman(body.getLong("salesmanId"));

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

    @RequestMapping(value = "/querySalesman", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询业务员")
    public ResponseData querySalesman(@RequestParam(value = "salesmanId", required = true) Long salesmanId) {
        try {
            Map<String, Object> map = new HashMap<>();

            BsSalesman salesman = salesmanService.getSalesman(salesmanId);
            if (salesman != null) {
                map.put("salesmanDetail", salesman);

                SecUser account = userService.getMainAccount(SecUserTypeEnum.type3.getNumber(), salesmanId);
                if (account != null) {
                    account.setPassword(null);
                    map.put("salesmanAccount", account);
                } else {
                    map.put("salesmanAccount", null);
                }
                return ResponseMsgUtil.success(map);
            }
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error("BsSalesmanController --> querySalesman() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/querySalesmanListByAgent", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询代理商下的业务员列表")
    public ResponseData querySalesmanListByAgent(@RequestParam(value = "name", required = false) String name,
                                                 @RequestParam(value = "phone", required = false) String phone,
                                                 @RequestParam(value = "status", required = false) Integer status,
                                                 @RequestParam(value = "pageNum", required = true) Integer pageNum,
                                                 @RequestParam(value = "pageSize", required = true) Integer pageSize) {
        try {
            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel.getAgent() == null) {
                log.error("BsSalesmanController --> querySalesmanListByAgent() error!", "权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            Map<String, Object> param = new HashMap<>();
            param.put("agentId", userModel.getAgent().getId());
            param.put("name", name);
            param.put("phone", phone);
            param.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(salesmanService.getSalesmanList(param)));
        } catch (Exception e) {
            log.error("BsSalesmanController --> querySalesmanListByAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/querySalesmanList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询业务员列表")
    public ResponseData querySalesmanList(@RequestParam(value = "companyId", required = false) Long companyId,
                                        @RequestParam(value = "agentId", required = false) Long agentId,
                                        @RequestParam(value = "name", required = false) String name,
                                        @RequestParam(value = "phone", required = false) String phone,
                                        @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);
                param.put("agentId", agentId);

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

            } else if (userInfoModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type2.getNumber())) {
                param.put("agentId", userInfoModel.getAgent().getId());

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

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