package com.ruoyi.xq.job;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.xq.domain.AreaCode;
import com.ruoyi.xq.domain.User;
import com.ruoyi.xq.service.AreaCodeService;
import com.ruoyi.xq.service.UserService;
import com.ruoyi.xq.util.AgeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class JobManager {
    @Autowired
    private UserService userService;
    @Autowired
    private AreaCodeService areaCodeService;

    public void updateAge(){
        int current = 0;
        while (true){
            current++;
            IPage<User> page = new Page<>();
            page.setCurrent(current);
            page.setSize(100);
            IPage<User> userPage = userService.page(page);
            List<User> records = userPage.getRecords();
            if(records.isEmpty()){
                break;
            }
            for (User record : records) {
                if(record.getBirthday() == null){
                    continue;
                }
                User update = new User();
                update.setId(record.getId());
                update.setAge(AgeUtil.getAge(record.getBirthday()));
                userService.updateById(update);
            }
        }
    }

    public void refreshUserAreaCode() {
        int current = 0;
        while (true){
            current++;
            IPage<User> page = new Page<>();
            page.setCurrent(current);
            page.setSize(100);
            IPage<User> userPage = userService.page(page);
            List<User> records = userPage.getRecords();
            if(records.isEmpty()){
                break;
            }
            for (User record : records) {
                boolean updateFlag = false;
                User update = new User();
                update.setId(record.getId());
                if(record.getAddressCode() != null){
                    AreaCode areaCode = areaCodeService.getById(record.getAddressCode());
                    if(areaCode != null){
                        updateFlag = true;
                        update.setAddressName(areaCode.getFullname());
                    }
                }
                if(record.getResidenceCode() != null){
                    AreaCode areaCode = areaCodeService.getById(record.getResidenceCode());
                    if(areaCode != null){
                        updateFlag = true;
                        update.setResidenceName(areaCode.getFullname());
                        update.setResidenceCityCode(areaCode.getCityCode());
                        update.setResidenceCityName(areaCode.getCityName());
                    }
                }
                if(updateFlag){
                    userService.updateById(update);
                }
            }
        }
    }
}
