package com.neusoft.smart.pos.org.service;

import com.neusoft.smart.pos.dto.device.request.DeviceStoreRequest;
import com.neusoft.smart.pos.dto.org.request.PostShopRequest;
import com.neusoft.smart.pos.dto.org.request.PutShopRequest;
import com.neusoft.smart.pos.dto.org.request.ShopQueryRequest;
import com.neusoft.smart.pos.dto.org.response.PostShopResponse;
import com.neusoft.smart.pos.framework.constants.CommonErrorCode;
import com.neusoft.smart.pos.framework.constants.RoleConstant;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.org.constants.OrgShopErrorCode;
import com.neusoft.smart.pos.org.dto.User;
import com.neusoft.smart.pos.org.persistent.domain.Shop;
import com.neusoft.smart.pos.org.persistent.domain.ShopExample;
import com.neusoft.smart.pos.org.persistent.domain.UserShopExample;
import com.neusoft.smart.pos.org.persistent.domain.UserShopKey;
import com.neusoft.smart.pos.org.persistent.mapper.UserShopMapper;
import com.neusoft.smart.pos.org.repository.ShopRepository;
import com.neusoft.smart.pos.utils.RequestHeaderUtil;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShopService {
    @Autowired
    UserShopMapper userShopMapper;

    @Autowired
    RemoteDeviceService remoteDeviceService;

    @Resource
    public ShopRepository shopRepository;

    @Autowired
    RemoteUserService remoteUserService;

    public List<Shop> selectShopsByUsername(String username) {
        User user = remoteUserService.getUser(username);
        if (user != null) {
            UserShopExample userShopExample = new UserShopExample();
            userShopExample.createCriteria().andUsrEqualTo(user.getId());
            List<UserShopKey> userShopKeys = userShopMapper.selectByExample(userShopExample);
            return userShopKeys.stream()
                    .map(userShopKey -> shopRepository.selectByPrimaryKey(userShopKey.getShop()))
                    .collect(Collectors.toList());
        }
        return null;
    }

    public List<Integer> selectShopIdByUserId(Integer userId) {
        UserShopExample userShopExample = new UserShopExample();
        userShopExample.createCriteria().andUsrEqualTo(userId);
        List<UserShopKey> userShopKeys = userShopMapper.selectByExample(userShopExample);
        return userShopKeys.stream()
                .map(UserShopKey::getShop)
                .collect(Collectors.toList());
    }

    public PostShopResponse insertShop(PostShopRequest shopRequest) {
        if (StringUtils.isEmpty(shopRequest.getName())) {
            throw new BusinessCommonException(OrgShopErrorCode.SHOP_NAME_IS_NULL);
        }
        if (StringUtils.isEmpty(shopRequest.getProvince())) {
            throw new BusinessCommonException(OrgShopErrorCode.SHOP_PROVINCE_IS_NULL);
        }
        if (StringUtils.isEmpty(shopRequest.getCity())) {
            throw new BusinessCommonException(OrgShopErrorCode.SHOP_CITY_IS_NULL);
        }
        if (StringUtils.isEmpty(shopRequest.getOrg())) {
            throw new BusinessCommonException(OrgShopErrorCode.SHOP_ORG_IS_NULL);
        }
        //验证门店名称是否重复
        if (shopRepository.queryShopByName(shopRequest.getName(), shopRequest.getOrg()) != null)
            throw new BusinessCommonException(OrgShopErrorCode.SHOP_NAME_REPEAT);
        //验证角色
        Integer orgId = RequestHeaderUtil.getOrgId();
        if (null != orgId && (RequestHeaderUtil.getRole().equals(RoleConstant.ROLE_ADMIN))) {
            shopRequest.setOrg(orgId);
        } else if (null != orgId && (RequestHeaderUtil.getRole().equals(RoleConstant.ROLE_USER))) {
            throw new BusinessCommonException(CommonErrorCode.PERMISSION_ERROR);
        }
        //插入新的门店数据
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopRequest, shop);
        shopRepository.insertSelective(shop);
        //绑定设备ID至门店
        if (!StringUtils.isEmpty(shopRequest.getDeviceIds()) && shopRequest.getDeviceIds().size() > 0) {
            DeviceStoreRequest deviceStoreRequest = new DeviceStoreRequest();
            deviceStoreRequest.setDeviceIds(shopRequest.getDeviceIds());
            deviceStoreRequest.setStoreId(shop.getId());
            remoteDeviceService.updateStatus(deviceStoreRequest);
            //更新POS数
            shop.setPosnum(shopRequest.getDeviceIds().size());
            shopRepository.updateByPrimaryKeySelective(shop);
        }
        //根据新插入数据的ID得到详细信息并返回        
        PostShopResponse shopResponse = new PostShopResponse();
        BeanUtils.copyProperties(selectShopById(shop.getId()), shopResponse);
        return shopResponse;
    }

    public int updateShop(PutShopRequest shopRequest) {
        if (!StringUtils.isEmpty(shopRequest.getName())) {
            Shop shop = shopRepository.queryShopByName(shopRequest.getName(), shopRequest.getOrg());
            if (shop != null && !shop.getId().equals(shopRequest.getId())) {
                throw new BusinessCommonException(OrgShopErrorCode.SHOP_NAME_REPEAT);
            }
        }
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopRequest, shop);
        //绑定设备ID至门店
        if (!StringUtils.isEmpty(shopRequest.getDeviceIds()) && shopRequest.getDeviceIds().size() > 0) {
            DeviceStoreRequest deviceStoreRequest = new DeviceStoreRequest();
            deviceStoreRequest.setDeviceIds(shopRequest.getDeviceIds());
            deviceStoreRequest.setStoreId(shop.getId());
            remoteDeviceService.updateStatus(deviceStoreRequest);
            //更新POS数
            shop.setPosnum(shopRequest.getDeviceIds().size());
        }
        return shopRepository.updateByPrimaryKeySelective(shop);
    }

    public int deleteShop(int shopId) {
        int shop_id = RequestHeaderUtil.getStoreIdByRole(shopId);
        //return shopMapper.deleteByPrimaryKey(shopId);
        Shop shop = new Shop();
        shop.setStatus("0");
        shop.setId(shop_id);
        //解除绑定设备ID至门店
        DeviceStoreRequest deviceStoreRequest = new DeviceStoreRequest();
        deviceStoreRequest.setDeviceIds(new ArrayList<Integer>());
        deviceStoreRequest.setStoreId(shop_id);
        remoteDeviceService.updateStatus(deviceStoreRequest);
        //更新POS数
        shop.setPosnum(0);
        int i = shopRepository.updateByPrimaryKeySelective(shop);
        return i;
    }

    public List<PostShopResponse> selectShopsByCondi(ShopQueryRequest shopQueryRequest) {
        List<Integer> shopIds = RequestHeaderUtil.getStoreIds();
        if (StringUtils.isEmpty(RequestHeaderUtil.getRole())) throw new BusinessCommonException(OrgShopErrorCode.ROLE_IS_NULL);
        if (RequestHeaderUtil.getRole().equals(RoleConstant.ROLE_ADMIN)){
        	Integer orgId = RequestHeaderUtil.getOrgId();
        	if (StringUtils.isEmpty(orgId)) throw new BusinessCommonException(OrgShopErrorCode.ORGID_IS_NULL);
        	shopQueryRequest.setOrg(Integer.toString(orgId));
        }else if(RequestHeaderUtil.getRole().equals(RoleConstant.ROLE_USER)) {
        	if ((StringUtils.isEmpty(shopIds) || shopIds.size() <= 0)){
            	return new ArrayList<>();
            }
            shopQueryRequest.setIds(shopIds);
        }

        List<Shop> shops = shopRepository.selectByExample(shopQueryRequest);
        List<PostShopResponse> result = new ArrayList<>();
        shops.forEach(po -> {
            PostShopResponse response = new PostShopResponse();
            BeanUtils.copyProperties(po, response);
            result.add(response);
        });
        return result;
    }

    public int countShopsByCondi(ShopQueryRequest shopQueryRequest) {
        return shopRepository.countByExample(shopQueryRequest);
    }

    public PostShopResponse selectShopById(int shopId) {
        PostShopResponse response = new PostShopResponse();
        BeanUtils.copyProperties(shopRepository.selectByPrimaryKey(shopId), response);
        return response;
    }

    /**
     * 根据门店ID列表查询门店信息
     *
     * @param ids
     * @return
     */
    public List<PostShopResponse> queryShopListByIds(List<Integer> ids) {
        if (null == ids || ids.size() == 0) {
            return null;
        }
        List<Shop> shops = shopRepository.selectByExample(ids);
        List<PostShopResponse> result = new ArrayList<>();
        shops.forEach(po -> {
            PostShopResponse response = new PostShopResponse();
            BeanUtils.copyProperties(po, response);
            result.add(response);
        });
        return result;
    }

    /**
     * 根据集团及门店ID列表查询门店信息
     *
     * @param orgId:集团ID
     * @param shopId:门店ID
     * @return
     */
    public List<PostShopResponse> queryShopListByOrgId(Integer orgId, Integer shopId) {
        val example = new ShopExample();
        example.createCriteria()
                .andStatusEqualTo("1")
                .andOrgEqualTo(orgId);
        if (shopId != 0) {
            example.getOredCriteria().get(0).andIdEqualTo(shopId);
        }
        List<Shop> shops = shopRepository.selectByExample(example);
        List<PostShopResponse> result = new ArrayList<>();
        shops.forEach(po -> {
            PostShopResponse response = new PostShopResponse();
            BeanUtils.copyProperties(po, response);
            result.add(response);
        });
        return result;
    }
    
    
    public void changeSettleType(Integer shopId, String settleType) {
        Shop shop = new Shop();
        shop.setId(shopId);
        shop.setSettle(settleType);
        shopRepository.updateByPrimaryKeySelective(shop);
    }
}
