package com.hai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.CoordCommonUtil;
import com.hai.common.utils.MD5Util;
import com.hai.config.SpPrinterConfig;
import com.hai.dao.HighMerchantStoreMapper;
import com.hai.entity.*;
import com.hai.model.GasSelfBuiltStationModel;
import com.hai.model.HighMerchantStoreModel;
import com.hai.service.HighMerchantStoreAccountService;
import com.hai.service.HighMerchantStoreService;
import com.hai.service.SecUserService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("highMerchantStoreService")
public class HighMerchantStoreServiceImpl implements HighMerchantStoreService {

    @Resource
    private HighMerchantStoreMapper highMerchantStoreMapper;

    @Resource
    private SecUserService secUserService;

    @Resource
    private HighMerchantStoreAccountService merchantStoreAccountService;

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void insertMerchantStore(HighMerchantStoreModel highMerchantStore) throws Exception {
        highMerchantStoreMapper.insert(highMerchantStore);
        if (StringUtils.isBlank(highMerchantStore.getStoreKey())) {
            Long storeKey = 11000000 + highMerchantStore.getId();
            highMerchantStore.setStoreKey(storeKey.toString());
            highMerchantStoreMapper.updateByPrimaryKey(highMerchantStore);
        }
        highMerchantStore.setSecUser(new SecUser());
        highMerchantStore.getSecUser().setUserName(highMerchantStore.getStoreName());
        highMerchantStore.getSecUser().setLoginName(highMerchantStore.getStoreKey());
        highMerchantStore.getSecUser().setPassword(MD5Util.encode("123456".getBytes()));
        highMerchantStore.getSecUser().setAdminFlag(1);
        highMerchantStore.getSecUser().setStatus(1);
        highMerchantStore.getSecUser().setRoleId(4L);
        highMerchantStore.getSecUser().setObjectType(3);
        highMerchantStore.getSecUser().setObjectId(highMerchantStore.getId());
        highMerchantStore.getSecUser().setCreateTime(new Date());
        highMerchantStore.getSecUser().setUpdateTime(new Date());
        secUserService.addUser(highMerchantStore.getSecUser());

        // 绑定设备
        if (StringUtils.isNotBlank(highMerchantStore.getDeviceKey())
                && StringUtils.isNotBlank(highMerchantStore.getDeviceSn())
                && StringUtils.isNotBlank(highMerchantStore.getDeviceName())) {
            SpPrinterConfig sp = new SpPrinterConfig();
            JSONObject jsonObject = JSONObject.parseObject(sp.addPrinter(highMerchantStore.getDeviceSn(), highMerchantStore.getDeviceKey(), highMerchantStore.getDeviceName()));
            if (!jsonObject.getInteger("errorcode").equals(0)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "设备绑定失败");
            }
        }

        // 预存类型  0：非预存  1：预存门店
        if (highMerchantStore.getPrestoreType().equals(1)) {
            // 是否开通了账户
            HighMerchantStoreAccount account = merchantStoreAccountService.getStoreAccountDetail(highMerchantStore.getId());
            if (account == null) {
                account = new HighMerchantStoreAccount();
                account.setStoreId(highMerchantStore.getId());
                account.setAmounts(new BigDecimal("0"));
                merchantStoreAccountService.editStoreAccount(account);
            }
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void insertMerchantStoreList(List<HighMerchantStoreModel> highMerchantStoreList) throws Exception {
        for (HighMerchantStoreModel highMerchantStore : highMerchantStoreList) {
            insertMerchantStore(highMerchantStore);
        }
    }

    @Override
    @Transactional
    public void updateMerchantStore(HighMerchantStoreModel highMerchantStore)  {
        highMerchantStoreMapper.updateByPrimaryKey(highMerchantStore);
    }

    @Override
    public void updateMerchantStoreDetail(HighMerchantStore highMerchantStore) throws Exception {
        highMerchantStoreMapper.updateByPrimaryKey(highMerchantStore);
    }

    @Override
    @Transactional
    public void deleteMerchantStore(Long id) {
        // 查询门店
        HighMerchantStore store = highMerchantStoreMapper.selectByPrimaryKey(id);
        if (store == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_STORE_NOF_FOUND, "");
        }
        store.setStatus(0);
        store.setUpdateTime(new Date());
        highMerchantStoreMapper.updateByPrimaryKey(store);

        // 查询门店下的所有用户
        List<SecUser> userList = secUserService.getMerchantStoreUser(store.getId());
        for (SecUser user : userList) {
            user.setStatus(0);  // 删除
            secUserService.updateUser(user);
        }
    }

    @Override
    public HighMerchantStoreModel getMerchantStoreById(Long id) {
        HighMerchantStore merchantStore = highMerchantStoreMapper.selectByPrimaryKey(id);
        if (merchantStore == null) {
            return null;
        }
        HighMerchantStoreModel model = new HighMerchantStoreModel();
        BeanUtils.copyProperties(merchantStore, model);

        // 查询主账号
        SecUser mainAccount = secUserService.getMainAccount(3, merchantStore.getId());
        if (mainAccount != null) {
            model.setSecUser(mainAccount);
        }
        return model;
    }

    @Override
    public HighMerchantStoreModel getMerchantStoreByKey(String storeKey) {
        HighMerchantStoreExample example = new HighMerchantStoreExample();
        example.createCriteria().andStoreKeyEqualTo(storeKey);
        List<HighMerchantStore> list = highMerchantStoreMapper.selectByExample(example);
        if (list.size() > 0) {
            HighMerchantStore merchantStore = list.get(0);
            if (merchantStore == null) {
                return null;
            }
            HighMerchantStoreModel model = new HighMerchantStoreModel();
            BeanUtils.copyProperties(merchantStore, model);

            // 查询主账号
            SecUser mainAccount = secUserService.getMainAccount(3, merchantStore.getId());
            if (mainAccount != null) {
                model.setSecUser(mainAccount);
            }
            return model;
        }
        return null;
    }

    @Override
    public HighMerchantStore getMerStoreDetailByKey(String storeKey) {
        HighMerchantStoreExample example = new HighMerchantStoreExample();
        example.createCriteria().andStoreKeyEqualTo(storeKey);
        List<HighMerchantStore> list = highMerchantStoreMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public HighMerchantStore getDetailById(Long id) {
        return highMerchantStoreMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<HighMerchantStore> getStoreListByMer(Long merId) {
        HighMerchantStoreExample example = new HighMerchantStoreExample();
        example.createCriteria().andMerchantIdEqualTo(merId);
        return highMerchantStoreMapper.selectByExample(example);
    }

    @Override
    public List<HighMerchantStore> getMerchantStoreList(Map<String, Object> map) {
        HighMerchantStoreExample example = new HighMerchantStoreExample();
        HighMerchantStoreExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getInteger(map, "type") != null) {
            criteria.andTypeEqualTo(MapUtils.getInteger(map, "type"));
        }

        if (MapUtils.getInteger(map, "sourceType") != null) {
            criteria.andSourceTypeEqualTo(MapUtils.getInteger(map, "sourceType"));
        }

        if (MapUtils.getLong(map, "companyId") != null) {
            criteria.andCompanyIdEqualTo(MapUtils.getLong(map, "companyId"));
        }

        if (MapUtils.getLong(map, "merchantId") != null) {
            criteria.andMerchantIdEqualTo(MapUtils.getLong(map, "merchantId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "storeKey"))) {
            criteria.andStoreKeyEqualTo(MapUtils.getString(map, "storeKey"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "storeName"))) {
            criteria.andStoreNameLike("%" + MapUtils.getString(map, "storeName") + "%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "telephone"))) {
            criteria.andTelephoneEqualTo(MapUtils.getString(map, "telephone"));
        }

        criteria.andStatusEqualTo(1);

        example.setOrderByClause("create_time desc");
        return highMerchantStoreMapper.selectByExample(example);
    }

    @Override
    public List<HighMerchantStore> getStoreListByLongitude(Map<String, Object> map) {
        List<HighMerchantStore> storeList = getMerchantStoreList(map);
        for (HighMerchantStore store : storeList) {
            double distance = CoordCommonUtil.getDistance(Double.valueOf(store.getLatitude()), Double.valueOf(store.getLongitude()), Double.valueOf(map.get("latitude").toString()), Double.valueOf(map.get("longitude").toString()));
            store.setDistance(Math.round(distance/100d)/10d);
        }
        List<HighMerchantStore> collect = storeList.stream().sorted(Comparator.comparing(HighMerchantStore::getDistance)).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<GasSelfBuiltStationModel> getGasSelfBuiltStationList(Map<String, Object> map) {
        return highMerchantStoreMapper.selectGasSelfBuiltStationList(map);
    }


}
