package com.jwipc.sys.logic.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jwipc.exception.DaoException;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.sys.convert.PurchaseOrgConvert;
import com.jwipc.sys.dto.PurchaseOrgDTO;
import com.jwipc.sys.dto.UserPurOrgTreeDTO;
import com.jwipc.sys.entity.PurchaseOrg;
import com.jwipc.sys.entity.UserPurchaseOrg;
import com.jwipc.sys.logic.PurchaseOrgLogic;
import com.jwipc.sys.model.param.PurchaseOrgParam;
import com.jwipc.sys.model.po.PurchaseOrgPO;
import com.jwipc.sys.model.query.PurchaseOrgQuery;
import com.jwipc.sys.service.IPurchaseOrgService;
import com.jwipc.sys.service.IUserPurchaseOrgService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class PurchaseOrgLogicImpl implements PurchaseOrgLogic {
    private final IPurchaseOrgService purchaseOrgService;
    private final PurchaseOrgConvert purchaseOrgConvert;

    private final IUserPurchaseOrgService userPurchaseOrgService;
    @Override
    public PageView findByPage(PurchaseOrgQuery query) {
        final Page<PurchaseOrg> dbPage = PageUtil.toPage(query);

        List<PurchaseOrgPO> purchaseOrgPOS = purchaseOrgService.findPageByQuery(dbPage, query);

        return PageUtil.getPV(purchaseOrgConvert.po2PageListDTO(purchaseOrgPOS), dbPage.getTotal());
    }

    @Override
    public PurchaseOrgDTO getById(Long id) {
        if (id != null) {
            PurchaseOrgPO purchaseOrgPO = purchaseOrgService.getDataById(id);
            return purchaseOrgConvert.po2DTO(purchaseOrgPO);
        }else{
            return new PurchaseOrgDTO();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(PurchaseOrgParam param) {
        //保存
        if (Objects.isNull(param.getId())){

            final LambdaQueryWrapper<PurchaseOrg> resourcesLambdaQueryWrapper = new LambdaQueryWrapper<PurchaseOrg>().eq(
                    PurchaseOrg::getPurchaseOrgCode, param.getPurchaseOrgCode()).last(" limit 1");
            if (ObjectUtil.isNotNull(purchaseOrgService.getOne(resourcesLambdaQueryWrapper))){
                throw new DaoException("采购组织编码重复");
            }

            param.setCreateTime(LocalDateTime.now());


        }else {
            final LambdaQueryWrapper<PurchaseOrg> resourcesLambdaQueryWrapper = new LambdaQueryWrapper<PurchaseOrg>().eq(
                    PurchaseOrg::getPurchaseOrgCode, param.getPurchaseOrgCode()).ne(PurchaseOrg::getId,param.getId()).last(" limit 1");
            if (ObjectUtil.isNotNull(purchaseOrgService.getOne(resourcesLambdaQueryWrapper))){
                throw new DaoException("采购组织编码重复");
            }
            param.setLastUpdateTime(LocalDateTime.now());


        }
        String sapClient = ObjectUtil.isNull(param.getSapClient()) ? "" : param.getSapClient();
        String companyCode = ObjectUtil.isNull(param.getCompanyCode()) ? "" : param.getCompanyCode();
        String purchaseOrgCode = ObjectUtil.isNull(param.getPurchaseOrgCode()) ? "" : param.getPurchaseOrgCode();

        String dataPrimary = sapClient + companyCode + purchaseOrgCode;
        param.setDataPrimary(dataPrimary);
        purchaseOrgService.saveOrUpdate(purchaseOrgConvert.param2Entity(param));
    }

    @Override
    public List<UserPurOrgTreeDTO> getForTree(Long userId) {
        final LambdaQueryWrapper<UserPurchaseOrg> userPurchaseOrgLambdaQueryWrapper =
                new LambdaQueryWrapper<UserPurchaseOrg>().eq(
                        UserPurchaseOrg::getUserId, userId);
        final List<UserPurchaseOrg> userPurchaseOrgs = userPurchaseOrgService.list(userPurchaseOrgLambdaQueryWrapper);
        final List<String> userPurchaseOrgCodes = userPurchaseOrgs.stream().map(UserPurchaseOrg::getPurchaseOrgCode)
                .collect(Collectors.toList());
        final List<PurchaseOrg> list = purchaseOrgService.list();
        UserPurOrgTreeDTO purGroupTreeDTO = new UserPurOrgTreeDTO();

        purGroupTreeDTO.setId(-1L);
        purGroupTreeDTO.setText("采购组织选择");
        purGroupTreeDTO.setState("open");
        purGroupTreeDTO.setLevel("0");
        purGroupTreeDTO.setAttributes("");
        purGroupTreeDTO.setChecked(false);
        purGroupTreeDTO.setChildren(Lists.newArrayList());
        for (PurchaseOrg purchaseOrg : list) {
            UserPurOrgTreeDTO userPurGroupTreeDTO = new UserPurOrgTreeDTO();
            userPurGroupTreeDTO.setId(purchaseOrg.getId());
            userPurGroupTreeDTO.setText(
                    StrUtil.format("({}){}", purchaseOrg.getPurchaseOrgCode(), purchaseOrg.getPurchaseOrgDesc()));
            userPurGroupTreeDTO.setState("open");
            userPurGroupTreeDTO.setLevel("1");
            userPurGroupTreeDTO.setAttributes(purchaseOrg.getPurchaseOrgCode());
            userPurGroupTreeDTO.setChecked(userPurchaseOrgCodes.contains(purchaseOrg.getPurchaseOrgCode()));
            purGroupTreeDTO.getChildren().add(userPurGroupTreeDTO);
        }
        List<UserPurOrgTreeDTO> treeData = Lists.newArrayList();
        treeData.add(purGroupTreeDTO);
        return treeData;
    }
    @Override
    public void remove(String purchaseOrgCode) {
        purchaseOrgService.remove(new LambdaQueryWrapper<PurchaseOrg>().eq(PurchaseOrg::getPurchaseOrgCode, purchaseOrgCode));
    }

    @Override
    public List<PurchaseOrgDTO> listAll(PurchaseOrgQuery query) {
        List<PurchaseOrgPO> purchaseOrgPOS = purchaseOrgService.findPageByQuery(null, query);
        return purchaseOrgConvert.po2PageListDTO(purchaseOrgPOS);
    }
}