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.DateUtil;
import com.hai.common.utils.MemberValidateUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.model.HighMerchantModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighMerchantService;
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;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/8 21:55
 */
@Controller
@RequestMapping(value = "/highMerchant")
@Api(value = "商户接口")
public class HighMerchantController {

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighMerchantService highMerchantService;

    @Resource
    private SecUserService secUserService;

    @RequestMapping(value="/insertMerchant",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加商户")
    public ResponseData insertMerchant(@RequestBody HighMerchantModel highMerchant, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighMerchantController -> updateMerchant() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }

            if (StringUtils.isBlank(highMerchant.getMerchantName())
                || StringUtils.isBlank(highMerchant.getTelephone())
                || StringUtils.isBlank(highMerchant.getAddress())
                || StringUtils.isBlank(highMerchant.getSecUser().getPassword())
                || StringUtils.isBlank(highMerchant.getSecUser().getTelephone())
            ) {
                log.error("HighMerchantController -> insertMerchant() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 校验账户手机号
            if (!MemberValidateUtil.validatePhone(highMerchant.getSecUser().getTelephone())) {
                log.error("BsStudentController --> insertMerchant() error!", "请输入正确的电话号码");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.PHONE_NUM_IS_ERROR, "");
            }

            // 校验账号手机号是否存在
            if (secUserService.findByPhone(highMerchant.getSecUser().getTelephone()) != null) {
                log.error("BsStudentController --> insertMerchant() error!", "电话号码已被使用");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.PHONE_NUM_EXISTED, "");
            }

            highMerchant.setMerchantKey("HF" + DateUtil.date2String(new Date(), "MMddHHmmss"));
            highMerchant.setStatus(1); // 状态：0：不可用，1：可用
            highMerchant.setCreateTime(new Date());
            highMerchant.setUpdateTime(new Date());
            highMerchant.setCompanyId(userInfoModel.getBsCompany().getId());
            highMerchant.setOperatorId(userInfoModel.getSecUser().getId());
            highMerchant.setOperatorName(userInfoModel.getSecUser().getUserName());
            highMerchantService.insertMerchant(highMerchant);

            return ResponseMsgUtil.success(highMerchant);
        } catch (Exception e) {
            log.error("HighMerchantController -> insertMerchant() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/updateMerchant",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改商户")
    public ResponseData updateMerchant(@RequestBody HighMerchantModel highMerchant, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighMerchantController -> updateMerchant() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }
            if (highMerchant.getId() == null
                    || StringUtils.isBlank(highMerchant.getMerchantName())
                    || StringUtils.isBlank(highMerchant.getTelephone())
                    || StringUtils.isBlank(highMerchant.getAddress())
            ) {
                log.error("HighMerchantController -> updateMerchant() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询商户
            HighMerchantModel merchant = highMerchantService.getMerchantById(highMerchant.getId());
            if (merchant == null) {
                log.error("HighMerchantController -> updateMerchant() error!","未找到商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "");
            }

            // 商户主账号
            if (merchant.getSecUser() == null) {
                log.error("HighMerchantController -> updateMerchant() error!","主账号异常");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPANY_ADMIN_USER_ERROR, "");
            }

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

            // 校验账号手机号是否存在
            if (!merchant.getSecUser().getTelephone().equals(highMerchant.getSecUser().getTelephone())
                   && secUserService.findByPhone(highMerchant.getSecUser().getTelephone()) != null) {
                log.error("BsStudentController --> updateMerchant() error!", "电话号码已被使用");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.PHONE_NUM_EXISTED, "");
            }

            merchant.setMerchantName(highMerchant.getMerchantName());
            merchant.setTelephone(highMerchant.getTelephone());
            merchant.setAddress(highMerchant.getAddress());
            merchant.setBankName(highMerchant.getBankName());
            merchant.setBankHolder(highMerchant.getBankHolder());
            merchant.setBankAccount(highMerchant.getBankAccount());
            merchant.setMerchantLogo(highMerchant.getMerchantLogo());
            merchant.setMerchantDesc(highMerchant.getMerchantDesc());
            merchant.setUpdateTime(new Date());
            merchant.setOperatorId(userInfoModel.getSecUser().getId());
            merchant.setOperatorName(userInfoModel.getSecUser().getUserName());
            merchant.setCompanyId(userInfoModel.getBsCompany().getId());
            highMerchantService.updateMerchant(merchant);

            return ResponseMsgUtil.success(merchant);
        } catch (Exception e) {
            log.error("HighMerchantController -> updateMerchant() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getMerchantById",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询商户")
    public ResponseData getMerchantById(@RequestParam(name = "id", required = true) Long id) {
        try {

            return ResponseMsgUtil.success(highMerchantService.getMerchantById(id));

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

    @RequestMapping(value="/disableMerchant",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "禁用商户")
    public ResponseData disableMerchant(@RequestParam(name = "id", required = true) Long id) {
        try {

            highMerchantService.updateStatus(id, 0);

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

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

    @RequestMapping(value="/enableMerchant",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "启用商户")
    public ResponseData enableMerchant(@RequestParam(name = "id", required = true) Long id) {
        try {

            highMerchantService.updateStatus(id, 1);

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

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

    @RequestMapping(value="/getMerchantList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户列表")
    public ResponseData getMerchantList(@RequestParam(name = "merchantKey", required = false) String merchantKey,
                                        @RequestParam(name = "merchantName", required = false) String merchantName,
                                        @RequestParam(name = "telephone", required = false) String telephone,
                                        @RequestParam(name = "status", required = false) Integer status,
                                        @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("HighMerchantController -> getMerchantList() error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("companyId", userInfoModel.getBsCompany().getId());
            map.put("merchantKey", merchantKey);
            map.put("merchantName", merchantName);
            map.put("telephone", telephone);
            map.put("status", status);

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highMerchantService.getMerchantList(map)));

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

    @RequestMapping(value="/getMerchantListByCompany",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据公司 查询商户列表")
    public ResponseData getMerchantListByCompany(@RequestParam(name = "companyId", required = false) Long companyId) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("companyId", companyId);
            return ResponseMsgUtil.success(highMerchantService.getMerchantList(map));

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