package com.hotent.baseInfo.manager.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.query.PageList;
import com.hotent.base.util.StringUtil;
import com.hotent.baseInfo.dao.AuditedUnitDao;
import com.hotent.baseInfo.manager.AuditedUnitManager;
import com.hotent.baseInfo.model.AuditedUnit;
import com.hotent.baseInfo.req.AuditedUnitPageReq;
import com.hotent.baseInfo.resp.AuditedUnitDetailResp;
import com.hotent.constant.BaseConstant;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.manager.UserManager;
import com.hotent.uc.model.User;
import com.hotent.uc.util.ContextUtil;
import com.hotent.util.AreaCodeUtil;
import com.hotent.util.CopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AuditedUnitManagerImpl extends BaseManagerImpl<AuditedUnitDao, AuditedUnit> implements AuditedUnitManager {

    @Autowired
    private UserManager userService;

    @Override
    public List<AuditedUnit> listByRegionAndName( String unitId) {
        QueryWrapper<AuditedUnit> qw = new QueryWrapper<>();
        qw.eq("is_deleted", BaseConstant.NORMAL_STATUS);
        if(StringUtil.isNotEmpty(unitId)){
            qw.ne("unit_id", unitId);
        }
        return this.list(qw);
    }



    @Override
    @Transactional
    public boolean toggleStatus(String unitId, Integer enable) {
        AuditedUnit unit = this.getById(unitId);
        if (unit == null || Boolean.TRUE.equals(unit.getIsDeleted())) {
            throw new RuntimeException("单位不存在");
        }
        unit.setStatus(enable);
        unit.setUpdateTime(LocalDateTime.now());
        unit.setUpdateBy(ContextUtil.getCurrentUser().getAccount());
        return this.updateById(unit);
    }

    @Override
    @Transactional
    public boolean deleteLogical(String unitId) {
        AuditedUnit unit = this.getById(unitId);
        if (unit == null || Boolean.TRUE.equals(unit.getIsDeleted())) {
            return true;
        }
        unit.setIsDeleted(BaseConstant.DELETE_FLAG);
        unit.setUpdateTime(LocalDateTime.now());
        unit.setUpdateBy(ContextUtil.getCurrentUser().getAccount());
        return this.updateById(unit);
    }

    @Override
    @Transactional
    public void createOrUpdate(AuditedUnit unit) {
        this.saveOrUpdate(unit);
    }

    @Override
    public IPage<AuditedUnit> auditUnitPage(AuditedUnitPageReq req) {
        LambdaQueryWrapper<AuditedUnit> qw = new LambdaQueryWrapper<>();
        qw.eq(AuditedUnit::getIsDeleted, BaseConstant.NORMAL_STATUS);
        if(StringUtil.isNotEmpty(req.getAreaCode())){
            qw.eq(AuditedUnit::getAreaCode, req.getAreaCode());
        }
        if(StringUtil.isNotEmpty(req.getUnitName())){
            qw.like(AuditedUnit::getUnitName, req.getUnitName());
        }
        // 创建分页对象
        Page<AuditedUnit> page = new Page<>(req.getPage(), req.getPageSize());
        return this.page(page,qw);
    }

    @Override
    public AuditedUnitDetailResp detail(String unitId) {
        AuditedUnit costAnnualPlan = this.get(unitId);
        if(costAnnualPlan == null){
            return null;
        }
        AuditedUnitDetailResp detailResp = CopyUtil.copy(costAnnualPlan, AuditedUnitDetailResp.class);
        //单位级别：0:省/自治区/直辖市 1:市级 2:县级
        if(ObjectUtil.isNotEmpty(costAnnualPlan.getAreaCode()) && ObjectUtil.isNotEmpty(costAnnualPlan.getAreaLevel())){
            //如果是区县级
            if(BaseConstant.REGION_LEVEL_COUNTY.equals(costAnnualPlan.getAreaLevel())){
                String cityCode = AreaCodeUtil.getCityCode(costAnnualPlan.getAreaCode());
                String provinceCode = AreaCodeUtil.getProvinceCode(cityCode);
                detailResp.setCity(cityCode);
                detailResp.setProvince(provinceCode);
                detailResp.setCounty(costAnnualPlan.getAreaCode());
            }else if(BaseConstant.REGION_LEVEL_CITY.equals(costAnnualPlan.getAreaLevel())){
                String provinceCode = AreaCodeUtil.getProvinceCode(costAnnualPlan.getAreaCode());
                detailResp.setProvince(provinceCode);
                detailResp.setCity(costAnnualPlan.getAreaCode());
            }else if(BaseConstant.REGION_LEVEL_PROVINCE.equals(costAnnualPlan.getAreaLevel())){
                detailResp.setProvince(costAnnualPlan.getAreaCode());
            }else{
                detailResp.setProvince("未知编码");
            }
        }

        return detailResp;
    }

    @Override
    public PageList<AuditedUnit> pageList(AuditedUnitPageReq req) throws Exception {
        IUser iUser = ContextUtil.getCurrentUser();
        User user = userService.getByAccount(iUser.getAccount());
        req.setDataScope(user.getDataScope());
        req.setProvinceCode(user.getProvinceCode());
        req.setCityCode(user.getCityCode());
        req.setCountyCode(user.getCountyCode());
        Page<AuditedUnit> objectPage = new Page<>(req.getPage(),req.getPageSize());
        //Page<CostSurveyTemplate> page =baseMapper.getCostSurveyTemplatePage(objectPage,params);
        Page<AuditedUnit> page =baseMapper.getAuditedUnitPage(objectPage
                ,req.getDataScope()
                ,req.getProvinceCode(),req.getCityCode()
                ,req.getCountyCode()
                ,req.getAreaCode()
                ,req.getUnitName());
        return new PageList<>(page);
    }

    @Override
    public List<AuditedUnit> getList(String unitId) throws Exception {
        IUser iUser = ContextUtil.getCurrentUser();
        User user = userService.getByAccount(iUser.getAccount());
        //qw.eq("is_deleted", BaseConstant.NORMAL_STATUS);
        List<AuditedUnit>  units=baseMapper.getList(unitId
                ,user.getDataScope()
                ,user.getProvinceCode()
                ,user.getCityCode()
                ,user.getCountyCode()
                );
        return units;
    }

    @Override
    public List<AuditedUnit> getByUserAccount(String account) {
        QueryWrapper<AuditedUnit> wrapper = new QueryWrapper<>();
        wrapper.eq("account",account);
        return this.list(wrapper);
    }
}


