package com.huimv.receive.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.receive.common.token.TokenSign;
import com.huimv.receive.common.utils.*;
import com.huimv.receive.entity.SysAccountMultilevel;
import com.huimv.receive.entity.SysUser;
import com.huimv.receive.entity.vo.AccountVo;
import com.huimv.receive.mapper.SysAccountMultilevelMapper;
import com.huimv.receive.mapper.SysUserMapper;
import com.huimv.receive.service.ISysAccountMultilevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author astupidcoder
 * @since 2021-10-14
 */
@Service
public class SysAccountMultilevelServiceImpl extends ServiceImpl<SysAccountMultilevelMapper, SysAccountMultilevel> implements ISysAccountMultilevelService {

    @Autowired
    private SysAccountMultilevelMapper accountMultilevelMapper;
    @Autowired
    private UploadImage uploadImage;
    @Autowired
    private SysUserMapper userMapper;

    @Override
    public Result findUserAccount(String searchStr, int pageNum, int pageSize, Integer userId) {

        QueryWrapper<SysAccountMultilevel> wrapper = new QueryWrapper<>();
        wrapper.like("pids", userId).or().eq("id", userId);
        IPage<SysAccountMultilevel> page = this.page(new Page<>(pageNum, pageSize), wrapper);
        return new Result(ResultCode.SUCCESS, page);
    }

    @Override
    public Result add(SysAccountMultilevel sysAccountMultilevel, Integer userId) {

        int account = this.count(new QueryWrapper<SysAccountMultilevel>().eq("account", sysAccountMultilevel.getAccount()));
        if (account > 0) {
            return new Result(10001, "该账号已经存在，请重新创建", false);
        }
        SysAccountMultilevel byId = this.getById(userId);
        sysAccountMultilevel.setPid(userId);
        sysAccountMultilevel.setPids(byId.getPids() + "," + userId);
        sysAccountMultilevel.setType(byId.getType());
        sysAccountMultilevel.setType(0);
        sysAccountMultilevel.setLastFarmId(sysAccountMultilevel.getFarmId());
        accountMultilevelMapper.insert(sysAccountMultilevel);
        return new Result(10000, "添加成功", true);
    }

    @Override
    public Result setAccountStatus(List<Integer> ids, Integer status) {
        try {
            for (Integer id : ids) {
                SysAccountMultilevel account = new SysAccountMultilevel();
                account.setId(id);
                account.setAccountStatus(status);
                this.updateById(account);
            }
        } catch (Exception e) {
            return new Result(10001, "插入失败", false);
        }
        String message = "";
        if (status == 1) {
            message = "你选择的账号已经启用。";
        } else {
            message = "你选择的账号已经暂停启用。";
        }
        return new Result(10000, message, true);
    }

    @Override
    public List<Integer> getAllChildId(Integer userId) {
        List<SysAccountMultilevel> pids = this.list(new QueryWrapper<SysAccountMultilevel>().eq("pid", userId));
        List<Integer> list = new ArrayList<>();
        for (SysAccountMultilevel pid : pids) {
            list.add(pid.getId());
        }
        list.add(userId);
        return list;
    }

    @Override
    public Result listSubordinate(String searchStr, int pageNum, int pageSize, Integer userId) {
        QueryWrapper<SysAccountMultilevel> wrapper = new QueryWrapper<>();
        wrapper.like("pids", userId);
        if (StringUtils.isNotBlank(searchStr)) {
            wrapper.like("user_name", searchStr);
        }
        IPage<SysAccountMultilevel> page = this.page(new Page<>(pageNum, pageSize), wrapper);
        return new Result(ResultCode.SUCCESS, page);
    }

    @Override
    public Result getLastFarmId(Integer userId) {
        SysAccountMultilevel sysAccountMultilevel = accountMultilevelMapper.selectById(userId);
        Integer lastFarmId = sysAccountMultilevel.getLastFarmId();
        String farmIds = sysAccountMultilevel.getFarmIds();
        if (farmIds == null) {
            return new Result(10001, "该账号没有绑定牧场", true);
        }
        if (lastFarmId == null) {
            String[] split = farmIds.split(",");
            String s = split[0];
            sysAccountMultilevel.setLastFarmId(Integer.valueOf(s));
            accountMultilevelMapper.updateById(sysAccountMultilevel);
            return new Result(ResultCode.SUCCESS, s);
        }
        return new Result(ResultCode.SUCCESS, lastFarmId);
    }

    @Override
    public Result listSubordinateByFarm(String farmId, Integer userId) {
        QueryWrapper<SysAccountMultilevel> wrapper = new QueryWrapper<>();
        wrapper.like("pids", userId);
        wrapper.like("farm_ids", farmId);
        List<SysAccountMultilevel> page = this.list(wrapper);
        return new Result(ResultCode.SUCCESS, page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateUser(HttpServletRequest httpServletRequest, MultipartFile img, String userName, String phone, Integer workPost, String workLocation, String workLocationId, String workName, String papersType, String papersCode) throws IOException {
        SysAccountMultilevel sysAccountMultilevel = accountMultilevelMapper.selectById(TokenSign.getMemberIdByJwtToken(httpServletRequest));
        if (ObjectUtil.isNotEmpty(img)) {
            MultipartFile multipartFile = ImageSizeUtil.byte2Base64StringFun(img);
            boolean result = uploadImage.checkFileSize(multipartFile.getSize(), 100, "K");
            if (!result) {
                return new Result(10001, "上传个人照片太大，请重新上传", false);
            }
            String imageCom = uploadImage.getImageCom(multipartFile);
            if ("上传失败".equals(imageCom)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(10001, "图片上传失败", false);
            }
            sysAccountMultilevel.setImgUrl(imageCom);
        }
        if (ObjectUtil.isNotEmpty(userName)) {
            sysAccountMultilevel.setUserName(userName);
        }
        if (ObjectUtil.isNotEmpty(phone)) {
            if (!PhoneNumberValidator.isValidPhoneNumber(phone)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(10001, "手机号格式错误！", false);
            }
            sysAccountMultilevel.setPhone(phone);
        }
        if (ObjectUtil.isNotEmpty(workPost)) {
            sysAccountMultilevel.setWorkPost(workPost.toString());
        }
        if (ObjectUtil.isNotEmpty(workLocation)) {
            sysAccountMultilevel.setWorkLocation(workLocation);
        }
        if (ObjectUtil.isNotEmpty(workLocationId)) {
            sysAccountMultilevel.setWorkLocationType(workLocationId);
        }
        if (ObjectUtil.isNotEmpty(workName)) {
            sysAccountMultilevel.setWorkName(workName);
        }

        if (ObjectUtil.isNotEmpty(papersCode)) {
//            if (!IDCardValidator.isValidIDCard(papersCode)) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return new Result(10001, "身份证号格式错误!", false);
//            }
            sysAccountMultilevel.setPapersCode(papersCode);
        }

        accountMultilevelMapper.updateById(sysAccountMultilevel);
        return new Result(ResultCode.SUCCESS, sysAccountMultilevel);
    }

    @Override
    public void printAccount(HttpServletResponse httpServletRequest, Map<String, String> paramsMap) throws Exception {
        String ids = paramsMap.get("ids");
        String[] split = ids.split(",");
        List<AccountVo> list = new ArrayList<>();
        for (String s : split) {
            QueryWrapper<SysAccountMultilevel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", s);
            SysAccountMultilevel sysAccountMultilevel = accountMultilevelMapper.selectOne(queryWrapper);
            QueryWrapper<SysUser> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("id", sysAccountMultilevel.getUserId());
            SysUser user = userMapper.selectOne(queryWrapper1);
            AccountVo accountVo = new AccountVo();
            accountVo.setAccount(sysAccountMultilevel.getAccount());
            accountVo.setPassword(sysAccountMultilevel.getPassword());
            accountVo.setUserName(user.getUserName());
            accountVo.setWorkLocation(user.getWorkLocation());
            accountVo.setUserNum(user.getUserId());
            String job = user.getJob();
            String[] strings = job.split(",");
            String jobName = "";
            for (String string : strings) {
                if ("1".equals(string)) {
                    jobName = jobName + " 场长";
                } else if ("2".equals(string)) {
                    jobName = jobName + " 紧急入场审核员";
                }else if ("3".equals(string)) {
                    jobName = jobName + " 生物安全负责人";
                }else if ("4".equals(string)) {
                    jobName = jobName + " pcr检测人员";
                }else if ("5".equals(string)) {
                    jobName = jobName + " 洗消站点工作人员";
                }else if ("8".equals(string)) {
                    jobName = jobName + " 采样人员";
                }else if ("9".equals(string)) {
                    jobName = jobName + " 洗澡前拍照人员";
                }
            }
            accountVo.setWorkName(jobName);
            list.add(accountVo);
        }
        Print.printAccount(list);

    }

    @Override
    public void updateByUser(SysUser sysUser) {
        Integer id = sysUser.getId();
        SysAccountMultilevel sysAccountMultilevel = accountMultilevelMapper.selectOne(new QueryWrapper<SysAccountMultilevel>().eq("user_id", id));
        if (ObjectUtil.isNotEmpty(sysAccountMultilevel)){
            sysAccountMultilevel.setUserName(sysUser.getUserName());
            if (ObjectUtil.isNotEmpty(sysUser.getJob())){
                sysAccountMultilevel.setJobs(sysUser.getJob());
                sysAccountMultilevel.setType(Integer.parseInt(sysUser.getJob().split(",")[0]));
            }
            sysAccountMultilevel.setWorkLocation(sysUser.getWorkLocation());
            sysAccountMultilevel.setWorkLocationType(sysUser.getWorkLocationType());
            sysAccountMultilevel.setPhone(sysUser.getUserPhone());
            sysAccountMultilevel.setWorkName(sysUser.getDepartment());
            sysAccountMultilevel.setPapersCode(sysUser.getCardNum());
            sysAccountMultilevel.setImgUrl(sysUser.getImgUrl());
//        sysAccountMultilevel.setPapersType(sysUser.getCardType());
            sysAccountMultilevel.setUserId(id);
            accountMultilevelMapper.updateById(sysAccountMultilevel);
        }

    }

}
