package com.pj.tb_company;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.pj.api.consts.FeignFactory;
import com.pj.api.dto.DistrictDTO;
import com.pj.current.satoken.StpUserUtil;
import com.pj.tb_fee_item.TbFeeItem;
import com.pj.tb_fee_item.TbFeeItemService;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Service: tb_company -- 企业管理
 *
 * @author yzs
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbCompanyService extends ServiceImpl<TbCompanyMapper, TbCompany> implements IService<TbCompany> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbCompanyMapper tbCompanyMapper;
    @Resource
    private TbFeeItemService tbFeeItemService;

    /**
     * 增
     */
    void add(TbCompany t) {
        save(t);
        List<DistrictDTO> districtDTOS = FeignFactory.adminInterface.getDistrictList(t.getAddressIds());
        t.setAddress(districtDTOS.stream().map(DistrictDTO::getDistrict)
                .collect(Collectors.joining())).setCreateTime(new Date())
                .setCreateBy(StpUserUtil.getLoginIdAsString())
                .setCreateName(StpUserUtil.getPCLoginInfo().getLoginName());
        updateById(t);
    }

    /**
     * 删
     */
    void delete(Long id) {
        List<TbFeeItem> feeItems = tbFeeItemService.findByCompanyId(id);
        if (!feeItems.isEmpty()){
            feeItems.forEach(tbFeeItem -> tbFeeItem.setCompanyId("").setCompanyName(""));
            tbFeeItemService.updateBatchById(feeItems);
        }
        removeById(id);
    }

    /**
     * 改
     */
    void update(TbCompany t) {
        updateById(t);
        List<DistrictDTO> districtDTOS = FeignFactory.adminInterface.getDistrictList(t.getAddressIds());
        t.setAddress(districtDTOS.stream().map(DistrictDTO::getDistrict)
                .collect(Collectors.joining())).setUpdateTime(new Date())
                .setUpdateBy(StpUserUtil.getLoginIdAsString())
                .setUpdateName(StpUserUtil.getPCLoginInfo().getLoginName());
        updateById(t);

    }

    /**
     * 查
     */
    TbCompany getById(Long id) {
        return super.getById(id);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    List<TbCompany> getList(SoMap so) {
        return tbCompanyMapper.getList(so);
    }


}
