package com.bweb.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.MD5Util;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.BsCompany;
import com.hai.entity.BsOrganization;
import com.hai.entity.SecRole;
import com.hai.entity.SecUser;
import com.hai.model.ResponseData;
import com.hai.model.SecCompanyModel;
import com.hai.model.UserInfoModel;
import com.hai.service.BsCompanyService;
import com.hai.service.BsOrganizationService;
import com.hai.service.SecRoleService;
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.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.Map;

@Controller
@RequestMapping(value = "/bsCompany")
@Api(value = "公司管理")
public class BsCompanyController {

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private BsCompanyService bsCompanyService;

    @Resource
    private SecUserService secUserService;

    @Resource
    private SecRoleService secRoleService;

    @Resource
    private BsOrganizationService bsOrganizationService;


    @RequestMapping(value = "/selectCompanyList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取公司列表")
    public ResponseData selectCompanyList(@RequestParam(name = "name", required = false) String name,
                                          @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                          @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            if (pageNum == null || pageSize == null) {
                log.error("BsCompanyController --> selectCompanyList() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            Map<String, String> map = new HashMap<>();
            if(StringUtils.isNotBlank(name)){
                map.put("name", name);
            }

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(bsCompanyService.findPage(map)));
        } catch (Exception e) {
            log.error("BsCompanyController --> selectCompanyList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/addCompanyAndUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增公司和管理员账号")
    public ResponseData addCompanyAndUser(@RequestBody SecCompanyModel secCompanyModel, HttpServletRequest request) {
        try {
            BsCompany company = secCompanyModel.getCompany();
            SecUser user = secCompanyModel.getUser();
            if (StringUtils.isBlank(company.getName())
                    || StringUtils.isBlank(company.getRegionId())
                    || StringUtils.isBlank(user.getLoginName())
                    || StringUtils.isBlank(user.getPassword())
                    ) {
                log.error("BsCompanyController --> addCompanyAndUser() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            if(sessionObject == null){
                log.error("SecCompanyController --> updateCompany() error!", "");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            // 校验该区域是否存在公司
            if (bsCompanyService.selectCompanyByRegion(secCompanyModel.getCompany().getRegionId()) != null) {
                log.error("BsCompanyController --> addCompanyAndUser() error!", "该区域分公司已存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "");
            }

            // 校验公司名称
            BsCompany secCompany = bsCompanyService.selectCompanyByName(company.getName());
            if (secCompany != null) {
                log.error("BsCompanyController --> addCompanyAndUser() error!", "该单位已经存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPANY_NAME_IS_EXIST_ERROR, "");
            }
            // 校验用户
            SecUser secUser = secUserService.findByLoginName(user.getLoginName());
            if (secUser != null) {
                log.error("BsCompanyController --> addCompanyAndUser() error!", "该登录用户名已经存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_LOGIN_NAME_IS_EXIST_ERROR, "");
            }
            // 校验用户电话
            SecUser secUserPhone = secUserService.findByPhone(user.getTelephone());
            if (secUserPhone != null) {
                log.error("BsCompanyController --> addCompanyAndUser() error!", "该用户电话已被绑定，请更换");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_PHONE_HAS_ONE_ERROR, "");
            }

            //生成公司状态
            company.setStatus(1);
            company.setCreateTime(new Date());
            company.setUpdateTime(new Date());

            //员工
            user.setAvatar(company.getLogo());
            user.setUserName(company.getName());
            user.setStatus(1);
            user.setAdminFlag(1);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            user.setPassword(MD5Util.encode(user.getPassword().getBytes()));

            //组织架构
            BsOrganization bsOrganization = new BsOrganization();
            bsOrganization.setRegionId(company.getRegionId());
            bsOrganization.setParentId(null);
            bsOrganization.setName(company.getName());
            bsOrganization.setAddress(company.getAddress());
            bsOrganization.setPhone(company.getPhone());
            bsOrganization.setRemark(company.getIntroduction());
            bsOrganization.setEmail(company.getEmail());
            bsOrganization.setSiteUrl(company.getSiteUrl());
            bsOrganization.setLogo(company.getLogo());
            bsOrganization.setStatus(1);
            bsOrganization.setCreateTime(new Date());
            bsOrganization.setUpdateTime(new Date());
            bsOrganization.setOpId(userInfoModel.getSecUser().getId());
            //添加数据
            bsCompanyService.addCompanyInfo(company, user, bsOrganization);
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error("BsCompanyController --> addCompanyAndUser() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updateCompany", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改公司信息")
    public ResponseData updateCompany(@RequestBody SecCompanyModel secCompanyModel, HttpServletRequest request) {
        try {
            BsCompany company = secCompanyModel.getCompany();
            SecUser user = secCompanyModel.getUser();
            if ( StringUtils.isBlank(company.getName())
                    || company.getRegionId() == null
                    || company.getId() == null
                    || StringUtils.isBlank(user.getLoginName())
                    || StringUtils.isBlank(user.getPassword())
                    || user.getId() == null
            ) {
                log.error("BsCompanyController --> updateCompany() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            if(sessionObject == null){
                log.error("SecCompanyController --> updateCompany() error!", "");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();



            // 校验公司名称
            BsCompany secCompany = bsCompanyService.selectCompanyByName(company.getName());
            if (secCompany != null && !secCompany.getId().equals(company.getId())) {
                log.error("BsCompanyController --> updateCompany() error!", "该单位已经存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPANY_NAME_IS_EXIST_ERROR, "");
            }
            BsCompany companyId = bsCompanyService.getCompanyById(company.getId());
            // 校验该区域是否存在公司
            if (bsCompanyService.selectCompanyByRegion(secCompanyModel.getCompany().getRegionId()) != null && !companyId.getId().equals(company.getId())) {
                log.error("BsCompanyController --> addCompanyAndUser() error!", "该区域分公司已存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "");
            }
            BsOrganization organization = bsOrganizationService.findTopByCompany(company.getId());
            if (organization == null) {
                log.error("BsCompanyController --> updateCompany() error!", "未找到该部门信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.UN_FIND_ORGANIZATION_ERROR, "");
            }

            // 查询用户
            SecUser secUser = secUserService.findById(user.getId());
            if (secUser == null) {
                log.error("BsCompanyController --> updateCompany() error!", "未找到该用户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_USER_ERROR, "");
            }

            // 校验用户电话
            SecUser secUserPhone = secUserService.findByPhone(user.getTelephone());
            if (secUserPhone != null && !secUserPhone.getId().equals(user.getId())) {
                log.error("BsCompanyController --> updateCompany() error!", "该用户电话已被绑定，请更换");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_PHONE_HAS_ONE_ERROR, "");
            }
            if (!secUser.getPassword().equals(user.getPassword())) {
                secUser.setPassword(MD5Util.encode(user.getPassword().getBytes()));
            }
            secUser.setAvatar(company.getLogo());
            secUser.setUserName(company.getName());
            secUser.setTelephone(user.getTelephone());
            secUser.setUpdateTime(new Date());

            //组装数据
            organization.setName(company.getName());
            organization.setRegionId(company.getRegionId());
            organization.setOpId(userInfoModel.getSecUser().getId());
            organization.setUpdateTime(new Date());
            organization.setAddress(company.getAddress());
            organization.setPhone(company.getPhone());
            organization.setRemark(company.getIntroduction());
            organization.setEmail(company.getEmail());
            organization.setSiteUrl(company.getSiteUrl());
            organization.setLogo(company.getLogo());
            company.setUpdateTime(new Date());
            //修改公司信息和顶级组织信息
            bsCompanyService.updateCompanyAndDept(company,secUser,organization);

            return ResponseMsgUtil.success("修改成功");
        } catch (Exception e) {
            log.error("BsCompanyController --> updateCompany() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/companyView", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "公司详情")
    public ResponseData companyView(Long companyId) {
        try {
            if (companyId == null) {
                log.error("BsCompanyController --> companyView() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            BsCompany company = bsCompanyService.getCompanyById(companyId);
            SecUser secUser = secUserService.selectAdminUser(companyId);
            SecCompanyModel companyModel = new SecCompanyModel();
            companyModel.setCompany(company);
            companyModel.setUser(secUser);
            return ResponseMsgUtil.success(companyModel);
        } catch (Exception e) {
            log.error("BsCompanyController --> companyView() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/editStatus", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "编辑公司状态")
    public ResponseData editStatus(@RequestParam(name = "companyId", required = true) Long companyId,
                                   @RequestParam(name = "status", required = true) Integer status) {
        try {
            BsCompany company = bsCompanyService.getCompanyById(companyId);
            if (company == null) {
                log.error("BsCompanyController --> editStatus() error!", "未找到公司");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COMPANY, "");
            }
            company.setStatus(status);
            bsCompanyService.updateCompany(company);

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

    @RequestMapping(value="/selectAdminUser",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询公司主账号")
    public ResponseData selectAdminUser(Long companyId) {
        try {
            if (companyId == null) {
                log.error("BsCompanyController --> selectAdminUser() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            SecUser user = secUserService.selectAdminUser(companyId);
            if (user == null) {
                log.error("BsCompanyController --> selectAdminUser() error!", "公司主账号异常");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPANY_ADMIN_USER_ERROR, "");
            }
            SecRole role = secRoleService.getRoleByUserId(user.getId());
            user.setRoleId(role.getId());
            return ResponseMsgUtil.success(user);
        } catch (Exception e) {
            log.error("BsCompanyController --> selectAdminUser() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }
}
