package com.iformall.controller;


import com.iformall.annotation.AuthIgnore;
import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxMall;
import com.iformall.domain.po.WxMerchant;
import com.iformall.domain.po.WxMerchantBUser;
import com.iformall.domain.po.WxScoreRules;
import com.iformall.enums.EnumCreditLockedStatus;
import com.iformall.enums.EnumMerchantBUserStatus;
import com.iformall.enums.EnumMerchantStatus;
import com.iformall.service.*;
import com.iformall.utils.HashUtil;
import com.iformall.utils.IPUtil;
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.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(description = "B端用户相关接口")
@RequestMapping("/api/user")
public class WxMerchantBUserController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMerchantBUserService wxMerchantBUserService;

    @Autowired
    private WxMerchantService wxMerchantService;

    @Autowired
    private WxMallService wxMallService;

    @Autowired
    private WxLevelConfigService wxLevelConfigService;

    @Autowired
    private WxCUserService wxCUserService;

    @Autowired
    private WxCUserBasicInfoService wxCUserBasicInfoService;

    @Autowired
    private WxScoreRulesService wxScoreRulesService;

    @ApiOperation("查寻当bUser详情接口")
    @GetMapping("/detail")
    public ResultData detail() {
        Map resultMap = new HashMap();

        WxMerchantBUser user = getUser();

        if (user == null){
            return new ResultData(ErrorCode.USER_IS_EMPTY);
        }

        WxMerchant merchant = wxMerchantService.getById(user.getMerchantId());
        if (merchant == null){
            return new ResultData(ErrorCode.MCH_INFO_NOT_FOUND);
        }

        WxMall mall = wxMallService.getByTenantId(merchant.getTenantId());
        if (mall == null){
            return new ResultData(ErrorCode.MALL_INFO_NOT_FOUND);
        }

        resultMap.put("creditLocked", merchant.getCreditLocked());
        WxScoreRules scoreRules = wxScoreRulesService.getCreditRules(user.getTenantId());
        if (scoreRules.getCreditLocked().equals(EnumCreditLockedStatus.CLOSE.getCode())) {
            resultMap.put("creditLocked", EnumCreditLockedStatus.CLOSE.getCode());
        }
        resultMap.put("phone", user.getPhone());
        resultMap.put("name", user.getName());
        resultMap.put("merchant_name", merchant.getName());
        resultMap.put("merchant_img_url", merchant.getImgUrl());
        resultMap.put("mall_name", mall.getName());
        resultMap.put("service_phone", mall.getServicePhone());
        resultMap.put("tenant_id",merchant.getTenantId());
        resultMap.put("merchant_id",merchant.getId());
        resultMap.put("is_admin",merchant.getIsAdmin());
        resultMap.put("businessId", merchant.getBusinessId());

        String mid = null;
        try {
            mid = String.valueOf(merchant.getId());
            if(mid != null) {
                resultMap.put("merchant_id_scan", HashUtil.EncoderByMd5(mid));
            }
        }catch (Exception e) {
            logger.error(e.getMessage());
        }

        return new ResultData(resultMap);
    }


    /**
     * 用户登录
     *
     * @param map
     * @return
     */
    @AuthIgnore
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "{" +
            "\"appId\":\"string\"," +
            "\"phone\":\"string\",\"password\":\"string\"," +
            "\"latitude\":\"string\",\"longitude\":\"string\"}")
    public ResultData userLogin(@RequestBody Map<String, String> map) {
        logger.debug(map.toString());

        String appId = map.get("appId");
        String phone = map.get("phone");
        String password = map.get("password");
        String latitude = map.get("latitude");
        String longitude = map.get("longitude");
        //登录凭证不能为空
        if (StringUtils.isBlank(phone)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "手机号不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "密码不能为空");
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipaddress = IPUtil.getIpAddr(request);
        if (!StringUtils.isBlank(latitude) && !StringUtils.isBlank(longitude)) {
            logger.info("B端用户: " + phone + " 登录 IP" + ipaddress + ", 经纬度(" + longitude + "," + latitude + ")");
        }
        WxMerchantBUser user = new WxMerchantBUser();
        user.setAppId(appId);
        user.setPhone(phone);
        user.setStatus(EnumMerchantBUserStatus.VALID.getCode());
        WxMerchantBUser user1 = null;
        try {
            user1 = wxMerchantBUserService.getBUserByAppId(user);
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.error("B端用户不存在, phone: " + phone);
            return new ResultData(ErrorCode.USER_IS_EMPTY);
        }

        if (user1 != null) {
            // check merchant 状态
            WxMerchant merchant = null;
            try {
                merchant = wxMerchantService.getById(user1.getMerchantId());
            } catch (Exception e) {
                logger.error(ErrorCode.DB_FAIL.getMessage() + ": " + user1.getMerchantId() + e.getMessage());
                return new ResultData(ErrorCode.DB_FAIL);
            }
            if (merchant == null) {
                logger.error(ErrorCode.MERCHANT_INFO_NOT_FOUND.getMessage() + ": " + user1.getMerchantId());
                return new ResultData(ErrorCode.MERCHANT_INFO_NOT_FOUND);
            }
            if (merchant.getStatus().equals(EnumMerchantStatus.NOT_VALID.getCode())) {
                logger.error(ErrorCode.MERCHANT_INFO_NOT_VALID.getMessage() + ": " + user1.getMerchantId());
                return new ResultData(ErrorCode.MERCHANT_INFO_NOT_VALID);
            }
            // check password
            if (user1.getUserPwd().equalsIgnoreCase(password)) {
                try {
                    wxMerchantBUserService.saveOrUpdate(user1);
                } catch (Exception e) {
                    logger.error("B端用户更新用户信息失败, e:" + e.getMessage());
                    return new ResultData(ErrorCode.DB_FAIL.getCode(), "数据库保存失败,e:" + e.getMessage());
                }
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("bUserId", user1.getId());
                return new ResultData(resultMap);
            } else {
                return new ResultData(ErrorCode.PASSWORD_ERROR);
            }
        } else {
            logger.error("B端用户不存在, phone: " + phone);
            return new ResultData(ErrorCode.USER_IS_EMPTY);
        }

    }


    @AuthIgnore
    @ApiOperation(value = "修改密码", notes = "{\"appId\",\"string\", \"phone\",\"string\",\"code\",\"string\",\"pwd\",\"string\"}")
    @PostMapping("/updatepwd")
    public ResultData updatepwd(@RequestBody Map<String, String> params) {
        // String phone,String code,String pwd
        String appId = params.get("appId");
        String phone = params.get("phone");
        String code = params.get("code");
        String pwd = params.get("pwd");
        if (StringUtils.isBlank(appId)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "appId不能为空");
        }
        if (StringUtils.isBlank(phone)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "手机号不能为空");
        }
        if (StringUtils.isBlank(code)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "验证码不能为空");
        }
        if (StringUtils.isBlank(pwd)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "密码不能为空");
        }

        return wxMerchantBUserService.updatepwd(appId, phone, code, pwd);
    }

}
