package cn.superdesk.uniorder.service.setting.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.dao.entity.setting.UnifiedService;
import cn.superdesk.uniorder.dao.entity.setting.UnifiedServiceExample;
import cn.superdesk.uniorder.dao.entity.unified.UnifiedServiceGroup;
import cn.superdesk.uniorder.dao.mapper.setting.UnifiedServiceMapper;
import cn.superdesk.uniorder.dao.mapper.setting.UnifiedServiceMapperEx;
import cn.superdesk.uniorder.dto.param.setting.UnifiedServicePartGoodsTransportParam;
import cn.superdesk.uniorder.dto.vo._function.select.SelectOptionCommon;
import cn.superdesk.uniorder.dto.vo._function.select.SelectOptionUnifiedService;
import cn.superdesk.uniorder.dto.vo.setting.Level1OrderTypeStruct;
import cn.superdesk.uniorder.dto.vo.setting.UnifiedServiceCacheStruct;
import cn.superdesk.uniorder.service.setting.UnifiedServiceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2021/8/23 下午2:35
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/8/23 下午2:35
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class UnifiedServiceServiceImpl implements UnifiedServiceService {


    @Autowired
    private UnifiedServiceMapper   unifiedServiceMapper;
    @Autowired
    private UnifiedServiceMapperEx unifiedServiceMapperEx;

    /****************************************** extends BaseService 部分 start ******************************************/


    @Override
    public int insertSelective(UnifiedService entity) {

        return unifiedServiceMapper.insertSelective(entity);
    }

    @Override
    public int updateByPrimaryKeySelective(UnifiedService entity) {

        return unifiedServiceMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void deleteObj(Long id) {

        unifiedServiceMapper.deleteByPrimaryKey(id);
    }

    @Override
    public UnifiedService findById(Long id) {

        return unifiedServiceMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<UnifiedService> findByPaging(Map<String, Object> params, Integer pageNo, Integer pageSize) {

        return null;
    }

    @Override
    public List<UnifiedService> findAll(Map<String, Object> queryMap) {

        return unifiedServiceMapperEx.findAll(queryMap);
    }

    /****************************************** extends BaseService 部分   end ******************************************/


    public void addUnifiedService(UnifiedService entity) {
        unifiedServiceMapper.insertSelective(entity);
    }

    public void updateUnifiedService(UnifiedService entity) {
        UnifiedService originEntity = unifiedServiceMapper.selectByPrimaryKey(entity.getId());
//		AssertUtil.notNull(originEntity);
        AnBeanUtils.copy(entity, originEntity);
        unifiedServiceMapper.updateByPrimaryKey(originEntity);
    }

    public void deleteUnifiedService(Long id) {
        unifiedServiceMapper.deleteByPrimaryKey(id);
    }

    public UnifiedService findUnifiedServiceById(Long id) {
        UnifiedService entity = unifiedServiceMapper.selectByPrimaryKey(id);
//		AssertUtil.notNull(entity);
        return entity;
    }

    public R<List<UnifiedService>> pageQuery(Map<String, Object> conditions, int pageNun, int pageSize) {

        // 样例 保留
//		UnifiedService unifiedServiceConditions = BeanUtils.mapToBean(conditions,UnifiedService.class);

        UnifiedServiceExample          example  = new UnifiedServiceExample();
        UnifiedServiceExample.Criteria criteria = example.createCriteria();

        PageHelper.startPage(pageNun, pageSize);
        List<UnifiedService>     resultList = unifiedServiceMapper.selectByExample(example);
        PageInfo<UnifiedService> page       = new PageInfo<UnifiedService>(resultList);
        PageHelper.clearPage();

        return new R<List<UnifiedService>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), resultList);

    }

    /****************************************** 原先的 start ******************************************/

    @Override
    public R<List<UnifiedService>> getPage(Map<String, Object> params, int pageNo, int pageSize) {

        PageHelper.startPage(pageNo, pageSize);
        List<UnifiedService>     result = unifiedServiceMapperEx.findAll(params);
        PageInfo<UnifiedService> page   = new PageInfo<UnifiedService>(result);
        PageHelper.clearPage();
        return new R<List<UnifiedService>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), result);

    }

    @Override
    public List<UnifiedService> getAsService() {
        UnifiedServiceExample example = new UnifiedServiceExample();
        example.createCriteria()
                .andAsServiceEqualTo(1);

        List<UnifiedService> result = unifiedServiceMapper.selectByExample(example);
        return result;
    }

    @Override
    public List<UnifiedService> getAsOrderType() {
        UnifiedServiceExample example = new UnifiedServiceExample();
        example.createCriteria()
                .andAsOrderTypeEqualTo(1);

        List<UnifiedService> resultList = unifiedServiceMapper.selectByExample(example);
        return resultList;
    }


    @Override
    public UnifiedServiceCacheStruct convertForMapAsOrderType() {

        List<UnifiedService> resultList = getAsOrderType();

        List<Level1OrderTypeStruct> orderTypeStructList = new ArrayList<>();

        if (CollUtil.isNotEmpty(resultList)) {

            resultList.forEach(_item -> {

                Level1OrderTypeStruct level1OrderTypeStruct = Level1OrderTypeStruct
                        .builder()
                        .id(_item.getId())
                        .asService(_item.getAsService())
                        .asOrderType(_item.getAsOrderType())

                        .serviceId(_item.getServiceId())
                        .serviceNo(_item.getServiceNo())
                        .serviceName(_item.getServiceName())

                        .goodsTransportFiscalCode(_item.getGoodsTransportFiscalCode())
                        .goodsTransportTaxCode(_item.getGoodsTransportTaxCode())
                        .goodsTransportTaxRate(_item.getGoodsTransportTaxRate())
                        .build();

                List<SelectOptionCommon> orderStateList = new ArrayList<>();
                List<SelectOptionCommon> payTypeList    = new ArrayList<>();

                if (StrUtil.isNotBlank(_item.getOrderStateJson())) {
                    orderStateList = AnJsonUtils.toList(_item.getOrderStateJson(), SelectOptionCommon.class);
                }

                if (StrUtil.isNotBlank(_item.getPayTypeJson())) {
                    payTypeList = AnJsonUtils.toList(_item.getPayTypeJson(), SelectOptionCommon.class);
                }

                level1OrderTypeStruct.setOrderStateList(orderStateList);
                level1OrderTypeStruct.setPayTypeList(payTypeList);

                orderTypeStructList.add(
                        level1OrderTypeStruct
                );
            });

        }
        return UnifiedServiceCacheStruct
                .builder()
                .orderTypeStructList(orderTypeStructList)
                .build();
    }

    @Override
    public List<SelectOptionUnifiedService> getSelectByVirt(Map<String, Object> params) {

        return unifiedServiceMapperEx.getSelectByVirt(params);
    }

    @Override
    public List<UnifiedServiceGroup> findAllByGroup(Map<String, Object> params) {
        return unifiedServiceMapperEx.findAllByGroup(params);
    }

    @Override
    public UnifiedService findByCode(String code) {
        return unifiedServiceMapperEx.findByCode(code);
    }


    @Value(value = "${goods.transport.fiscal_code}")
    private String     GOODS_TRANSPORT_FISCAL_CODE;
    @Value(value = "${goods.transport.tax_code}")
    private String     GOODS_TRANSPORT_TAX_CODE;
    @Value(value = "${goods.transport.tax_rate}")
    private BigDecimal GOODS_TRANSPORT_TAX_RATE;

    /**
     * 取运费税率
     *
     * @param serviceNo
     * @return
     */
    @Override
    public UnifiedServicePartGoodsTransportParam getUnifiedServicePartGoodsTransport(String serviceNo) {

        UnifiedServicePartGoodsTransportParam partGoodsTransportParam;

        UnifiedService unifiedService = unifiedServiceMapperEx.findByServiceNo(serviceNo);

        // 查数据库查不到的情况
        if (null == unifiedService || StrUtil.isBlank(serviceNo)) {

            /****************************************** 查不到就填入配置文件 所以补全 start ******************************************/

            partGoodsTransportParam = new UnifiedServicePartGoodsTransportParam();
            partGoodsTransportParam.setGoodsTransportFiscalCode(GOODS_TRANSPORT_FISCAL_CODE);
            partGoodsTransportParam.setGoodsTransportTaxCode(GOODS_TRANSPORT_TAX_CODE);
            partGoodsTransportParam.setGoodsTransportTaxRate(GOODS_TRANSPORT_TAX_RATE);

            /****************************************** 查不到就填入配置文件 所以补全  end ******************************************/

        }
        // 查数据库查到的情况
        else {

            /****************************************** 查到了也有可能没设置 所以补全 start ******************************************/

            if (null == unifiedService.getGoodsTransportFiscalCode()) {
                unifiedService.setGoodsTransportFiscalCode(GOODS_TRANSPORT_FISCAL_CODE);
            }
            if (null == unifiedService.getGoodsTransportTaxCode()) {
                unifiedService.setGoodsTransportTaxCode(GOODS_TRANSPORT_TAX_CODE);
            }
            if (null == unifiedService.getGoodsTransportTaxRate()) {
                unifiedService.setGoodsTransportTaxRate(GOODS_TRANSPORT_TAX_RATE);
            }

            /****************************************** 查到了也有可能没设置 所以补全   end ******************************************/

            partGoodsTransportParam = AnBeanUtils.copy(unifiedService, UnifiedServicePartGoodsTransportParam.class);

        }

        log.info("取运费税率 service_no {} info = {}", serviceNo, AnJsonUtils.toJson(partGoodsTransportParam));

        return partGoodsTransportParam;

    }

}
