package com.iformall.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.dto.WxCUserFromBDto;
import com.iformall.domain.po.*;
import com.iformall.enums.EnumAssignTagsTrigger;
import com.iformall.enums.EnumScoreType;
import com.iformall.enums.EnumUserType;
import com.iformall.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
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 java.util.Date;
import java.util.List;

/**
 * @author gongbiao
 */
@RestController
@RequestMapping("/api/cuser")
@Api(description = "B端来源会员")
public class WxCUserController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private WxCUserBasicInfoService wxCUserBasicInfoService;

    @Autowired
    private WxScoreRulesService wxScoreRulesService;

    @Autowired
    private WxCUserTagsService wxCUserTagsService;

    @Autowired
    private WxMerchantBUserService wxMerchantBUserService;

    @Autowired
    private WxCUserFromBService wxCUserFromBService;

    @Autowired
    private WxCUserService wxCUserService;

    @Autowired
    private WxCreditHistoryService wxCreditHistoryService;


    /**
     * 会员更新信息
     *
     * @return
     */
    @PostMapping("/updateUserInfo")
    @ApiOperation(value = "用户更新信息", notes = "")
    public ResultData updateUserInfo(@RequestBody WxCUserFromBDto wxCUserFromBDto) {
        logger.info("WxCUserController::updateUserInfo");
        if (wxCUserFromBDto == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL, "没有传入用户信息");
        }
        if (StringUtils.isEmpty(wxCUserFromBDto.getOpenid())) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL, "C端openid不能为空");
        }
        if (StringUtils.isEmpty(wxCUserFromBDto.getAppId())) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL, "C端appId不能为空");
        }
        if (wxCUserFromBDto.getUserId() == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL, "bUserId不能为空");
        }
        //根据bUserId查询B端用户是否存在
        WxMerchantBUser bUser = wxMerchantBUserService.getById(wxCUserFromBDto.getUserId());
        if (bUser == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL, "B端用户不存在");
        }
        final IdWorker idWorker = IdWorker.get();

        WxCUserFromB wxCUserFromB = wxCUserFromBService.getByOpenidAndAppId(wxCUserFromBDto);
        //查询C端微信信息
        WxCUser wxCUser = new WxCUser();
        wxCUser.setAppId(wxCUserFromBDto.getAppId());
        wxCUser.setOpenId(wxCUserFromBDto.getOpenid());
        wxCUser = wxCUserService.getByOpenId(wxCUser);
        if (wxCUserFromB == null) {
            //TODO phone可能为空
            String phone = wxCUser.getPhone();
            String tenantId = wxCUser.getTenantId();
            //查询会员信息
            List<WxCUserBasicInfo> byPhone = wxCUserBasicInfoService.findByPhone(tenantId, phone);
            //存在会员信息
            if (!byPhone.isEmpty()) {
                //更新会员信息
                WxCUserBasicInfo wxCUserBasicInfo = byPhone.get(0);
                if (!StringUtils.isEmpty(wxCUserFromBDto.getName())) {
                    wxCUserBasicInfo.setName(wxCUserFromBDto.getName());
                }
                if (wxCUserFromBDto != null) {
                    wxCUserBasicInfo.setBirthdate(wxCUserFromBDto.getBirthdate());
                }
                if (wxCUserFromBDto.getSex() != null) {
                    wxCUserBasicInfo.setSex(wxCUserFromBDto.getSex());
                }
                if (!StringUtils.isEmpty(wxCUserFromBDto.getAddress())) {
                    wxCUserBasicInfo.setAddress(wxCUserFromBDto.getAddress());
                }
                wxCUserBasicInfo.setPhone(wxCUser.getPhone());
                wxCUserBasicInfo.setUpdateDate(new Date());
                wxCUserBasicInfoService.update(wxCUserBasicInfo);
                wxScoreRulesService.addScore(EnumScoreType.COMPLETE_INFO, wxCUserBasicInfo);
                //增加积分
                addCredit(wxCUserBasicInfo, EnumScoreType.COMPLETE_INFO, wxCUserFromBDto.getUserId());
                wxCUserTagsService.triggerAssignTags(EnumAssignTagsTrigger.ASSIGN_TAGS_TRIGGER_IMPORT, wxCUserBasicInfo);
                //新增来自B端的会员关联数据
                wxCUserFromB = new WxCUserFromB();
                wxCUserFromB.setBUserId(wxCUserFromBDto.getUserId());
                wxCUserFromB.setCUserId(wxCUserBasicInfo.getId());
                wxCUserFromB.setOpenid(wxCUserFromBDto.getOpenid());
                wxCUserFromB.setMerchantId(bUser.getMerchantId());
                wxCUserFromB.setTenantId(bUser.getTenantId());
                wxCUserFromB.setAppId(wxCUserFromBDto.getAppId());
                wxCUserFromB.setInfo(JSONObject.toJSONString(wxCUserBasicInfo));
                wxCUserFromBService.saveOrUpdate(wxCUserFromB);
            } else {
                //新增来自B端的会员
                long cUserId = idWorker.nextId();
                WxCUserBasicInfo wxCUserBasicInfo = new WxCUserBasicInfo();
                wxCUserBasicInfo.setId(cUserId);
                if (!StringUtils.isEmpty(wxCUserFromBDto.getName())) {
                    wxCUserBasicInfo.setName(wxCUserFromBDto.getName());
                }
                if (wxCUserFromBDto != null) {
                    wxCUserBasicInfo.setBirthdate(wxCUserFromBDto.getBirthdate());
                }
                if (wxCUserFromBDto.getSex() != null) {
                    wxCUserBasicInfo.setSex(wxCUserFromBDto.getSex());
                }
                if (!StringUtils.isEmpty(wxCUserFromBDto.getAddress())) {
                    wxCUserBasicInfo.setAddress(wxCUserFromBDto.getAddress());
                }
                wxCUserBasicInfo.setPhone(wxCUser.getPhone());
                wxCUserBasicInfo.setUpdateDate(new Date());
                wxCUserBasicInfoService.save(wxCUserBasicInfo);
                //新增来自B端的会员关联数据
                wxCUserFromB = new WxCUserFromB();
                wxCUserFromB.setBUserId(wxCUserFromBDto.getUserId());
                wxCUserFromB.setCUserId(cUserId);
                wxCUserFromB.setOpenid(wxCUserFromBDto.getOpenid());
                wxCUserFromB.setMerchantId(bUser.getMerchantId());
                wxCUserFromB.setTenantId(bUser.getTenantId());
                wxCUserFromB.setAppId(wxCUserFromBDto.getAppId());
                wxCUserFromB.setInfo(JSONObject.toJSONString(wxCUserBasicInfo));
                wxCUserFromBService.saveOrUpdate(wxCUserFromB);
            }
        } else {
            WxCUserBasicInfo wxCUserBasicInfo = wxCUserBasicInfoService.getById(wxCUserFromB.getCUserId());
            if (!StringUtils.isEmpty(wxCUserFromBDto.getName())) {
                wxCUserBasicInfo.setName(wxCUserFromBDto.getName());
            }
            if (wxCUserFromBDto != null) {
                wxCUserBasicInfo.setBirthdate(wxCUserFromBDto.getBirthdate());
            }
            if (wxCUserFromBDto.getSex() != null) {
                wxCUserBasicInfo.setSex(wxCUserFromBDto.getSex());
            }
            if (!StringUtils.isEmpty(wxCUserFromBDto.getAddress())) {
                wxCUserBasicInfo.setAddress(wxCUserFromBDto.getAddress());
            }
            wxCUserBasicInfo.setPhone(wxCUser.getPhone());
            wxCUserBasicInfoService.update(wxCUserBasicInfo);
            wxScoreRulesService.addScore(EnumScoreType.COMPLETE_INFO, wxCUserBasicInfo);
            //增加积分
            addCredit(wxCUserBasicInfo, EnumScoreType.COMPLETE_INFO, wxCUserFromBDto.getUserId());
            wxCUserTagsService.triggerAssignTags(EnumAssignTagsTrigger.ASSIGN_TAGS_TRIGGER_IMPORT, wxCUserBasicInfo);
            //更新B端来源会员
            wxCUserFromB.setInfo(JSONObject.toJSONString(wxCUserBasicInfo));
            wxCUserFromBService.saveOrUpdate(wxCUserFromB);
        }
        return new ResultData();
    }

    private void addCredit(WxCUserBasicInfo wxCUserBasicInfo, EnumScoreType enumScoreType, Long userId) {
        WxCreditHistory wxCreditHistory = new WxCreditHistory();
        wxCreditHistory.setCUserId(wxCUserBasicInfo.getId());
        wxCreditHistory.setTenantId(getTenantId());
        wxCreditHistory.setCreateDate(new Date());
        wxCreditHistory.setCreditType(enumScoreType.getCode());
        wxCreditHistory.setOperatorType(EnumUserType.BUSER.getCode());
        wxCreditHistory.setOperatorId(userId);
        wxCreditHistoryService.saveOrUpdate(wxCreditHistory);
    }


    /**
     * 会员信息
     *
     * @return
     */
    @PostMapping("/findUserInfo")
    @ApiOperation(value = "获取会员信息", notes = "")
    public ResultData findUserInfo(@RequestBody WxCUserFromBDto wxCUserFromBDto) {
        logger.info("WxCUserController::findUserInfo");
        if (wxCUserFromBDto == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL, "没有传入用户信息");
        }
        if (StringUtils.isEmpty(wxCUserFromBDto.getOpenid())) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL, "C端openid不能为空");
        }
        if (StringUtils.isEmpty(wxCUserFromBDto.getAppId())) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL, "C端appid不能为空");
        }
        if (wxCUserFromBDto.getUserId() == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL, "B端userId不能为空");
        }
        WxCUserFromB wxCUserFromB = wxCUserFromBService.getByOpenidAndAppId(wxCUserFromBDto);
        if(wxCUserFromB!=null){
            WxCUserBasicInfo wxCUserBasicInfo = wxCUserBasicInfoService.getById(wxCUserFromB.getCUserId());
            return new ResultData(wxCUserBasicInfo);
        }
        return new ResultData(Result.SUCCESS,"查询成功",null);
    }

    @ApiOperation("分页列表接口")
    @GetMapping("listCUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    public ResultData listCUser(@ModelAttribute WxCUserFromBDto wxCUserFromBDto, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxCUserController::listCUser");
        if (wxCUserFromBDto == null) {
            wxCUserFromBDto = new WxCUserFromBDto();
        }
        PageInfo<WxCUserFromB> wxCUserFromBPageInfo = wxCUserFromBService.listCUser(wxCUserFromBDto, pageNum, pageSize);
        return new ResultData(wxCUserFromBPageInfo);
    }

}
