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.conditions.update.UpdateWrapper;
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.utils.Print;
import com.huimv.receive.common.utils.Result;
import com.huimv.receive.common.utils.ResultCode;
import com.huimv.receive.common.utils.UploadImage;
import com.huimv.receive.entity.BaseLocation;
import com.huimv.receive.entity.Farm;
import com.huimv.receive.entity.SysAccountMultilevel;
import com.huimv.receive.entity.SysUser;
import com.huimv.receive.entity.pojo.UserPagePojo;
import com.huimv.receive.entity.vo.UserAccountVo;
import com.huimv.receive.entity.vo.UserAgeAndGender;
import com.huimv.receive.entity.vo.UserJob;
import com.huimv.receive.mapper.*;
import com.huimv.receive.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-09-04
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private BaseLocationMapper baseLocationMapper;
    @Autowired
    private FarmMapper farmMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysAccountMultilevelMapper sysAccountMultilevelMapper;

    @Autowired
    private UploadImage uploadImage;

    @Autowired
    private ExistMapper  existMapper;

    @Override
    public Result pageAll(UserPagePojo userPagePojo) {
        Integer pageNum = userPagePojo.getPageNum();
        Integer pageSize = userPagePojo.getPageSize();
        Integer job = userPagePojo.getJob();
        Integer workLocationType = userPagePojo.getWorkLocationType();
        String workLocation = userPagePojo.getWorkLocation();
        Integer gender = userPagePojo.getGender();
        String farmId = userPagePojo.getFarmId();
        String searchStr = userPagePojo.getSearchStr();

        if (checkFarm(farmId))
           return new Result(10001,"牧场信息为空",false);

        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (ObjectUtil.isEmpty(pageNum) || pageNum<1)
            pageNum = 1;
        if (ObjectUtil.isEmpty(pageSize) || pageSize<1 )
            pageSize = 10;
        wrapper.eq("farm_id",farmId);
        wrapper.eq(ObjectUtil.isNotEmpty(job),"job",job);
        wrapper.eq(ObjectUtil.isNotEmpty(workLocation),"work_location",workLocation);
        wrapper.eq(ObjectUtil.isNotEmpty(workLocationType),"work_location_type",workLocationType);
        wrapper.eq(ObjectUtil.isNotEmpty(gender),"gender",gender);
        if (StringUtils.isNotBlank(searchStr))
            wrapper.and(i -> i.like("user_name",searchStr).or().like("user_phone",searchStr));
        wrapper.orderByDesc("id");
        IPage<SysUser> page = this.page(new Page<>(pageNum, pageSize), wrapper);
        return new Result(ResultCode.SUCCESS,page);

    }

    @Override
    public Result listWorkLocation(Map map) {
        String farmId = (String)map.get("farmId");
        if (checkFarm(farmId)){
            return new Result(10001,"牧场信息为空",false);
        }else {
            return new Result(ResultCode.SUCCESS,baseLocationMapper.selectList(new QueryWrapper<BaseLocation>().like("farm_ids",farmId)));
        }
      }

    @Override
    public Result pageAccount(UserPagePojo userPagePojo) {
        Integer pageNum = userPagePojo.getPageNum();
        Integer pageSize = userPagePojo.getPageSize();
        Integer job = userPagePojo.getJob();
        Integer gender = userPagePojo.getGender();
        Integer workLocationType = userPagePojo.getWorkLocationType();
        String workLocation = userPagePojo.getWorkLocation();
        String farmId = userPagePojo.getFarmId();
        String searchStr = userPagePojo.getSearchStr();


        if (checkFarm(farmId))
            return new Result(10001,"牧场信息为空",false);
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (ObjectUtil.isEmpty(pageNum) || pageNum<1)
            pageNum = 1;
        if (ObjectUtil.isEmpty(pageSize) || pageSize<1 )
            pageSize = 10;
//        wrapper.eq("farm_id",farmId);
        wrapper.eq(ObjectUtil.isNotEmpty(job),"job",job);
        wrapper.eq(ObjectUtil.isNotEmpty(workLocation),"work_location",workLocation);
        wrapper.eq(ObjectUtil.isNotEmpty(workLocationType),"work_location_type",workLocationType);
        wrapper.eq(ObjectUtil.isNotEmpty(gender),"gender",gender);
        if (StringUtils.isNotBlank(searchStr))
            wrapper.and(i -> i.like("sys_user.user_name",searchStr).or().like("sys_user.user_id",searchStr));

        Page<UserAccountVo> userAccountVoPage = new Page<>(pageNum,pageSize);
        IPage<UserAccountVo> userAccountVoIPage =  userMapper.pageAccount(userAccountVoPage,wrapper,farmId);
        return new Result(ResultCode.SUCCESS,userAccountVoIPage);
    }

    @Override
    public Result addAccount(Map<String, Object> map) {
        Integer id = (Integer)map.get("id");
        String account = (String)map.get("account");
        String password = (String)map.get("password");

        SysUser sysUser = this.getById(id);
        Integer countAccount = sysAccountMultilevelMapper.selectCount(new QueryWrapper<SysAccountMultilevel>().eq("account",account).ne("type",7));
        if (countAccount >0){
            return new Result(10001,"该账号已存在",false);
        }
        Integer countUser = sysAccountMultilevelMapper.selectCount(new QueryWrapper<SysAccountMultilevel>().eq("user_id",id));
        if (countUser >0){
            return new Result(10001,"该用户已绑定账号",false);
        }
        SysAccountMultilevel sysAccountMultilevel = new SysAccountMultilevel();
        sysAccountMultilevel.setAccount(account);
        sysAccountMultilevel.setPassword(password);
        sysAccountMultilevel.setUserName(sysUser.getUserName());
        sysAccountMultilevel.setAccountStatus(1);
        sysAccountMultilevel.setFarmId(Integer.parseInt(sysUser.getFarmId()));
        sysAccountMultilevel.setFarmIds(sysUser.getFarmId());
        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.setLastFarmId(Integer.parseInt(sysUser.getFarmId()));
        sysAccountMultilevel.setPid(0);
        sysAccountMultilevel.setPids("");
        sysAccountMultilevel.setImgUrl(sysUser.getImgUrl());
//        sysAccountMultilevel.setPapersType(sysUser.getCardType());
        sysAccountMultilevel.setUserId(id);
        sysAccountMultilevelMapper.insert(sysAccountMultilevel);
        return new Result(10000,"添加成功",true);
    }

    @Override
    public Result list(Map map) {
        String farmId = (String)map.get("farmId");
        if (checkFarm(farmId))
            return new Result(10001,"牧场信息为空",false);
        return new Result(ResultCode.SUCCESS,this.list(new QueryWrapper<SysUser>().eq("farm_id",farmId)));
    }

    @Override
    public Result updateAccount(Map<String, Object> map) {
        Integer id = (Integer)map.get("id");
        String account = (String)map.get("account");
        String password = (String)map.get("password");
        Integer countAccount = sysAccountMultilevelMapper.selectCount(new QueryWrapper<SysAccountMultilevel>().eq("account",account).ne("type",7));
        if (countAccount >1){
            return new Result(10001,"改账号已存在",false);
        }
        SysAccountMultilevel sysAccountMultilevel = new SysAccountMultilevel();
        sysAccountMultilevel.setAccount(account);
        sysAccountMultilevel.setPassword(password);
        sysAccountMultilevelMapper.update(sysAccountMultilevel,new UpdateWrapper<SysAccountMultilevel>().eq("user_id",id));
        return new Result(10000,"修改成功",true);
    }

    @Override
    public void printUser(HttpServletResponse httpServletRequest, Map<String, String> paramsMap) throws Exception {
        String ids = paramsMap.get("ids");
        String[] split = ids.split(",");
        List<SysUser> list = new ArrayList<>();
        for (String s : split) {
            SysUser admission = userMapper.selectById(s);
            list.add(admission);
        }
        Print.printUser(list);
    }

    @Override
    public Result uploadUserImg(MultipartFile imgUrl, Integer id) throws IOException {
        String imageCom = uploadImage.getImageCom(imgUrl);
        if (ObjectUtil.isNotEmpty(imgUrl)) {
            if (imageCom.equals("上传失败")) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(10001, "图片上传失败", false);
            }

        }
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        sysUser.setImgUrl(imageCom);
        userMapper.updateById(sysUser);

        SysAccountMultilevel sysAccountMultilevel = new SysAccountMultilevel();
        sysAccountMultilevel.setImgUrl(imageCom);
        sysAccountMultilevelMapper.update(sysAccountMultilevel,new UpdateWrapper<SysAccountMultilevel>().eq("user_id",id));
        return new Result(10000,"修改成功",true);

    }

    @Override
    public Result removeAccount(Map<String, String> map) {
        String ids = map.get("ids");
        sysAccountMultilevelMapper.delete(new QueryWrapper<SysAccountMultilevel>().in("user_id", Arrays.asList(ids.split(","))));
        return new Result(10000,"删除成功",true);

    }

    @Override
    public Result userAgeAndGender(Map<String, String> map) {
        String farmId = map.get("farmId");
        if (checkFarm(farmId))
            return new Result(10001,"牧场信息为空",false);
        List<UserAgeAndGender>  userAgeAndGenders=  userMapper.userAgeAndGender(farmId);
        return new Result(ResultCode.SUCCESS,userAgeAndGenders);
    }

    @Override
    public Result userJob(Map<String, String> map) {
        String farmId = map.get("farmId");
        if (checkFarm(farmId))
            return new Result(10001,"牧场信息为空",false);
        List<UserJob>  userJobs=  userMapper.userJob(farmId);
        return new Result(ResultCode.SUCCESS,userJobs);

    }

    private boolean checkFarm(String farmId){
        if (StringUtils.isBlank(farmId) )
            return true;
        Farm byId = farmMapper.selectById(farmId);
        if (ObjectUtil.isEmpty(byId))
            return true;
        return false;
    }
}
