package com.thinkgem.jeesite.modules.youka.service;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.MD5;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.youka.dao.YoukaCardDao;
import com.thinkgem.jeesite.modules.youka.dao.YoukaUserDao;
import com.thinkgem.jeesite.modules.youka.dao.YoukaUserDetailDao;
import com.thinkgem.jeesite.modules.youka.entity.UserSubMchId;
import com.thinkgem.jeesite.modules.youka.entity.YoukaCardEntity;
import com.thinkgem.jeesite.modules.youka.entity.YoukaUser;
import com.thinkgem.jeesite.modules.youka.entity.YoukaUserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author niehh
 * @Description: 优卡用户
 * @date 2018年03月05日 15:51
 */

@Service
@Transactional(readOnly = true)
public class YoukaUserService extends CrudService<YoukaUserDao, YoukaUser> {

    @Autowired
    private YoukaUserDetailDao youkaUserDetailDao;

    @Autowired
    private YoukaCardDao youkaCardDao;

    @Autowired
    private SystemService systemService;

    @Autowired
    private YoukaUserDao youkaUserDao;


    @Override
    public YoukaUser get(String id) {
        YoukaUser user = dao.get(id);
        if (user != null && user.getAvatar() != null) {
            user.setAvatar(Global.IMAGE_SAVE_URL + user.getAvatar());
        }

        return user;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void save(YoukaUser youkaUser) {
        //当前登录用户信息
        User user2 = UserUtils.getUser();
        if (StringUtils.isBlank(youkaUser.getBelongTo())) {
            youkaUser.setBelongTo("B");
        }
        //添加王者
        if (StringUtils.isBlank(youkaUser.getRecommendedPath()) && "A".equals(youkaUser.getLevel())) {
            if ("B".equals(youkaUser.getBelongTo())) {
                YoukaUser youkaUser1 = dao.get("1");
                youkaUser.setRecommendedPath(youkaUser1 !=null? ",0,1,":",0,");
                youkaUser.setRecommendedMobile(youkaUser1 != null ? youkaUser1.getMobile() : "");
            } else if ("S".equals(youkaUser.getBelongTo())) {
                YoukaUser youkaUser1 = dao.get("2");
                youkaUser.setRecommendedPath(youkaUser1 !=null?",0,2,":",0,");
                youkaUser.setRecommendedMobile(youkaUser1 != null ? youkaUser1.getMobile() : "");
            }
            //添加钻石，添加青铜
        } else if (StringUtils.isBlank(youkaUser.getRecommendedPath()) && ("B".equals(youkaUser.getLevel()) || "E".equals(youkaUser.getLevel()))) {
            YoukaUser youkaUser2 = new YoukaUser();
            youkaUser2.setMobile(user2.getPhone());
            YoukaUser youkaUser1 = youkaUserDao.checkMobile(youkaUser2);

            youkaUser.setRecommendedPath(youkaUser1.getRecommendedPath() + youkaUser1.getId() + ",");
            youkaUser.setRecommendedMobile(youkaUser1.getMobile());

        }

        if (youkaUser.getId() != null && !"".equals(youkaUser.getId())) {
//            youkaUser.setUpdateBy(UserUtils.getUser());
            youkaUser.preUpdate();
            youkaUser.setAvatar(StringUtils.replace(youkaUser.getAvatar(), Global.IMAGE_SAVE_URL, ""));
            dao.update(youkaUser);
            YoukaUserDetail youkaUserDetail = youkaUser.getYoukaUserDetail();
            if (youkaUserDetail != null) {
                youkaUserDetail.preUpdate();
                youkaUserDetail.setIdCardFront(StringUtils.replace(youkaUserDetail.getIdCardFront(), Global.IMAGE_SAVE_URL, ""));
                youkaUserDetail.setIdCardBack(StringUtils.replace(youkaUserDetail.getIdCardBack(), Global.IMAGE_SAVE_URL, ""));
                youkaUserDetail.setIdCardHold(StringUtils.replace(youkaUserDetail.getIdCardHold(), Global.IMAGE_SAVE_URL, ""));
                youkaUserDetail.setDebitCard(StringUtils.replace(youkaUserDetail.getDebitCard(), Global.IMAGE_SAVE_URL, ""));

                youkaUserDetail.setUpdateBy(UserUtils.getUser());
                youkaUserDetail.setUserCode(youkaUser.getCode());
                if (youkaUserDetailDao.getByUserCode(youkaUser.getCode()) == null) {
                    youkaUserDetail.preInsert();
                    youkaUserDetail.setCode(IdGen.randomBase62(64));
                    youkaUserDetailDao.insert(youkaUserDetail);
                } else {
                    youkaUserDetailDao.update(youkaUserDetail);
                }

            }
            List<YoukaCardEntity> youkaCardEntityList = youkaUser.getYoukaCardEntityList();
            if (youkaCardEntityList != null && youkaCardEntityList.size() > 0) {
                for (YoukaCardEntity youkaCardEntity : youkaCardEntityList) {
                    if (youkaCardEntity.getIsDebit() != null && !youkaCardEntity.getIsDebit().equals(youkaCardEntity.getIsNewDebit())) {
                        youkaCardEntity.setIsDebit(youkaCardEntity.getIsNewDebit());
                        youkaCardDao.updateIsDebit(youkaCardEntity);
                    }
                }
            }

        } else {
            youkaUser.preInsert();
            // 申请子商户号
            String subMerchantId = "subMerchantId" + DateUtils.formatDateTime(new Date());
            youkaUser.setSubMerchantId(subMerchantId);
            // 保存用户信息
            String code = IdGen.randomBase62(64);
            youkaUser.setNickname("E_" + youkaUser.getMobile());

            //王者会员只能添加钻石会员
            if (!StringUtils.isBlank(user2.getOffice().getName()) && (user2.getOffice().getName().equals("王者用户"))) {
                youkaUser.setBelongTo(user2.getName());
                youkaUser.setStatus("5");
            } else if (!StringUtils.isBlank(user2.getOffice().getName()) && user2.getOffice().getName().equals("钻石用户")) {
                youkaUser.setBelongTo(user2.getName());
                youkaUser.setStatus("0");
            } else {
                youkaUser.setStatus("5");
            }

            youkaUser.setCode(code);
            youkaUser.setAvatar(StringUtils.replace(youkaUser.getAvatar(), Global.IMAGE_SAVE_URL, ""));
            String pwd = null;
            if (StringUtils.isBlank(youkaUser.getOrderCode())) {
                pwd = youkaUser.getPassword();
                //用户端，管理后台密码加密不同
//                youkaUser.setPassword(SystemService.entryptPassword(youkaUser.getPassword()));
                youkaUser.setPassword(MD5.sign(youkaUser.getPassword(), "Y0UKA@2018", "utf-8"));
            }

            dao.insert(youkaUser);
            YoukaUserDetail youkaUserDetail = youkaUser.getYoukaUserDetail();
            if (youkaUserDetail != null) {
                youkaUserDetail.preInsert();

                youkaUserDetail.setIdCardFront(StringUtils.replace(youkaUserDetail.getIdCardFront(), Global.IMAGE_SAVE_URL, ""));
                youkaUserDetail.setIdCardBack(StringUtils.replace(youkaUserDetail.getIdCardBack(), Global.IMAGE_SAVE_URL, ""));
                youkaUserDetail.setIdCardHold(StringUtils.replace(youkaUserDetail.getIdCardHold(), Global.IMAGE_SAVE_URL, ""));
                youkaUserDetail.setDebitCard(StringUtils.replace(youkaUserDetail.getDebitCard(), Global.IMAGE_SAVE_URL, ""));
                youkaUserDetail.setUpdateBy(UserUtils.getUser());
                youkaUserDetail.setUserCode(youkaUser.getCode());
                youkaUserDetail.setCode(IdGen.randomBase62(64));
                youkaUserDetailDao.insert(youkaUserDetail);
            }

            //管理员添加王者用户
            if ("A".equals(youkaUser.getLevel())) {
                User aUser = new User();
                aUser.setCompany(new Office("48b56cabc6d64691b6f97c518bac76fd"));
                aUser.setOffice(new Office("9e4e371817b142059ee4276a0f554ffb"));
                aUser.setPassword(SystemService.entryptPassword(pwd));
                aUser.setPhone(youkaUser.getMobile());
                List<Role> roleList = Lists.newArrayList();
                List<String> roleIdList = new ArrayList<>();
                roleIdList.add("488d4edba1804b609d5017eaf8a68109");
//                user.preInsert();
                for (Role r : systemService.findAllRole()) {
                    if (roleIdList.contains(r.getId())) {
                        roleList.add(r);
                    }
                }
                aUser.setRoleList(roleList);
                aUser.setName("userId_" + youkaUser.getId());
                aUser.setLoginName(youkaUser.getMobile());
                aUser.setLoginFlag("1");
                aUser.setNo("121323");
                // 保存用户信息
                systemService.saveUser(aUser);
            }
            //王者用户添加钻石用户
            if ("B".equals(youkaUser.getLevel())) {
                User bUser = new User();
                bUser.setCompany(new Office("48b56cabc6d64691b6f97c518bac76fd"));
                bUser.setOffice(new Office("153fd0952728416aa9d3e712dc525bf5"));
                bUser.setPassword(SystemService.entryptPassword(pwd));
                bUser.setPhone(youkaUser.getMobile());
                List<Role> roleList = Lists.newArrayList();
                List<String> roleIdList = new ArrayList<>();
                roleIdList.add("5253e6070a7a456683d697a49980978a");
//                user.preInsert();
                for (Role r : systemService.findAllRole()) {
                    if (roleIdList.contains(r.getId())) {
                        roleList.add(r);
                    }
                }
                bUser.setRoleList(roleList);
                bUser.setName("userId_" + youkaUser.getId());
                bUser.setLoginName(youkaUser.getMobile());
                bUser.setLoginFlag("1");
                bUser.setNo("121323");
                // 保存用户信息
                systemService.saveUser(bUser);
            }
        }
    }


    public List<YoukaUser> findByIdIn(String[] ids) {
        return dao.findByIdIn(ids);
    }

    public YoukaUser checkRecommend(YoukaUser youkaUser) {
        return dao.checkRecommend(youkaUser);
    }

    public YoukaUser checkMobile(YoukaUser youkaUser) {
        return dao.checkMobile(youkaUser);
    }

    public YoukaUser checkMobile(String mobile) {
        YoukaUser youkaUser = new YoukaUser();
        youkaUser.setMobile(mobile);
        return dao.checkMobile(youkaUser);
    }

    // 根据通道获取Submchid
    public List<UserSubMchId> getUserSubmchid(String paychannel, String level) {
        UserSubMchId userSubMchId = new UserSubMchId();
        userSubMchId.setPayChannel(paychannel);
        userSubMchId.setLevel(level);
        return dao.getUserSubmchid(userSubMchId);
    }

}
