package com.jwipc.inquiry.logic.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jwipc.exception.DaoException;
import com.jwipc.inquiry.convert.InquiryTemplateConvert;
import com.jwipc.inquiry.convert.InquiryTemplateFieldConvert;
import com.jwipc.inquiry.dto.InquiryTemplateDTO;
import com.jwipc.inquiry.dto.InquiryTemplateFieldDTO;
import com.jwipc.inquiry.dto.InquiryTemplateFieldRelationDTO;
import com.jwipc.inquiry.entity.InquiryTemplate;
import com.jwipc.inquiry.entity.InquiryTemplateField;
import com.jwipc.inquiry.entity.InquiryTemplateFieldRelation;
import com.jwipc.inquiry.logic.InquiryTemplateLogic;
import com.jwipc.inquiry.model.po.InquiryTemplateFieldPO;
import com.jwipc.inquiry.model.po.InquiryTemplatePO;
import com.jwipc.inquiry.model.query.InquiryTemplateFieldQuery;
import com.jwipc.inquiry.model.query.InquiryTemplateQuery;
import com.jwipc.inquiry.service.IInquiryTemplateFieldRelationService;
import com.jwipc.inquiry.service.IInquiryTemplateFieldService;
import com.jwipc.inquiry.service.IInquiryTemplateService;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * @author shenyang.ou
 * @date 2024/2/4 19:51
 * @desc 询价模板
 */
@Service
@RequiredArgsConstructor
public class InquiryTemplateLogicImpl implements InquiryTemplateLogic {
    private final IInquiryTemplateService inquiryTemplateService;
    private final IInquiryTemplateFieldService inquiryTemplateFieldService;
    private final IInquiryTemplateFieldRelationService inquiryTemplateFieldRelationService;
    private final InquiryTemplateConvert inquiryTemplateConvert;
    private final InquiryTemplateFieldConvert inquiryTemplateFieldConvert;

    @Override
    public PageView findByPage(InquiryTemplateQuery query) {
        final Page<InquiryTemplate> dbPage = PageUtil.toPage(query);

        List<InquiryTemplatePO> inquiryTemplatePOS = inquiryTemplateService.findPageByQuery(dbPage, query);

        List<InquiryTemplateDTO> inquiryTemplateDTOS = inquiryTemplateConvert.po2DTOList(inquiryTemplatePOS);
        return PageUtil.getPV(inquiryTemplateDTOS, dbPage.getTotal());
    }

    @Override
    public InquiryTemplateDTO getById(Long id) {
        InquiryTemplate inquiryTemplate = inquiryTemplateService.getById(id);
        return inquiryTemplateConvert.entity2Dto(inquiryTemplate);
    }

    /**
     * 获取系统默认字段(新增用)
     *
     * @return 字段
     */
    @Override
    public List<InquiryTemplateFieldDTO> getTemplateField(InquiryTemplateFieldQuery query) {
        List<InquiryTemplateFieldPO> inquiryTemplateFieldPOS = inquiryTemplateFieldService.getTemplateField(query);
        return inquiryTemplateConvert.fieldPo2DTOList(inquiryTemplateFieldPOS);
    }

    /**
     * 根据模板id和模板字段分组获取模板字段(编辑用)
     * @param templateId 模板id
     * @param fieldGroup 模板字段分组；0-基础字段；1-基础扩展；2-阶梯报价；3-自定义扩展字段
     * @return 字段
     */
    @Override
    public List<InquiryTemplateFieldDTO> getFieldByTemplateIdAndFieldGroup(Long templateId,Integer fieldGroup) {
        List<InquiryTemplateFieldPO> inquiryTemplateFieldPOS = inquiryTemplateFieldRelationService.getFieldByTemplateIdAndFieldGroup(templateId,fieldGroup);
        return inquiryTemplateConvert.fieldPo2DTOList(inquiryTemplateFieldPOS);
    }

    /**
     * 根据模板编码和模板字段分组获取模板字段(编辑用)
     *
     * @param templateCode 模板id
     * @param fieldGroup 模板字段分组；0-基础字段；1-基础扩展；2-阶梯报价；3-自定义扩展字段
     * @param supplierLookFlag 供应商显示；0-否；1-是；(null则不查)
     * @return 字段
     */
    @Override
    public List<InquiryTemplateFieldDTO> getFieldByTemplateCodeAndFieldGroup(String templateCode, Integer fieldGroup,Integer supplierLookFlag) {
        List<InquiryTemplateFieldPO> inquiryTemplateFieldPOS = inquiryTemplateFieldRelationService.getFieldByTemplateCodeAndFieldGroup(templateCode,fieldGroup,supplierLookFlag);
        return inquiryTemplateConvert.fieldPo2DTOList(inquiryTemplateFieldPOS);
    }

    @Override
    public void saveOrUpdate(InquiryTemplateDTO param) {
        //保存
        if (param.getId() == null) {
            if (ObjectUtil.isNotNull(inquiryTemplateService.getOne(new LambdaQueryWrapper<InquiryTemplate>().eq(
                    InquiryTemplate::getTemplateCode, param.getTemplateCode()).last(" limit 1")))) {
                throw new DaoException("模板编码已经存在, 请检查");
            }
            param.setCreateTime(LocalDateTime.now());
            param.setCreateUser(Objects.requireNonNull(LoginUtil.getCurrentUser()).getUserId());
        } else {
            if (ObjectUtil.isNotNull(inquiryTemplateService.getOne(new LambdaQueryWrapper<InquiryTemplate>().eq(
                            InquiryTemplate::getTemplateCode, param.getTemplateCode()).ne(InquiryTemplate::getId, param.getId())
                    .last(" limit 1")))) {
                throw new DaoException("模板编码已经存在, 请检查");
            }
            param.setUpdateTime(LocalDateTime.now());
            param.setUpdateUser(Objects.requireNonNull(LoginUtil.getCurrentUser()).getUserId());
            //删除关联字段
            inquiryTemplateFieldRelationService.remove(Wrappers.lambdaQuery(InquiryTemplateFieldRelation.class).eq(InquiryTemplateFieldRelation::getTemplateId,param.getId()));
        }
        InquiryTemplate inquiryTemplate = inquiryTemplateConvert.dto2Entity(param);
        inquiryTemplate.setDeleteFlag(0);
        inquiryTemplateService.saveOrUpdate(inquiryTemplate);
        if (CollectionUtil.isEmpty(param.getFields())){
            throw new DaoException("请配置模板字段, 请检查");
        }
        List<InquiryTemplateFieldRelationDTO> fields = param.getFields();
        fields.forEach(inquiryTemplateFieldRelationDTO -> {
            inquiryTemplateFieldRelationDTO.setTemplateId(inquiryTemplate.getId());
            inquiryTemplateFieldRelationDTO.setCreateTime(LocalDateTime.now());
            inquiryTemplateFieldRelationDTO.setCreateUser(Objects.requireNonNull(LoginUtil.getCurrentUser()).getUserId());
        });
        inquiryTemplateFieldRelationService.saveBatch(inquiryTemplateFieldConvert.dto2EntityList(fields));
    }

    @Override
    public void updateDeleteFlag(Long id) {
        InquiryTemplate inquiryTemplate = new InquiryTemplate();
        inquiryTemplate.setId(id);
        inquiryTemplate.setDeleteFlag(1);
        inquiryTemplateService.updateById(inquiryTemplate);
    }

    /**
     * 根据采购组编码获取询价模板且包含全部采购组
     *
     * @param purchaseGroupCode 采购组编码
     */
    @Override
    public List<InquiryTemplateDTO> getAllListByPurchaseGroupCode(String purchaseGroupCode) {
        List<InquiryTemplatePO> inquiryTemplatePOS = inquiryTemplateService.getAllListByPurchaseGroupCode(purchaseGroupCode);
        return inquiryTemplateConvert.po2DTOList(inquiryTemplatePOS);
    }

    /**
     * 根据模板编码获取供应商显示和编辑字段
     *
     * @param templateCode 模板编码
     * @return 字段
     */
    @Override
    public List<InquiryTemplateFieldDTO> getSupplierFieldByTemplateCode(String templateCode) {
        //查询供应商可见的字段
        List<InquiryTemplateFieldPO> inquiryTemplateFieldPOS = inquiryTemplateFieldRelationService.getFieldByTemplateCodeAndFieldGroup(templateCode,3,1);
        //查询供应商编辑的字段
        List<InquiryTemplateFieldPO> inquiryTemplateFieldSupplierPOS = inquiryTemplateFieldRelationService.getFieldByTemplateCodeAndFieldGroup(templateCode,1,null);
        inquiryTemplateFieldPOS.addAll(inquiryTemplateFieldSupplierPOS);
        return inquiryTemplateConvert.fieldPo2DTOList(inquiryTemplateFieldPOS);
    }

    /**
     * 根据模板编码获取定价显示字段
     *
     * @param templateCode 模板编码
     * @return 字段
     */
    @Override
    public List<InquiryTemplateFieldDTO> getFixFieldByTemplateCode(String templateCode) {
        //查询供应商可见的字段
        List<InquiryTemplateFieldPO> inquiryTemplateFieldPOS = inquiryTemplateFieldRelationService.getFixFieldByTemplateCodeAndFieldGroup(templateCode,1,1);
        return inquiryTemplateConvert.fieldPo2DTOList(inquiryTemplateFieldPOS);
    }

    @Override
    public List<InquiryTemplateDTO> listAll(InquiryTemplateQuery query) {
        List<InquiryTemplatePO> inquiryTemplatePOS = inquiryTemplateService.findPageByQuery(null, query);
        return inquiryTemplateConvert.po2DTOList(inquiryTemplatePOS);
    }
}
