package com.wgb.system.service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wgb.system.service.component.ExcelUtils;
import com.wgb.system.service.constant.SysConstant;
import com.wgb.system.service.domain.mapper.RegionMapper;
import com.wgb.system.service.domain.mapper.UserEnterpriseMapper;
import com.wgb.system.service.domain.mapper.UserMapper;
import com.wgb.system.service.domain.model.Region;
import com.wgb.system.service.domain.model.User;
import com.wgb.system.service.domain.model.UserEnterprise;
import com.wgb.system.service.domain.request.UserEnterpriseList;
import com.wgb.system.service.domain.request.UserList;
import com.wgb.system.service.domain.response.LayuiTableResponse;
import com.wgb.system.service.domain.response.VerificationOfLicenceResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserService extends ServiceBase{

    private final UserMapper userMapper;
    private final RegionMapper regionMapper;
    private final UserEnterpriseMapper userEnterpriseMapper;
    private final RedisTemplate<String,Object> redisTemplate;

    @Value("${redis.map.layer.val}")
    private String regionLayer;

    @Value("${sys.img.file}")
    private String imageFile;

    @Value("${sys.img.url}")
    private String imageUrl;

    public UserService(UserMapper userMapper,RegionMapper regionMapper,UserEnterpriseMapper userEnterpriseMapper,RedisTemplate<String,Object> redisTemplate) {
        this.userMapper= userMapper;
        this.regionMapper=regionMapper;
        this.userEnterpriseMapper=userEnterpriseMapper;
        this.redisTemplate=redisTemplate;
    }

    public LayuiTableResponse getList(UserList userList){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        if (userList.getRegionId()!=null){
            queryWrapper.lambda().like(User::getServicesAreaId,userList.getRegionId());
        }else if (userList.getMaster()!=null){
            queryWrapper.lambda().like(User::getMaster,userList.getMaster());
        }else if (StringUtils.isNoneEmpty(userList.getQueryBusinessRegion())){
            Region region= (Region) redisTemplate.opsForValue().get(regionLayer+userList.getQueryBusinessRegion());
            if (region!=null){
                queryWrapper.lambda().like(User::getAreaId,region.getId());
            }else{
                Region region1= regionMapper.selectOne(new QueryWrapper<Region>().lambda().eq(Region::getRegionName,userList.getQueryBusinessRegion()));
                handlerRegion(region1,queryWrapper);
            }
        }else if(StringUtils.isNoneEmpty(userList.getQueryUserName())){
            queryWrapper.lambda().like(User::getName,userList.getQueryUserName());
        }
        if(StringUtils.isNoneEmpty(userList.getQueryUserPhone())){
            queryWrapper.lambda().like(User::getUserCellphone,userList.getQueryUserPhone());
        }
        IPage<User> iPage=new Page<>(userList.getPage(),userList.getLimit());
        IPage<User> pageList= userMapper.selectPage(iPage,queryWrapper);
        return new LayuiTableResponse(0,"",pageList.getTotal(),pageList.getRecords());
    }

    public void uploadUserFile(MultipartFile file)throws Exception{
        List<Map<String, Object>> excel = ExcelUtils.read(file.getInputStream());
        List<List<String>> data = excel.get(0) == null ? null : (List<List<String>>) excel.get(0).get("data");
        Map<String,Region>map=getRegionMap();
        data.remove(0);
        Pattern p = Pattern.compile("^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\\d{8})$");
        data.stream().filter(i->{
            Matcher m = p.matcher(i.get(1));
            if(!m.find()) {
                return false;
            }
            return i==null?false:true;
        })
        .forEach(i->{
            List<Long> areaList=new ArrayList<>();
            String[] servicesAreas = i.get(8).split(",");
            for (String area:servicesAreas){
                Region region= map.get(area);
                if (region!=null){
                    areaList.add(region.getId());
                }
            }
            userMapper.insert(new User(
                    SysConstant.COMPONENT_NAME+LocalDate.now().getYear()+LocalDate.now().getMonthValue()+LocalDate.now().getDayOfMonth()+RandomStringUtils.random(4, false, true),
                    i.get(0),
                    i.get(1),
                    map.get(i.get(2))!=null?map.get(i.get(2)).getId():0,
                    map.get(i.get(3))!=null?map.get(i.get(2)).getId():0,
                    map.get(i.get(4))!=null?map.get(i.get(2)).getId():0,
                    i.get(5),
                    1,
                    i.get(6).equals(SysConstant.IS_TEAM)?1:0,
                    Integer.valueOf(i.get(7)),
                    StringUtil.join(areaList.toArray(),","),
                    1,
                    i.get(9),
                    LocalDateTime.now().toString()
            ));
        });
    }

    public Map<String,Region> getRegionMap(){
        List<Region> regionList= regionMapper.selectList(null);
        Map<String,Region>map=new HashMap<>();
        regionList.forEach(i->{
            map.put(i.getRegionName(),i);
        });
        return map;
    }

    public VerificationOfLicenceResponse verificationOfLicence(String userNo){
        QueryWrapper<UserEnterprise> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEnterprise::getUserNo,userNo);
        UserEnterprise enterprise= userEnterpriseMapper.selectOne(queryWrapper);
        if (enterprise==null){
            return new VerificationOfLicenceResponse(SysConstant.LICENCE_NO_RECORD_STATE);
        }
        switch (enterprise.getState()){
            case 0:return new VerificationOfLicenceResponse(SysConstant.LICENCE_PENDING_REVIEW_STATE);
            case 1:return new VerificationOfLicenceResponse(SysConstant.LICENCE_ADOPT_STATE);
            case 2:return new VerificationOfLicenceResponse(SysConstant.LICENCE_PASS_STATE,enterprise.getRemarks());
        }
        return null;
    }


    public void saveLicence(UserEnterprise userEnterprise,MultipartFile licenseImage)throws Exception{
        QueryWrapper<UserEnterprise> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEnterprise::getUserNo,userEnterprise.getUserNo());
        UserEnterprise enterprise= userEnterpriseMapper.selectOne(queryWrapper);
        if (enterprise!=null&&enterprise.getState().equals(2)){
            userEnterpriseMapper.deleteById(enterprise.getId());
        }
        handlerLicence(enterprise);

        if (licenseImage != null && !licenseImage.isEmpty()) {
            String prefix=licenseImage.getOriginalFilename().substring(licenseImage.getOriginalFilename().lastIndexOf(".")+1);
            String picPath = imageFile+ File.separator +LocalDate.now().toString().replaceAll("-","")+RandomStringUtils.random(4, false, true)+"."+prefix;
            FileUtils.writeByteArrayToFile(new File(picPath), licenseImage.getBytes());
            userEnterprise.setLicenseImage(imageUrl+picPath);
        }else{
            handlerLicenceImage();
        }
        userEnterpriseMapper.insert(userEnterprise);
    }

    private QueryWrapper<User> handlerRegion(Region region,QueryWrapper<User> queryWrapper){
        if (region!=null) {
            queryWrapper.lambda().like(User::getAreaId, region.getId());
        }
        return queryWrapper;
    }


    public LayuiTableResponse userEnterpriseList(UserEnterpriseList request){
        QueryWrapper<UserEnterprise> wrapper=new QueryWrapper<>();
        IPage<UserEnterprise> iPage=new Page<>(request.getPage(),request.getLimit());
        IPage<UserEnterprise> pageList= userEnterpriseMapper.selectPage(iPage,wrapper);
        return new LayuiTableResponse(0,"",pageList.getTotal(),pageList.getRecords());
    }
}
