package com.fjhx.service.customer.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.entity.customer.CustomerInfo;
import com.fjhx.mapper.customer.CustomerInfoMapper;
import com.fjhx.params.customer.CustomerInfoEx;
import com.fjhx.params.customer.CustomerInfoVo;
import com.fjhx.service.customer.CustomerInfoService;
import com.fjhx.uitl.code.CodeEnum;
import com.fjhx.utils.FileClientUtil;
import com.fjhx.utils.PageUtil;
import com.fjhx.utils.RegionClientUtil;
import com.fjhx.utils.wrapperUtil.IWrapper;
import com.fjhx.utils.wrapperUtil.KeywordData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>
 * 客户 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-12-02
 */
@Service
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Override
    public Page<CustomerInfoEx> getPage(Map<String, Object> condition) {

        IWrapper<CustomerInfo> wrapper = IWrapper.getWrapper(condition);
        wrapper.keyword(new KeywordData(CustomerInfo::getName), new KeywordData(CustomerInfo::getCode))
                .like(CustomerInfo::getName)
                .like(CustomerInfo::getCode)
                .eq(CustomerInfo::getCountryId)
                .eq(CustomerInfo::getProvinceId)
                .eq(CustomerInfo::getCityId);

        Page<CustomerInfo> itemPage = page(condition, wrapper);

        // 复制分页信息
        Page<CustomerInfoEx> page = PageUtil.copyPage(itemPage, CustomerInfoEx.class);

        // 赋值地理位置信息
        RegionClientUtil.setEntityRegionName(page.getRecords());

        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(CustomerInfoVo customerInfoVo) {
        synchronized (this) {
            customerInfoVo.setCode(CodeEnum.CUSTOMER.getCode(customerInfoVo.getCode()));
            save(customerInfoVo);
        }

        FileClientUtil.bindingFile(customerInfoVo.getId(), customerInfoVo.getFileInfoList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(CustomerInfoVo customerInfoVo) {
        updateById(customerInfoVo);
        FileClientUtil.againBindingFile(customerInfoVo.getId(), customerInfoVo.getFileInfoList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(CustomerInfoVo customerInfoVo) {
        removeById(customerInfoVo.getId());
        FileClientUtil.relieveBindingFile(customerInfoVo.getId());
    }

}
