package com.kingtom.shengtai.app.srm.service.impl;

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

import com.kingtom.kirin.app.org.model.OrgPerson;
import com.kingtom.kirin.app.org.model.OrgUnit;
import com.kingtom.kirin.app.org.service.IOrgMemberService;
import com.kingtom.kirin.app.org.service.IOrgPersonService;
import com.kingtom.kirin.app.org.service.IOrgService;
import com.kingtom.kirin.app.space.service.ISpaceFileService;
import com.kingtom.kirin.app.system.model.SystemUser;
import com.kingtom.kirin.app.system.model.SystemUserBO;
import com.kingtom.kirin.app.system.service.ISystemService;
import com.kingtom.kirin.app.system.utils.SystemUtils;
import com.kingtom.kirin.core.common.CommonConst;
import com.kingtom.kirin.core.common.base.service.impl.BaseServiceImpl;
import com.kingtom.kirin.core.common.exception.AppException;
import com.kingtom.kirin.core.common.utils.CollectionUtils;
import com.kingtom.kirin.core.common.utils.IDUtils;
import com.kingtom.kirin.core.common.utils.JsonUtils;
import com.kingtom.kirin.core.resource.ResourceConst;
import com.kingtom.shengtai.app.message.model.MsgSummary;
import com.kingtom.shengtai.app.message.service.IMsgSummaryService;
import com.kingtom.shengtai.app.message.ws.WsSendService;
import com.kingtom.shengtai.app.srm.SrmConst;
import com.kingtom.shengtai.app.srm.dao.ISrmSupplierDao;
import com.kingtom.shengtai.app.srm.model.SrmSupplier;
import com.kingtom.shengtai.app.srm.model.SrmSupplierDO;
import com.kingtom.shengtai.app.srm.service.ISrmSupplierService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.RawQueryCondition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.kingtom.shengtai.app.srm.model.table.SrmSupplierTableDef.SRM_SUPPLIER;

/**
 * 供应商信息表 服务层实现。
 *
 * @author wany
 * @since 2023-12-21
 */
@Service
public class SrmSupplierServiceImpl extends BaseServiceImpl<ISrmSupplierDao, SrmSupplier>
        implements ISrmSupplierService{

    @Autowired
    private ISystemService systemService;

    @Autowired
    private IMsgSummaryService msgSummaryService;

    @Autowired
    private WsSendService wsSendService;

    @Autowired
    private IOrgService orgService;

    @Autowired
    private IOrgMemberService orgMemberService;

    @Autowired
    private IOrgPersonService orgPersonService;

    @Autowired
    private ISpaceFileService spaceFileService;

    @Override
    public SrmSupplierDO create(SrmSupplier entity){
        if(entity.getId() == null){
            entity.setId(IDUtils.newUUID());
        }
        if(StringUtils.isEmpty(entity.getName())){
            throw new AppException("供应商名称为空，新建供应商失败！");
        }
//        if(StringUtils.isEmpty(entity.getType())){
//            throw new AppException("供应商类型为空，新建供应商失败！");
//        }
        if(StringUtils.isEmpty(entity.getPerson())){
            throw new AppException("供应商联系人为空，新建供应商失败！");
        }
        SrmSupplier byPerson = findByPerson(entity.getPerson());
        if(byPerson != null){
            throw new AppException("供应商联系人重复，新建供应商失败！");
        }
        entity.setGmtCreate(new Date());
        entity.setGmtModified(entity.getGmtCreate());
        entity.setSysId(SystemUtils.getCurrentSystemId());
        boolean f = mapper.insert(entity) > 0;
        if(!f){
            throw new AppException("落库出错，新建供应商失败！");
        }
        //文件存储为正式文件
        saveFileFormal(entity);
        return findById(entity.getId());
    }

    private void saveFileFormal(SrmSupplier entity){
        List<String> imageFileIds =
                StringUtils.isEmpty(entity.getImage()) ? null : JsonUtils.toObjectList(entity.getImage(), String.class);
        spaceFileService.doFormalOfReplace(imageFileIds, SrmConst.SRM_SUPPLIER_RESOURCE_KEY, entity.getId(),
                SrmConst.SRM_SUPPLIER_IMAGES);
        spaceFileService.doFormalOfReplace(entity.getBusinessLicense(), SrmConst.SRM_SUPPLIER_RESOURCE_KEY,
                entity.getId(),
                SrmConst.SUPPLIER_BUSINESS_LICENSE);
        List<String> certificateFileIds = StringUtils.isEmpty(entity.getCertificates()) ? null :
                JsonUtils.toObjectList(entity.getCertificates(), String.class);
        spaceFileService.doFormalOfReplace(certificateFileIds, SrmConst.SRM_SUPPLIER_RESOURCE_KEY, entity.getId(),
                SrmConst.SUPPLIER_CERTIFICATES);
    }

    @Override
    public void deleteById(String id){
        if(StringUtils.isEmpty(id)){
            return;
        }
        boolean f = mapper.deleteById(id) > 0;
        if(!f){
            throw new AppException("落库出错，删除供应商失败！");
        }
    }

    @Override
    public void deleteByIds(List<String> ids){
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        boolean f = mapper.deleteBatchByIds(ids) > 0;
        if(!f){
            throw new AppException("落库出错，删除供应商失败！");
        }
    }

    @Override
    public SrmSupplierDO update(SrmSupplier entity){
        if(entity == null || entity.getId() == null){
            throw new AppException("参数错误，更新供应商失败！");
        }
        if(StringUtils.isBlank(entity.getPerson())){
            entity.setPerson(null);
        } else{
            SrmSupplier byPerson = findByPerson(entity.getPerson());
            if(byPerson != null && !byPerson.getId().equals(entity.getId())){
                throw new AppException("供应商联系人重复，更新供应商失败！");
            }
        }
        entity.setGmtModified(new Date());
        boolean f = mapper.update(entity) > 0;
        if(!f){
            throw new AppException("落库出错，更新供应商失败！");
        }
        //文件存储为正式文件
        saveFileFormal(entity);
        return findById(entity.getId());
    }

    @Override
    public SrmSupplierDO findById(String id){
        if(StringUtils.isEmpty(id)){
            return null;
        }
        SrmSupplier srmSupplier = mapper.selectOneById(id);
        if(srmSupplier == null){
            return null;
        }
        SrmSupplierDO build = SrmSupplierDO.builder().supplier(srmSupplier).build();
        if(StringUtils.isNotEmpty(srmSupplier.getPerson())){
            SystemUserBO systemUser = systemService.findSystemUser(srmSupplier.getPerson());
            build.setUser(systemUser.getSystemUser());
        }
        return build;
    }


    @Override
    public SrmSupplier findByPerson(String personId){
        return mapper.selectOneByCondition(SRM_SUPPLIER.PERSON.eq(personId));
    }

    @Override
    public Page<SrmSupplierDO> page(String name, String type, String state, List<String> products, Integer pageNum,
            Integer pageSize){
        products = products == null ? new ArrayList<>() : products;
        QueryCondition condition =
                QueryCondition.createEmpty().and(SRM_SUPPLIER.NAME.like(name).when(StringUtils.isNotEmpty(name)))
                        .and(SRM_SUPPLIER.TYPE.like(type).when(StringUtils.isNotEmpty(type)))
                        .and(SRM_SUPPLIER.STATE.like(state).when(StringUtils.isNotEmpty(state)))
                        .and(new RawQueryCondition(
                                "product::jsonb ??& array['" + StringUtils.join(products, "','") + "']").when(
                                CollectionUtils.isNotEmpty(products)));
        Page<SrmSupplier> paginate = mapper.paginate(pageNum, pageSize, condition);
        if(CollectionUtils.isEmpty(paginate.getRecords())){
            return new Page<>(new ArrayList<>(), pageNum, pageSize, paginate.getTotalRow());
        }
        List<String> personIds =
                paginate.getRecords().stream().map(SrmSupplier::getPerson).collect(Collectors.toList());
        List<SystemUser> users = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(personIds)){
            users = systemService.findSystemUserByIds(personIds);
        }
        Map<String, SystemUser> userMap = users.stream().collect(Collectors.toMap(SystemUser::getId, e -> e));
        List<SrmSupplierDO> collect = paginate.getRecords().stream()
                .map(e -> SrmSupplierDO.builder().supplier(e).user(userMap.get(e.getPerson())).build())
                .collect(Collectors.toList());
        return new Page<>(collect, pageNum, pageSize, paginate.getTotalRow());
    }

    @Override
    public void appeal(String userId, String content){
        MsgSummary msgSummary = new MsgSummary();
        msgSummary.setSender(userId);
        msgSummary.setTitle("供应商评分申诉");
        msgSummary.setType("供应商评分申诉");
        msgSummary.setContent(content);
        OrgUnit defaultUnit = orgService.findDefaultUnit();
        List<String> orgMemberPersonIds = orgMemberService.findOrgMemberPersonIds(defaultUnit.getId());
        List<OrgPerson> people = orgPersonService.findByIds(orgMemberPersonIds);
        List<String> userIds = people.stream().map(OrgPerson::getUserId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(userIds)){
            msgSummaryService.createMsg(msgSummary, userIds);
            wsSendService.sendMsg(userIds, JsonUtils.toJson(msgSummary));
        }
    }

}
