package com.kmall.admin.service.impl;

import com.google.common.collect.ImmutableBiMap;
import com.kmall.admin.dao.ExportExceptionDataDao;
import com.kmall.admin.dao.MerchDao;
import com.kmall.admin.dao.StoreDao;
import com.kmall.admin.dao.ThirdMerchantBizDao;
import com.kmall.admin.dto.StoreDto;
import com.kmall.admin.dto.StoreIdDto;
import com.kmall.admin.entity.*;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.admin.service.StoreService;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.MapBeanUtil;
import com.kmall.common.utils.R;
import com.kmall.common.utils.RRException;
import com.kmall.common.utils.ValidatorUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * Service实现类
 *
 * @author Scott
 * @email
 * @date 2017-12-02 00:53:32
 */
@Service("storeService")
public class StoreServiceImpl implements StoreService {
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private MerchDao merchDao;
    @Autowired
    private ThirdMerchantBizDao thirdMerchantBizDao;
    @Autowired
    private ExportExceptionDataDao exportExceptionDataDao;

    @Override
    public StoreEntity queryObject(Integer id) {
        return storeDao.queryObject(id);
    }

    @Override
    public List<StoreEntity> queryList(Map<String, Object> map) {
        return storeDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return storeDao.queryTotal(map);
    }

    @Override
    public int save(StoreEntity store) {
        store.setStoreName(store.getStoreName().trim());
        if(StringUtils.isNotEmpty(store.getMerchSn())){
            MerchEntity merchEntity = merchDao.findByMerchSn(store.getMerchSn());
            if(merchEntity != null){
                store.setMerchName(merchEntity.getMerchName());
            }else{
                throw new RRException("商户编号不存在，请先维护用户商户编号信息再来操作");
            }
        }else{
            throw new RRException("商户编号不能为空");
        }
        if(StringUtils.isNotEmpty(store.getThirdPartyMerchCode())){
            ThirdMerchantBizEntity thirdMerchantBizEntity = thirdMerchantBizDao.getThirdMerchangByCode(store.getThirdPartyMerchCode());
            if(thirdMerchantBizEntity != null){
                store.setThirdPartyMerchName(thirdMerchantBizEntity.getThirdPartyMerchName());
            }else{
                throw new RRException("第三方商户编号【"+store.getThirdPartyMerchCode()+"】不存在，请先维护第三方商户信息再来操作");
            }
        }else{
            throw new RRException("第三方商户编号不能为空");
        }

        StoreEntity storeEntity = storeDao.queryObjectByName(store.getStoreName());
        if(storeEntity != null){
            throw new RRException("门店名称已存在");
        }
//        if(StringUtils.isNotEmpty(String.valueOf(store.getDistId()))) {
//            StoreEntity storeEntityByDistId = storeDao.queryObjectByDistId(store.getDistId());
//            if (storeEntityByDistId != null) {
//                throw new RRException("该分销商已与其他门店建立关系，请重新选择");
//            }
//        }
        return storeDao.save(store);
    }

    @Override
    public int update(StoreEntity store) {
        store.setStoreName(store.getStoreName().trim());
        if(StringUtils.isEmpty(store.getMerchSn())){
            throw new RRException("商户编号不能为空");
        }else{
            MerchEntity merchEntity = merchDao.findByMerchSn(store.getMerchSn());
            if(merchEntity != null){
                store.setMerchName(merchEntity.getMerchName());
            }else{
                throw new RRException("商户编号不存在，请先维护用户商户编号信息再来操作");
            }
        }
        if(StringUtils.isEmpty(store.getThirdPartyMerchCode())){
            throw new RRException("第三方商户编号不能为空");
        }else{
            ThirdMerchantBizEntity thirdMerchantBizEntity = thirdMerchantBizDao.getThirdMerchangByCode(store.getThirdPartyMerchCode());
            if(thirdMerchantBizEntity != null){
                store.setThirdPartyMerchName(thirdMerchantBizEntity.getThirdPartyMerchName());
            }else{
                throw new RRException("第三方商户编号【"+store.getThirdPartyMerchCode()+"】不存在，请先维护第三方商户信息再来操作");
            }
        }

        StoreEntity storeEntity = storeDao.queryObjectByName(store.getStoreName());
        if(storeEntity != null && !storeEntity.getId().equals(store.getId())){
            throw new RRException("门店名称已存在");
        }
//        if(StringUtils.isNotEmpty(String.valueOf(store.getDistId()))) {
//            StoreEntity storeEntityByDistId = storeDao.queryObjectByDistId(store.getDistId());
//            if (storeEntityByDistId != null && !storeEntityByDistId.getId().equals(store.getId())) {
//                throw new RRException("该分销商已与其他门店建立关系，请重新选择");
//            }
//        }
        return storeDao.update(store);
    }

    @Override
    public int delete(Integer id) {
        return storeDao.delete(id);
    }

    @Override
    public int deleteBatch(Integer[] ids) {
        return storeDao.deleteBatch(ids);
    }

    @Override
    public int uploadExcel(List<StoreDto> storeDtoList){
        SysUserEntity user = ShiroUtils.getUserEntity();
        String merchSn = user.getMerchSn();
        boolean isFail = false;
        List<String> failMerchSnList = new ArrayList<>(), failThirdMerchSnList = new ArrayList<>(),
                failAgreementTypeList = new ArrayList<>(), failHaveNameList = new ArrayList<>();
        if (storeDtoList != null && storeDtoList.size() > 0) {
            for (int i = 0; i < storeDtoList.size(); i++) {
                StoreDto storeDto = storeDtoList.get(i);
                StoreEntity storeEntity = new StoreEntity();
                Map<String, Object> valideDate = MapBeanUtil.fromObject(storeDto);
                ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
                builder.put("merchSn", "商户编码");
                builder.put("storeName", "门店名称");
                builder.put("storeNumber", "门店编码");
                builder.put("storeAddress", "门店地址");
                builder.put("provinceName", "省");
                builder.put("cityName", "市");
                builder.put("countyName", "区");
                builder.put("latitude", "纬度");
                builder.put("longitude", "经度");
                builder.put("thirdPartyMerchCode", "第三方商户代码");
                builder.put("exprAgreementType", "第三方商户快递协议类型");
                R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                if (Integer.valueOf(r.get("code").toString()) != 0) {
                    throw new RRException(r.get("msg").toString());
                }
                MerchEntity merchEntity = merchDao.findByMerchSn(storeDto.getMerchSn());
                if(merchEntity != null){
                    storeEntity.setMerchSn(merchEntity.getMerchSn());
                    storeEntity.setMerchName(merchEntity.getMerchName());
                }else{//商户不存在
                    isFail = true;
                    failMerchSnList.add(storeDto.getStoreName().trim());
                }
                ThirdMerchantBizEntity thirdMerchantBizEntity = thirdMerchantBizDao.getThirdMerchangByCode(storeDto.getThirdPartyMerchCode());
                if(thirdMerchantBizEntity != null){
                    storeEntity.setThirdPartyMerchCode(thirdMerchantBizEntity.getThirdPartyMerchCode());
                    storeEntity.setThirdPartyMerchName(thirdMerchantBizEntity.getThirdPartyMerchName());
                }else{//第三方商户不存在
                    isFail = true;
                    failThirdMerchSnList.add(storeDto.getThirdPartyMerchCode());
                }

                StoreEntity store = storeDao.queryObjectByName(storeDto.getStoreName().trim());
                if(store != null){
                    isFail = true;
                    failHaveNameList.add(storeDto.getStoreName().trim());
                }
                if(!storeDto.getExprAgreementType().equalsIgnoreCase(Dict.exprAgreementType.item_00.getItem()) &&
                        !storeDto.getExprAgreementType().equalsIgnoreCase(Dict.exprAgreementType.item_11.getItem())){
                    isFail = true;
                    failAgreementTypeList.add(storeDto.getStoreName().trim());
                }
                storeEntity.setStoreName(storeDto.getStoreName().trim());
                storeEntity.setStoreNumber(storeDto.getStoreNumber().trim());
                storeEntity.setStoreAddress(storeDto.getStoreAddress().trim());
                storeEntity.setCountyName(storeDto.getCountyName().trim());
                storeEntity.setCityName(storeDto.getCityName().trim());
                storeEntity.setProvinceName(storeDto.getProvinceName().trim());
                storeEntity.setLatitude(BigDecimal.valueOf(storeDto.getLatitude()));
                storeEntity.setLongitude(BigDecimal.valueOf(storeDto.getLatitude()));
                storeEntity.setExprAgreementType(storeDto.getExprAgreementType().trim());
                storeEntity.setCreaterSn(user.getUsername());
                storeEntity.setCreateTime(new Date());
                storeEntity.setModerSn(user.getUsername());
                storeEntity.setModTime(new Date());
                storeEntity.setIsValid(Dict.isValid.item_0.getItem());

                if(!isFail){
                    storeDao.save(storeEntity);
                }
            }
            ExportExceptionDataEntity exportExceptionDataEntity = new ExportExceptionDataEntity();
            exportExceptionDataEntity.setCreaterSn(user.getUserId().toString());
            exportExceptionDataEntity.setUserId(user.getUserId().intValue());
            exportExceptionDataEntity.setCreateTime(new Date());
            exportExceptionDataEntity.setModTime(new Date());
            exportExceptionDataEntity.setMerchSn(merchSn);
            exportExceptionDataEntity.setStoreId(user.getStoreId());
            exportExceptionDataEntity.setExportDataType(Dict.exportDataType.item_3.getItem());
            if(failMerchSnList != null && failMerchSnList.size() > 0){
                exportExceptionDataEntity.setExportExceptionData("商户编码不存在，请检查门店名称【"+failMerchSnList+"】的商户编码信息，请先维护再继续操作！");
                exportExceptionDataDao.save(exportExceptionDataEntity);
                throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
            }
            if(failThirdMerchSnList != null && failThirdMerchSnList.size() > 0){
                exportExceptionDataEntity.setExportExceptionData("第三方商户代码不存在，请在商城配置》第三方商户管理中维护，请检查门店名称【"+failThirdMerchSnList+"】的第三方商户代码信息，请先维护再继续操作！");
                exportExceptionDataDao.save(exportExceptionDataEntity);
                throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
            }
            if(failHaveNameList != null && failHaveNameList.size() > 0){
                exportExceptionDataEntity.setExportExceptionData("门店名称已重复！请检查门店名称【" + failHaveNameList + "】的门店名称信息");
                exportExceptionDataDao.save(exportExceptionDataEntity);
                throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
            }
            if(failAgreementTypeList != null && failAgreementTypeList.size() > 0){
                exportExceptionDataEntity.setExportExceptionData("第三方商户快递协议类型只能是【00:e码头，01:商户自谈】！请检查门店名称【"+failAgreementTypeList+"】的第三方商户快递协议类型信息");
                exportExceptionDataDao.save(exportExceptionDataEntity);
                throw new RRException("导入数据异常，异常信息请在商品管理》》导入异常数据中查看检查");
            }
        }else{
            throw new RRException("导入数据为空，或者检查数据是否为空");
        }
        throw new RRException("导入成功！");
//        return 1;
    }


    @Override
    public List<StoreEntity> queryExportList(Map<String, Object> map) {
        List<StoreEntity> list = storeDao.queryExportList(map);
        return list;
    }

    @Override
    public String checkStoreIdUpload(List<StoreIdDto> storeIdDtoList){
        Boolean isFalse = false;
        List<String> storeIdErrorList = new ArrayList<>();
        for(StoreIdDto storeIdDto : storeIdDtoList) {
            StoreEntity storeEntity = storeDao.queryObject(storeIdDto.getStoreId());
            if (storeEntity == null) {
                isFalse = true;
                storeIdErrorList.add(storeIdDto.getStoreId());
            }
        }
        if(isFalse){
            throw new RRException("门店不存在，不存在id【" + storeIdErrorList + "】");
        }else{
            StringBuffer storeIds = new StringBuffer();
            for(StoreIdDto storeIdDto : storeIdDtoList){
                storeIds.append(storeIdDto.getStoreId()+";");
            }
            return storeIds.toString();
        }
    }
}
