package com.gree.mall.manager.logic;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.StorageVO;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.commonmapper.CommonPageV2Mapper;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.Storage;
import com.gree.mall.manager.plus.service.StorageService;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
public class StorageLogic {

    @Autowired
    CommonLogic commonLogic;
    @Resource
    StorageService storageService;

    @Autowired
    CommonPageV2Mapper commonPageV2Mapper;

    /**
     * 仓储列表
     *
     * @param type
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<Storage> page(String type, Boolean status, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        return storageService.lambdaQuery()
                .like(!StringUtils.isEmpty(type), Storage::getType, type)
                .eq(Objects.nonNull(status), Storage::getStatus, status)
                .in(CollectionUtils.isNotEmpty(adminUser.getCompanyWechatIds()), Storage::getCompanyWechatId, adminUser.getCompanyWechatIds())
                .page(new Page<>(pageNum, pageSize));
    }

    /**
     * 仓储详情
     *
     * @param id
     * @return
     */
    public Storage detail(String id) {
        return storageService.getById(id);
    }

    public Storage detailByName(String companyWechatId,String name) {
        return storageService
                .lambdaQuery()
                .eq(Storage::getCompanyWechatId, companyWechatId)
                .eq(Storage::getStorageName,name)
                .one();
    }

    /**
     * 新增仓储
     *
     * @param storage
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(HttpServletRequest request,Storage storage) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if(StringUtils.isBlank(adminUser.getCompanyWechatId())){
            throw new RemoteServiceException("平台账号不可操作当前信息");
        }
        if (storage.getType().contains("商品") && (storage.getType().contains("辅材") || storage.getType().contains("配件"))) {
            throw new RemoteServiceException("仓库属性“商品”与“辅材或配件”不能同选");
        }

        if ((storage.getType().contains("辅材") || storage.getType().contains("配件"))
                && StringUtils.isBlank(storage.getWebsitId())
                && StringUtils.isBlank(storage.getWebsitName())) {
            throw new RemoteServiceException("仓库属性非”商品“, 请选择网点");
        }

        if (storage.getType().equals("商品")) {
            storage.setWebsitId(null)
                    .setWebsitName(null);
        }

        storage.setIsDefault(false);
        storage.setCreateTime(new Date());
        storage.setCompanyWechatId(adminUser.getCompanyWechatId());
        storage.setCompanyName(adminUser.getCompanyName());

        final Integer count = storageService.lambdaQuery()
                .eq(Storage::getCompanyWechatId, storage.getCompanyWechatId())
                .eq(StringUtils.isNotBlank(storage.getWebsitId()), Storage::getWebsitId, storage.getWebsitId())
                .eq(Storage::getStorageName, storage.getStorageName())
                .count();

        if (count > 0) {
            throw new RemoteServiceException("有相同的仓储名称");
        }

        storageService.save(storage);
    }

    /**
     * 修改仓储
     *
     * @param storage
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(Storage storage) {
        final Storage oldManage = storageService.getById(storage.getStorageId());
        if (Objects.isNull(oldManage)) {
            throw new RemoteServiceException("仓储信息不存在");
        }
        if (oldManage.getIsDefault() && !storage.getStatus()) {
            throw new RemoteServiceException("默认仓不能改变状态");
        }
        storage.setCompanyWechatId(oldManage.getCompanyWechatId())
                .setCompanyName(oldManage.getCompanyName())
                .setWebsitId(oldManage.getWebsitId())
                .setWebsitName(oldManage.getWebsitName())
                .setType(oldManage.getType());

        final Integer count = storageService.lambdaQuery()
                .eq(Storage::getCompanyWechatId, storage.getCompanyWechatId())
                .eq(StringUtils.isNotBlank(storage.getWebsitId()), Storage::getWebsitId, storage.getWebsitId())
                .ne(Storage::getStorageId, storage.getStorageId())
                .eq(Storage::getStorageName, storage.getStorageName())
                .count();

        if (count > 0) {
            throw new RemoteServiceException("有相同的仓储名称");
        }
        storage.setCreateTime(null);
        storageService.updateById(storage);
    }

    /**
     * 删除仓储
     *
     * @param storageId
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(String storageId) {
        final Storage storage = storageService.getById(storageId);
        if (storage.getIsDefault()) {
            throw new RemoteServiceException("默认仓不能删除");
        }
        storageService.removeById(storageId);
    }

    public IPage<StorageVO> pageV2(ZfireParamBean zfireParamBean) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();


        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, StorageVO.class, adminUser);

        IPage<StorageVO> storageVOIPage = commonPageV2Mapper.pageV2Storage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()),
                zfireParam, companyWechatIds);

        return storageVOIPage;
    }

    public void batchUpdateStatus(List<String> ids, Boolean status) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (Objects.isNull(adminUser.getAdminCompanyWechat())) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        storageService.lambdaUpdate()
                .set(Storage::getStatus, status)
                .eq(Storage::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(Storage::getIsDefault, false)
                .in(Storage::getStorageId, ids)
                .update();
    }
}
