package com.huimv.env.admin.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.huimv.env.admin.common.token.TokenSign;
import com.huimv.env.admin.common.utils.*;
import com.huimv.env.admin.entity.SysAccountMultilevel;
import com.huimv.env.admin.mapper.SysAccountMultilevelMapper;
import com.huimv.env.admin.service.ISysAccountMultilevelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-06
 */
@Service
public class SysAccountMultilevelServiceImpl extends ServiceImpl<SysAccountMultilevelMapper, SysAccountMultilevel> implements ISysAccountMultilevelService {

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

    @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());
        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)){
            if (uploadImage.getImageCom(img).equals("上传失败")) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(10001,"图片上传失败",false);
            }
            sysAccountMultilevel.setImgUrl(uploadImage.getImageCom(img));
        }
        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(papersType)){
            if (papersType.equals("0")){
                if (!IDCardValidator.isValidIDCard(papersCode)){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return new Result(10001,"身份证号格式错误!",false);
                }
            }
            sysAccountMultilevel.setPapersType(papersType);
            sysAccountMultilevel.setPapersCode(papersCode);
        }
        accountMultilevelMapper.updateById(sysAccountMultilevel);
        return new Result(ResultCode.SUCCESS,sysAccountMultilevel);
    }
}
