package cn.iocoder.yudao.module.system.service.biz;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.system.api.bpm.vo.ElderlyInfoReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.DeviceProductRespVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.SupplierInfoPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.SupplierInfoRespVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.SupplierInfoSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.excel.SupplierImportExcelVO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.SupplierInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictTypeDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.SupplierInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.dict.DictDataMapper;
import cn.iocoder.yudao.module.system.dal.mysql.dict.DictTypeMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.starter.annotation.LogRecord;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SUPPLIER_INFO_NOT_EXISTS;
import static cn.iocoder.yudao.module.system.enums.LogRecordConstants.*;

/**
 * @Author: jinyd
 * @CreateTime: 2024/11/21  9:55
 * @Description:
 * @Version: 4.0
 */

@Service
@Validated
public class SupplierInfoServiceImpl implements SupplierInfoService{

    @Resource
    private SupplierInfoMapper infoMapper;

    @Resource
    private DictTypeMapper dictTypeMapper;


    @Resource
    private DictDataMapper dictDataMapper;

    @Override
    @LogRecord(type = SUPPLIER_INFO_TYPE, subType = SUPPLIER_INFO_CREATE_SUB_TYPE, bizNo = "{{#id}}",
            success = SUPPLIER_INFO_CREATE_SUCCESS)
    public Long createInfo(SupplierInfoSaveReqVO createReqVO) {
        // 插入
        SupplierInfoDO info = BeanUtils.toBean(createReqVO, SupplierInfoDO.class);
        infoMapper.insert(info);
        // 返回
        LogRecordContext.putVariable("id", info.getId());
        return info.getId();
    }

    @Override
    @LogRecord(type = SUPPLIER_INFO_TYPE, subType = SUPPLIER_INFO_UPDATE_SUB_TYPE, bizNo = "{{#updateReqVO.id}}",
            success = SUPPLIER_INFO_UPDATE_SUCCESS)
    public void updateInfo(SupplierInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateInfoExists(updateReqVO.getId());
        // 更新
        SupplierInfoDO updateObj = BeanUtils.toBean(updateReqVO, SupplierInfoDO.class);
        infoMapper.updateById(updateObj);
    }

    @Override
    public void deleteInfo(Long id) {
        // 校验存在
        validateInfoExists(id);
        // 删除
        infoMapper.deleteById(id);
    }

    private void validateInfoExists(Long id) {
        if (infoMapper.selectById(id) == null) {
            throw exception(SUPPLIER_INFO_NOT_EXISTS);
        }
    }

    @Override
    public SupplierInfoDO getInfo(Long id) {
        return infoMapper.selectById(id);
    }

    @Override
    public PageResult<SupplierInfoRespVO> getInfoPage(SupplierInfoPageReqVO pageReqVO) {
        Page<DeviceProductRespVO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        List<SupplierInfoRespVO> list = infoMapper.selectSupplierInfoList(page, pageReqVO);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    @Transactional
    @LogRecord(type = SUPPLIER_INFO_TYPE, subType = SUPPLIER_INFO_IMPORT_SUB_TYPE, bizNo = "0",
            success = SUPPLIER_INFO_IMPORT_SUCCESS)
    public Map<String, Object> importSupplierExcel(List<SupplierImportExcelVO> list) {
        List<DictDataDO> dictDataDOS = dictDataMapper.selectList(new LambdaQueryWrapperX<DictDataDO>().eq(DictDataDO::getDictType, "supplier_type"));
        Map<String, String> dictDataMap= new HashMap<>();
        if (dictDataDOS == null || dictDataDOS.size() == 0) return null;
        dictDataDOS.forEach(dictDataDO -> dictDataMap.put(dictDataDO.getLabel(), dictDataDO.getLabel()));
        for (int i = 0; i < list.size(); i++) {
            SupplierImportExcelVO supplierImportExcelVO = list.get(i);
            if (!dictDataMap.containsKey(supplierImportExcelVO.getTypeName())) {
                throw exception(new ErrorCode(1000, "导入失败！第" + (i + 1) + "行，类型名称不存在"));
            }
            SupplierInfoDO supplierInfoDO = infoMapper.selectOne(new LambdaQueryWrapperX<SupplierInfoDO>()
                    .eq(SupplierInfoDO::getSupplierName, supplierImportExcelVO.getSupplierName())
                    .eq(SupplierInfoDO::getTypeName, dictDataMap.get(supplierImportExcelVO.getTypeName())));
            if (null == supplierInfoDO) {
                // 新增
                supplierInfoDO = new SupplierInfoDO();
                supplierInfoDO.setSupplierNumber(supplierImportExcelVO.getSupplierNumber());
                supplierInfoDO.setSupplierName(supplierImportExcelVO.getSupplierName());
                supplierInfoDO.setSupplierNickName(supplierImportExcelVO.getSupplierNickName());
                supplierInfoDO.setTypeName(dictDataMap.get(supplierImportExcelVO.getTypeName()));
                supplierInfoDO.setContacts(supplierImportExcelVO.getContacts());
                supplierInfoDO.setPhone(supplierImportExcelVO.getPhone());
                supplierInfoDO.setAddress(supplierImportExcelVO.getAddress());
                supplierInfoDO.setBusinessScope(supplierImportExcelVO.getBusinessScope());
                supplierInfoDO.setAccountName(supplierImportExcelVO.getAccountName());
                supplierInfoDO.setDepositBank(supplierImportExcelVO.getDepositBank());
                supplierInfoDO.setBankAccount(supplierImportExcelVO.getBankAccount());
                supplierInfoDO.setStatus(supplierImportExcelVO.getStatus());
                supplierInfoDO.setOperator(supplierInfoDO.getOperator());
                supplierInfoDO.setTenantId(TenantContextHolder.getTenantId());
                infoMapper.insert(supplierInfoDO);
            } else {
               // 根据 supplierInfoDO修改 supplierInfoDO
                supplierInfoDO.setSupplierNumber(supplierImportExcelVO.getSupplierNumber());
                supplierInfoDO.setSupplierNickName(supplierImportExcelVO.getSupplierNickName());
                supplierInfoDO.setContacts(supplierImportExcelVO.getContacts());
                supplierInfoDO.setPhone(supplierImportExcelVO.getPhone());
                supplierInfoDO.setAddress(supplierImportExcelVO.getAddress());
                supplierInfoDO.setBusinessScope(supplierImportExcelVO.getBusinessScope());
                supplierInfoDO.setAccountName(supplierImportExcelVO.getAccountName());
                supplierInfoDO.setDepositBank(supplierImportExcelVO.getDepositBank());
                supplierInfoDO.setBankAccount(supplierImportExcelVO.getBankAccount());
                supplierInfoDO.setStatus(supplierImportExcelVO.getStatus());
                supplierInfoDO.setOperator(supplierInfoDO.getOperator());
                infoMapper.updateById(supplierInfoDO);
            }
        }
        list.forEach(supplierImportExcelVO -> {
            if (!dictDataMap.containsKey(supplierImportExcelVO.getTypeName())) {
                throw exception(SUPPLIER_INFO_NOT_EXISTS);
            }
        });
        LogRecordContext.putVariable("size", list.size());
        Map<String,Object> map = new HashMap<>();
        map.put("successCount",list.size());
        map.put("failCount",0);
        map.put("errorList",null);
        return map;
    }

    @Override
    public List<SupplierInfoDO> list(Long[] tenantIds) {
        return infoMapper.selectList(new LambdaQueryWrapperX<SupplierInfoDO>().in(SupplierInfoDO::getTenantId,tenantIds));
    }
}
