package com.ruoyi.mall.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.common.weiXin.WeiXinUtils;
import com.ruoyi.mall.domain.MallMemberUser;
import com.ruoyi.mall.domain.MallOrderOrder;
import com.ruoyi.mall.domain.MallShopShop;
import com.ruoyi.mall.domain.vo.MallOrderGoodsVO;
import com.ruoyi.mall.mapper.*;
import com.ruoyi.mall.service.IMallOrderGoodsService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import netscape.javascript.JSObject;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mall.domain.MallSalesman;
import com.ruoyi.mall.service.IMallSalesmanService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 业务员Service业务层处理
 *
 * @author ruoyi
 * @date 2022-06-29
 */
@Service
public class MallSalesmanServiceImpl implements IMallSalesmanService
{
    @Resource
    private MallSalesmanMapper mallSalesmanMapper;
    @Resource
    private MallMemberUserMapper mallMemberUserMapper;
    @Resource
    private MallOrderOrderMapper mallOrderOrderMapper;
    @Resource
    private MallOrderGoodsMapper mallOrderGoodsMapper;
    @Autowired
    private IMallOrderGoodsService orderGoodsService;
    @Resource
    private MallShopShopMapper shopShopMapper;

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysDictDataMapper sysDictDataMapper;
    @Resource
    private SysUserPostMapper sysUserPostMapper;
    @Resource
    private WeiXinUtils weiXinUtils;

    /**
     * 业务员登陆
     *
     * @return 业务员
     */
    @Override
    public ApiResult salesmanLogin(Map<String,Object> param){
        String phone = MapUtils.getString(param, "phone");
        String password = MapUtils.getString(param, "password");

        MallSalesman mallSalesman = mallSalesmanMapper.selectMallSalesmanByPhone(phone);
        if (ObjectUtils.isNotEmpty(mallSalesman)){
            if(mallSalesman.getStatus() == 1){
                return ApiResult.error("此账号被冻结");
            }
            if (SecurityUtils.matchesPassword(password,mallSalesman.getPassword())){
                mallSalesman.setIsLogin(1);
                mallSalesmanMapper.updateMallSalesman(mallSalesman);

                mallSalesman.setPassword("");
                return ApiResult.ok().put("data",mallSalesman);
            }
        }
        return ApiResult.error("账号或密码错误");
    }

    @Override
    public ApiResult salesmanLogout(Map<String,Object> param){
        Integer salesmanId = MapUtils.getInteger(param, "salesmanId");
        MallSalesman mallSalesman = mallSalesmanMapper.selectMallSalesmanById(salesmanId);
        if (ObjectUtils.isNotEmpty(mallSalesman)){
            mallSalesman.setIsLogin(0);
            mallSalesmanMapper.updateMallSalesman(mallSalesman);
        }
        return ApiResult.ok();
    }

    /**
     * 业务员修改头像名称
     *
     * @return 业务员
     */
    @Override
    public ApiResult salesmanEdit(Map<String,Object> param){
        Integer salesmanId = MapUtils.getInteger(param, "salesmanId");
        String avatar = MapUtils.getString(param, "avatar");
        String name = MapUtils.getString(param, "name");

        MallSalesman mallSalesman = mallSalesmanMapper.selectMallSalesmanById(salesmanId);
        if (StringUtils.isNotBlank(avatar)){
            mallSalesman.setAvatar(avatar);
        }
        if (StringUtils.isNotBlank(name)){
            mallSalesman.setName(name);
        }
        return ApiResult.toAjax(mallSalesmanMapper.updateMallSalesman(mallSalesman));
    }

    /**
     * 业务员首页业绩
     *
     * @return 业务员
     */
    @Override
    public ApiResult indexData(Map<String,Object> param){
        Integer salesmanId = MapUtils.getInteger(param, "salesmanId");
        //时间筛选（0-日，1-月，2-年）
        Integer type = MapUtils.getInteger(param, "type");

        Map<String, Object> map = mallSalesmanMapper.indexData(salesmanId, type);
        return ApiResult.ok().put("data",map);
    }

    /**
     * 客户列表
     *
     * @return 业务员
     */
    @Override
    public ApiResult salesmanCustomerList(Map<String,Object> param){
        PageHelper.startPage(param);
        return ApiResult.ok().put("data",new PageInfo<>(mallSalesmanMapper.salesmanCustomerList(param)));
    }

    /**
     * 创建客户
     *
     * @return 业务员
     */
    @Override
    public ApiResult createMemberUser(Map<String,Object> param){
        //查询此手机号是否已注册
        MallMemberUser memberUser = mallMemberUserMapper.queryByPhone(MapUtils.getString(param,"phone"));
        if (ObjectUtils.isNotEmpty(memberUser)){
            return ApiResult.error("此手机号已被他人注册");
        }

        //创建客户
        MallMemberUser mallMemberUser = new MallMemberUser();
        mallMemberUser.setPhone(MapUtils.getString(param,"phone"));
        mallMemberUser.setName(MapUtils.getString(param,"name"));
//        mallMemberUser.setPassword(SecurityUtils.encryptPassword(MapUtils.getString(param,"password")));
        mallMemberUser.setPassword(SecurityUtils.encryptPassword("123456"));
        mallMemberUser.setSalesmanId(MapUtils.getInteger(param,"salesmanId"));
        mallMemberUser.setBindingAt(DateUtils.getTime());
        mallMemberUser.setToken(UUID.randomUUID().toString(true));
        mallMemberUser.setStatus("0");
        mallMemberUser.setProvince(MapUtils.getString(param,"province"));
        mallMemberUser.setCity(MapUtils.getString(param,"city"));
        mallMemberUser.setArea(MapUtils.getString(param,"area"));
        mallMemberUser.setAddress(MapUtils.getString(param,"address"));
//        mallMemberUser.setShopImage(MapUtils.getString(param,"shopImage"));
        mallMemberUser.setShopName(MapUtils.getString(param,"shopName"));
        mallMemberUser.setPersonName(MapUtils.getString(param,"name"));
        mallMemberUser.setCreateAt(DateUtils.getTime());
        mallMemberUser.setDelFlag("0");

        return ApiResult.toAjax(mallMemberUserMapper.insertMallMemberUser(mallMemberUser));
    }

    /**
     * 业绩
     *
     * @return 业务员
     */
    @Override
    public ApiResult salesmanAchievement(Map<String,Object> param){
        if (!param.containsKey("timeBegin") || StringUtils.isBlank(param.get("timeBegin").toString())
                || !param.containsKey("timeEnd") || StringUtils.isBlank(param.get("timeEnd").toString())){
            param.put("timeBegin",DateUtils.getDate());
            param.put("timeEnd",DateUtils.getDate());
        }
        //已完成订单，成交金额
        Map<String, Object> finishedMap = mallSalesmanMapper.finishedOrderData(MapUtils.getInteger(param, "salesmanId"),MapUtils.getString(param,"timeBegin"),MapUtils.getString(param,"timeEnd"));
        //待完成订单,待结算金额
        Map<String, Object> toBeSettledMap = mallSalesmanMapper.toBeSettledOrderData(MapUtils.getInteger(param, "salesmanId"),MapUtils.getString(param,"timeBegin"),MapUtils.getString(param,"timeEnd"));

        finishedMap.putAll(toBeSettledMap);
        return ApiResult.ok().put("data",finishedMap);
    }

    /**
     * 订单列表
     *
     * @return 业务员
     */
    @Override
    public ApiResult salesmanOrderList(Map<String,Object> param){
        Integer flag = MapUtils.getInteger(param, "flag");
        PageHelper.startPage(param);
        if (flag == 0){
            if (!param.containsKey("timeBegin") || StringUtils.isBlank(param.get("timeBegin").toString())
                    || !param.containsKey("timeEnd") || StringUtils.isBlank(param.get("timeEnd").toString())){
                param.put("timeBegin",DateUtils.getDate());
                param.put("timeEnd",DateUtils.getDate());
            }
        }
        //订单列表
        List<MallOrderOrder> list = new ArrayList<>();
        String type = MapUtils.getString(param, "type");
        if ("0".equals(type) || "1".equals(type) || "2".equals(type) || "3".equals(type)){
            String sqlStr = "('"+type+"')";
            param.put("status",sqlStr);
            list = mallOrderOrderMapper.salesmanOrderList(param);
        }
        if ("-1".equals(type)){
            String sqlStr = "('0','1','2','3','5','6')";
            param.put("status",sqlStr);
            list = mallOrderOrderMapper.salesmanOrderList(param);
        }
        if ("5".equals(type)){
            String sqlStr = "('5','6')";
            param.put("status",sqlStr);
            list = mallOrderOrderMapper.salesmanOrderList(param);
        }
        //订单详情
        if (list.size() > 0){
            for (MallOrderOrder orderOrder: list) {
                List<MallOrderGoodsVO> orderGoodsVOList = orderGoodsService.selectMallOrderGoodsByOrderId(orderOrder.getId());
                orderOrder.setGoodsVOList(orderGoodsVOList);
            }
        }

        return ApiResult.ok().put("data",new PageInfo<>(list));
    }

    /**
     * 订单详情
     *
     * @return 业务员
     */
    @Override
    public ApiResult salesmanOrderDetail(Map<String,Object> param){
        PageHelper.startPage(param);
        //订单列表
        List<MallOrderOrder> list = new ArrayList<>();
        String type = MapUtils.getString(param, "type");
        if ("0".equals(type) || "1".equals(type) || "2".equals(type) || "3".equals(type)){
            String sqlStr = "('"+type+"')";
            param.put("status",sqlStr);
            list = mallOrderOrderMapper.salesmanOrderList(param);
        }
        if ("-1".equals(type)){
            list = mallOrderOrderMapper.salesmanOrderList(param);
        }
        if ("5".equals(type)){
            String sqlStr = "('5','6')";
            param.put("status",sqlStr);
            list = mallOrderOrderMapper.salesmanOrderList(param);
        }
        //订单详情
        if (list.size() > 0){
            for (MallOrderOrder orderOrder: list) {
                List<MallOrderGoodsVO> orderGoodsVOList = orderGoodsService.selectMallOrderGoodsByOrderId(orderOrder.getId());
                orderOrder.setGoodsVOList(orderGoodsVOList);
            }
        }

        return ApiResult.ok().put("data",new PageInfo<>(list));
    }

    /**
     * 查询业务员
     *
     * @param id 业务员主键
     * @return 业务员
     */
    @Override
    public MallSalesman getSalesmanInfo(Integer id)
    {
        return mallSalesmanMapper.getSalesmanInfo(id);
    }

    /**
     * 后台重置业务员密码
     * @return 业务员
     */
    @Override
    public AjaxResult resetPassword(Map<String,Object> param){
        Integer salesmanId = MapUtils.getInteger(param, "salesmanId");
        // String oldPassword = MapUtils.getString(param, "oldPassword");
        String newPassword = MapUtils.getString(param, "newPassword");

        MallSalesman mallSalesman = mallSalesmanMapper.selectMallSalesmanById(salesmanId);
        // if (SecurityUtils.matchesPassword(oldPassword,mallSalesman.getPassword())){
            mallSalesman.setRealPassword(newPassword);
            mallSalesman.setPassword(SecurityUtils.encryptPassword(newPassword));

        // 修改系统用户
        SysUser sysUser = new SysUser();
        sysUser.setUserId(mallSalesman.getSysUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(newPassword));
        sysUser.setUpdateTime(DateUtils.getNowDate());
        sysUserMapper.updateUser(sysUser);
            return AjaxResult.toAjax(mallSalesmanMapper.updateMallSalesman(mallSalesman));
        // }else {
        //     return AjaxResult.error("原密码错误");
        // }
    }

    /**
     * 查询业务员
     *
     * @param id 业务员主键
     * @return 业务员
     */
    @Override
    public MallSalesman selectMallSalesmanById(Integer id)
    {
        return mallSalesmanMapper.selectMallSalesmanById(id);
    }

    /**
     * 查询业务员列表
     *
     * @param mallSalesman 业务员
     * @return 业务员
     */
    @Override
    public List<MallSalesman> selectMallSalesmanList(MallSalesman mallSalesman)
    {
        return mallSalesmanMapper.selectMallSalesmanList(mallSalesman);
    }

    /**
     * 新增业务员
     *
     * @param mallSalesman 业务员
     * @return 结果
     */
    @Override
    public int insertMallSalesman(MallSalesman mallSalesman)
    {
        String account = mallSalesman.getPhone();// 账号
        String password = mallSalesman.getPassword();// 密码

        mallSalesman.setRealPassword(password);
        mallSalesman.setPassword(SecurityUtils.encryptPassword(password));
        mallSalesman.setCreateAt(DateUtils.getTime());
        mallSalesman.setDelFlag(0);
        // 查询添加人账号
        LoginUser loginUser = SecurityUtils.getLoginUser();
        MallShopShop mallShopShop = shopShopMapper.selectMallShopShopBySysUserId(loginUser.getUserId());
        if (ObjectUtils.isNotEmpty(mallShopShop)){
            // 店铺账号添加
            mallSalesman.setShopId(mallShopShop.getShopId());
            mallSalesman.setCreateBy(loginUser.getUsername());
        }else{
            // 超管添加
            mallSalesman.setShopId(0L);
            mallSalesman.setCreateBy(loginUser.getUsername());
        }

        // 新增系统用户
        SysUser sysUser = new SysUser();
        sysUser.setUserName(account);
        sysUser.setNickName(mallSalesman.getName());
        sysUser.setPhonenumber(account);
        sysUser.setStatus(mallSalesman.getStatus().toString());
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUser.setAvatar(mallSalesman.getAvatar());
        sysUserMapper.insertUser(sysUser);

        // 新增用户与角色管理
        List<SysUserRole> userRoleList = new ArrayList<>();
        SysUserRole ur = new SysUserRole();
        ur.setUserId(sysUser.getUserId());
        if (mallSalesman.getCompanyUserType() == 0) {
            // 账号类型（10-分公司管理员，11-业务员
            ur.setRoleId(10L);
            mallSalesman.setRoleId(10L);
        } else {
            ur.setRoleId(11L);
            mallSalesman.setRoleId(11L);
        }
        userRoleList.add(ur);
        sysUserRoleMapper.batchUserRole(userRoleList);

        mallSalesman.setSysUserId(sysUser.getUserId());

        return mallSalesmanMapper.insertMallSalesman(mallSalesman);
    }

    /**
     * 修改业务员
     *
     * @param mallSalesman 业务员
     * @return 结果
     */
    @Override
    public int updateMallSalesman(MallSalesman mallSalesman)
    {
        String account = mallSalesman.getPhone();// 账号

        // 修改系统用户
        SysUser sysUser = new SysUser();
        sysUser.setUserId(mallSalesman.getSysUserId());
        sysUser.setUserName(account);
        sysUser.setNickName(mallSalesman.getName());
        sysUser.setPhonenumber(account);
        sysUser.setStatus(mallSalesman.getStatus().toString());
        sysUser.setAvatar(mallSalesman.getAvatar());
        sysUser.setUpdateTime(DateUtils.getNowDate());
        sysUserMapper.updateUser(sysUser);

        MallSalesman salesmanById = mallSalesmanMapper.selectMallSalesmanById(mallSalesman.getId());
        if (!Objects.equals(mallSalesman.getCompanyUserType(), salesmanById.getCompanyUserType())) {

            // 删除用户和角色关联
            sysUserRoleMapper.deleteUserRoleByUserId(mallSalesman.getSysUserId());

            // 新增用户与角色管理
            List<SysUserRole> userRoleList = new ArrayList<>();
            SysUserRole ur = new SysUserRole();
            ur.setUserId(sysUser.getUserId());
            if (mallSalesman.getCompanyUserType() == 0) {
                // 账号类型（10-分公司管理员，11-业务员
                ur.setRoleId(10L);
                mallSalesman.setRoleId(10L);
            } else {
                ur.setRoleId(11L);
                mallSalesman.setRoleId(11L);
            }
            userRoleList.add(ur);
            sysUserRoleMapper.batchUserRole(userRoleList);
        }


        mallSalesman.setUpdateAt(DateUtils.getTime());
        return mallSalesmanMapper.updateMallSalesman(mallSalesman);
    }

    /**
     * 批量删除业务员
     *
     * @param ids 需要删除的业务员主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteMallSalesmanByIds(Integer[] ids)
    {
        Long[] sysUserIds = mallSalesmanMapper.selectMallSalesmanSysUserIdByIds(ids);
        if (sysUserIds.length > 0) {
            // 删除用户与角色关联
            sysUserRoleMapper.deleteUserRole(sysUserIds);
            // 删除用户与岗位关联
            sysUserPostMapper.deleteUserPost(sysUserIds);
            sysUserMapper.deleteReallyUserByIds(sysUserIds);
        }
        return mallSalesmanMapper.deleteMallSalesmanByIds(ids);
    }

    /**
     * 删除业务员信息
     *
     * @param id 业务员主键
     * @return 结果
     */
    @Override
    public int deleteMallSalesmanById(Integer id)
    {
        return mallSalesmanMapper.deleteMallSalesmanById(id);
    }

    /**
     * 查询业务员列表（用户数量排序）
     *
     * @return 业务员集合
     */
    @Override
    public List<MallSalesman> selectMallSalesmanUserNumList() {
        return mallSalesmanMapper.selectMallSalesmanUserNumList();
    }

    /**
     * 根据绑定用户ID查询业务员
     *
     * @param userId 定用户ID
     * @return 业务员
     */
    @Override
    public MallSalesman selectMallSalesmanByUserId(Long userId) {
        return mallSalesmanMapper.selectMallSalesmanByUserId(userId);
    }

    /**
     * 新增业务员、分公司管理系统用户信息
     *
     * @param mallSalesman 业务员、分公司管理
     * @return 结果
     */
    @Override
    public int insertSysUserMallSalesman(MallSalesman mallSalesman) {
        String account = mallSalesman.getPhone();// 账号
        String password = "123456";// 密码

        mallSalesman.setRealPassword(password);
        mallSalesman.setPassword(SecurityUtils.encryptPassword(password));

        // 新增系统用户
        SysUser sysUser = new SysUser();
        sysUser.setUserName(account);
        sysUser.setNickName(mallSalesman.getName());
        sysUser.setPhonenumber(account);
        sysUser.setStatus(mallSalesman.getStatus().toString());
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUser.setAvatar(mallSalesman.getAvatar());
        sysUserMapper.insertUser(sysUser);

        // 新增用户与角色管理
        List<SysUserRole> userRoleList = new ArrayList<>();
        SysUserRole ur = new SysUserRole();
        ur.setUserId(sysUser.getUserId());
        if (mallSalesman.getCompanyUserType() == 0) {
            // 账号类型（10-分公司管理员，11-业务员
            ur.setRoleId(10L);
            mallSalesman.setRoleId(10L);
        } else {
            ur.setRoleId(11L);
            mallSalesman.setRoleId(11L);
        }
        userRoleList.add(ur);
        sysUserRoleMapper.batchUserRole(userRoleList);

        mallSalesman.setSysUserId(sysUser.getUserId());
        return mallSalesmanMapper.updateMallSalesman(mallSalesman);
    }

    /**
     * 查看业务员二维码
     * @param mallSalesman 业务员
     * @return 结果
     */
    @Override
    public JSONObject getSalesmanQrCode(MallSalesman mallSalesman){
        Integer id = mallSalesman.getId();
        MallSalesman queryInfo = mallSalesmanMapper.selectMallSalesmanById(id);
        if (ObjectUtils.isEmpty(queryInfo)){
            throw new ServiceException("业务员信息异常");
        }

        String qrCode = queryInfo.getQrCode();
        if (StringUtils.isBlank(qrCode)){
            // 获取小程序二维码
            qrCode = weiXinUtils.getQRCode(id.toString(), "IMG_SALEMAN_" + IdUtils.fastSimpleUUID()+".png");
            if (StringUtils.isBlank(qrCode)){
                throw new ServiceException("获取二维码异常");
            }else {
                queryInfo.setQrCode(qrCode);
                mallSalesmanMapper.updateMallSalesman(queryInfo);
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("qrCode", qrCode);
        return jsonObject;
    }

    @Override
    public MallSalesman selectMallSalesmanBysysUserId(Long userId) {
        return mallSalesmanMapper.selectMallSalesmanBySysUserId(userId);
    }
}
