package cn.pluss.platform.merchant.impl;

import cn.jiguang.common.utils.StringUtils;
import cn.pluss.platform.converter.MerchantStaffConverter;
import cn.pluss.platform.converter.UserAppConverter;
import cn.pluss.platform.dto.MerchantStaffDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantStaffConnMapper;
import cn.pluss.platform.merchant.MerchantStaffConnService;
import cn.pluss.platform.merchant.StaffPermissionService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.MD5Util;
import cn.pluss.platform.vo.MerchantStaffConnVO;
import cn.pluss.platform.vo.MerchantStaffVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 员工商户关联表 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2021-03-24
 */
@Service
public class MerchantStaffConnServiceImpl extends ServiceImpl<MerchantStaffConnMapper, MerchantStaffConn> implements MerchantStaffConnService {

    @Setter(onMethod_ = {@Autowired})
    private UserAppService userAppService;

    @Setter(onMethod_ = {@Autowired})
    private UserInfoService userInfoService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantBaseInfoService merchantBaseInfoService;

    @Setter(onMethod_ = {@Autowired})
    private StaffPermissionService staffPermissionService;

    @Override
    public UserApp createOrEditStaff(MerchantStaffDTO staffDTO) {
        UserApp userApp = userAppService.queryUserAppByToken();

        staffDTO.setMerchantCode(userApp.getMerchantCode());
        List<MerchantBaseInfo> merchList = merchantBaseInfoService.getAllByUserId(userApp.getUserId() + "");
        for (String merchantCode : staffDTO.getMerchantCodeList()) {
            boolean flag = true;
            for (MerchantBaseInfo merchantBaseInfo : merchList) {
                if (merchantBaseInfo.getMerchantCode().equals(merchantCode)) {
                    flag = false;
                    break;
                }
            }

            if (flag) {
                throw new MsgException("参数非法");
            }
        }

        if (staffDTO.getUserId() == null) {
            return createStaff(staffDTO);
        } else {
            return editStaff(staffDTO);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserApp createStaff(MerchantStaffDTO staffDTO) {
        String loginName = staffDTO.getLoginName().replace("@kuaiyin", "");
        if (loginName.contains("@")) {
            throw new MsgException("员工账号请不要带@");
        }
        staffDTO.setLoginName(loginName + "@kuaiyin");
        UserInfo existUserInfo = new UserInfo().setLoginName(staffDTO.getLoginName());
        existUserInfo = userInfoService.getOne(new QueryWrapper<>(existUserInfo));
        if (existUserInfo != null) {
            throw new MsgException("账号已存在");
        }

        if (staffDTO.getMerchantCodeList() == null || staffDTO.getMerchantCodeList().isEmpty()) {
            throw new MsgException("请选择关联店铺");
        }

        MerchantStaffConverter merchantStaffConverter = MerchantStaffConverter.INSTANCE;
        UserAppConverter userAppConverter = UserAppConverter.INSTANCE;

        UserInfo userInfo = merchantStaffConverter.toUserInfo(staffDTO);
        userInfo.setStatus(1);
        String pwd = MD5Util.MD5Encode(userInfo.getPassword(), "utf-8");
        userInfo.setPassword(pwd);
        Date date = new Date();
        userInfo.setCreateTime(date);
        userInfo.setUpdateTime(date);

        userInfoService.save(userInfo);

        UserApp userApp = userAppConverter.toUserApp(userInfo);
        userApp.setUserType("staff");
        userApp.setUserName(staffDTO.getUserName());
        userApp.setStaffType(1);
        userAppService.save(userApp);

        for (String merchantCode : staffDTO.getMerchantCodeList()) {
            bindStaff(userApp.getUserId(), merchantCode);
            StaffPermission staffPermission = staffPermissionService.getEntity(userApp.getUserId(), merchantCode);
            staffPermission.setPermissionBill(staffDTO.getPermissionBill());
            staffPermissionService.save(staffPermission);
        }

        return userApp;
    }

    @Override
    public UserApp editStaff(MerchantStaffDTO staffDTO) {
        if (staffDTO.getUserId() == null) {
            throw new MsgException("用户id不能为空");
        }

        MerchantStaffConverter merchantStaffConverter = MerchantStaffConverter.INSTANCE;
        UserAppConverter userAppConverter = UserAppConverter.INSTANCE;

        UserInfo userInfo = merchantStaffConverter.toUserInfo(staffDTO);
        if (StringUtils.isNotEmpty(staffDTO.getPassword())) {
            String pwd = MD5Util.MD5Encode(userInfo.getPassword(), "utf-8");
            userInfo.setPassword(pwd);
            Date date = new Date();
            userInfo.setUpdateTime(date);

            UpdateWrapper<UserInfo> uW = new UpdateWrapper<>();
            uW.eq("id", staffDTO.getUserId());
            userInfoService.update(userInfo, uW);
        } else {
            Date date = new Date();
            userInfo.setUpdateTime(date);

            UpdateWrapper<UserInfo> uW = new UpdateWrapper<>();
            uW.eq("id", staffDTO.getUserId());
            userInfoService.update(userInfo, uW);
        }

        UserApp userApp = userAppConverter.toUserApp(userInfo);
        userApp.setUserName(staffDTO.getUserName());
        UpdateWrapper<UserApp> uW2 = new UpdateWrapper<>();
        uW2.eq("userId", staffDTO.getUserId());
        userAppService.update(userApp, uW2);

        delAllStaff(userApp.getUserId());
        for (String merchantCode : staffDTO.getMerchantCodeList()) {
            bindStaff(userApp.getUserId(), merchantCode);

            // 编辑员工的时候只能修改当前门店下的员工权限
            if (!staffDTO.getMerchantCode().equals(merchantCode)) {
                continue;
            }

            StaffPermission staffPermission = staffPermissionService.getEntity(userApp.getUserId(), merchantCode);
            staffPermission.setPermissionBill(staffDTO.getPermissionBill());
            staffPermissionService.saveOrUpdate(staffPermission);
        }

        return userApp;
    }

    @Override
    public void bindStaff(Long userId, String merchantCode) {
        MerchantStaffConn merchantStaffConn = new MerchantStaffConn();
        merchantStaffConn.setUserId(userId);
        merchantStaffConn.setMerchantCode(merchantCode);
        save(merchantStaffConn);
    }

    @Override
    public void delAllStaff(Long userId) {
        MerchantStaffConn staffConn = new MerchantStaffConn();
        staffConn.setUserId(userId);
        
        QueryWrapper<MerchantStaffConn> qW = new QueryWrapper<>(staffConn);
        remove(qW);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delStaff(Long userId, List<String> merchantCodeList) {

        for (String merchantCode : merchantCodeList) {
            MerchantStaffConn staffConn = new MerchantStaffConn();
            staffConn.setMerchantCode(merchantCode);
            staffConn.setUserId(userId);
            remove(new QueryWrapper<>(staffConn));

            staffPermissionService.remove(userId, merchantCode);
        }

        MerchantStaffConn staffConn = new MerchantStaffConn().setUserId(userId);
        List<MerchantStaffConn> resultList = list(new QueryWrapper<>(staffConn));
        if (resultList.size() > 0) {
            return;
        }



        // 如果已解绑的所有的店铺，那么就删除所选账号
        userInfoService.removeById(userId);
        QueryWrapper<UserApp> qW = new QueryWrapper<>();
        qW.eq("userId", userId);
        userAppService.remove(qW);
    }

    @Override
    public MerchantStaffVO getOneForApp(String userId) {
        UserApp staffUa = userAppService.getOne(new QueryWrapper<>(new UserApp().setUserId(Long.parseLong(userId))));
        UserApp userApp = userAppService.queryUserAppByToken();

        MerchantStaffConn staffConn = new MerchantStaffConn();
        staffConn.setUserId(staffUa.getUserId());
        staffConn.setMerchantCode(userApp.getMerchantCode());
        staffConn = getOne(new QueryWrapper<>(staffConn));

        StaffPermission staffPermission = staffPermissionService.getEntity(Long.parseLong(userId), userApp.getMerchantCode());
        String permissionBill = staffPermission.getPermissionBill();
        staffUa.setPermissionBill(permissionBill == null? "1" : permissionBill);

//        if (staffConn == null) {
//            throw new MsgException("拒绝访问");
//        }
        
        MerchantStaffVO merchantStaffVO = new MerchantStaffVO();
        merchantStaffVO.setUserApp(staffUa);

        List<MerchantStaffConnVO> connList = baseMapper.selectByUserId(userId);
        merchantStaffVO.setConnList(connList);

        return merchantStaffVO;
    }

    @Override
    public List<MerchantStaffConnVO> getListByUserId(String userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public List<MerchantBaseInfo> getMercInfoByStaffId(String userAppId) {
        return baseMapper.getMercInfoByStaffId(userAppId);
    }

    @Override
    public MerchantStaffConn getStaffConnInfoByCodeAndId(String userId, String merchantCode) {
        List<MerchantStaffConn> list = baseMapper.selectList(new QueryWrapper<MerchantStaffConn>(new MerchantStaffConn().setMerchantCode(merchantCode).setUserId(Long.parseLong(userId))));
        return list.isEmpty() ? null : list.get(0);
    }
}
