package com.hwrj.cloud.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hwrj.cloud.admin.dao.UmsCompanyInfoDao;
import com.hwrj.cloud.admin.dao.UmsCompanyShopDao;
import com.hwrj.cloud.admin.dto.UmsCompanyDto;
import com.hwrj.cloud.admin.dto.param.CompanyWebPageParam;
import com.hwrj.cloud.admin.dto.param.SelectNewVo;
import com.hwrj.cloud.admin.dto.param.SelectVo;
import com.hwrj.cloud.admin.excelEntity.UmsCompanyInfoExcel;
import com.hwrj.cloud.admin.mapper.*;
import com.hwrj.cloud.admin.model.*;
import com.hwrj.cloud.admin.service.UmsCompanyService;
import com.hwrj.cloud.admin.util.CurrUserUtil;
import com.hwrj.cloud.common.api.CommonPage;
import com.hwrj.cloud.common.exception.GlobalException;

import com.hwrj.cloud.common.util.ShareCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class UmsCompanyInfoServiceImpl implements UmsCompanyService {

    @Autowired
    private UmsCompanyInfoMapper umsCompanyInfoMapper;

    @Autowired
    private UmsCompanyFileMapper umsCompanyFileMapper;

    @Autowired
    private UmsCompanyShopMapper umsCompanyShopMapper;

    @Autowired
    private UmsCompanyShopDao umsCompanyShopDao;

    @Autowired
    private UmsCompanyShareMapper umsCompanyShareMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(UmsCompanyDto dto) {
        UmsCompanyInfo ums = new UmsCompanyInfo();
        BeanUtil.copyProperties(dto, ums);
        ums.setCreateTime(new Date());
        int i = umsCompanyInfoMapper.insertSelective(ums);
        List<UmsCompanyFile> files = dto.getFiles();
        List<UmsCompanyShop> shops = dto.getShops();

        List<UmsCompanyFile> filesAdd = new ArrayList<>();
        List<UmsCompanyShop> shopsAdd = new ArrayList<>();
        if (shops != null && shops.size() > 0) {
            for (UmsCompanyShop shop : shops) {
                shop.setShopStatus(0);
                shop.setCreateTime(new Date());
                shop.setCreateId(dto.getCreateId());
                shop.setCompId(ums.getId());
                shopsAdd.add(shop);
            }
            umsCompanyShopDao.addUmsCompanyShopList(shopsAdd);
        }
        if (files != null && files.size() > 0) {
            for (UmsCompanyFile file : files) {
                file.setFileStatus(0);
                file.setCreateTime(new Date());
                file.setCreateId(dto.getCreateId());
                file.setCompId(ums.getId());
                filesAdd.add(file);
            }
            umsCompanyShopDao.insertFile(filesAdd);
        }
    }

    @Override
    public void update(UmsCompanyDto dto) {
        UmsCompanyInfo ums = new UmsCompanyInfo();
        BeanUtil.copyProperties(dto, ums);

        List<UmsCompanyFile> files = dto.getFiles();
        List<UmsCompanyShop> shops = dto.getShops();

        List<UmsCompanyFile> filesAdd = new ArrayList<>();
        List<UmsCompanyShop> shopsAdd = new ArrayList<>();
        Long id = ums.getId();
        if (shops != null && shops.size() > 0) {
            for (UmsCompanyShop shop : shops) {
                shop.setShopStatus(0);
                shop.setCreateTime(new Date());
                shop.setCreateId(dto.getCreateId());
                shop.setCompId(ums.getId());
                shopsAdd.add(shop);
            }
            deleteCompanyShop(id);
            umsCompanyShopDao.addUmsCompanyShopList(shopsAdd);
        }
        if (files != null && files.size() > 0) {
            for (UmsCompanyFile file : files) {
                file.setFileStatus(0);
                file.setCreateTime(new Date());
                file.setCreateId(dto.getCreateId());
                file.setCompId(ums.getId());
                filesAdd.add(file);
            }
            deleteCompanyFile(id);
            umsCompanyShopDao.insertFile(filesAdd);
        }
        umsCompanyInfoMapper.updateByPrimaryKeySelective(ums);
    }

    @Autowired
    private UmsCompanyInfoDao umsCompanyInfoDao;

    @Autowired
    private UmsAdminMapper umsAdminMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        long i = umsCompanyInfoDao.deleteCheck(id);
        if (i > 0) {
            throw new GlobalException("该供应商的数据被用户~生产地~商品所引用无法删除！");
        }
        UmsCompanyInfo info = new UmsCompanyInfo();
        info.setCompStatus(2);
        info.setId(id);

        umsCompanyInfoMapper.updateByPrimaryKeySelective(info);

        deleteCompanyShop(id);
        deleteCompanyShare(id);
        deleteCompanyFile(id);
        deleteAdmin(id);
    }


    private void deleteCompanyShare(Long compId){
        UmsCompanyShareExample example=new UmsCompanyShareExample();
        example.createCriteria().andCompIdEqualTo(compId);
        umsCompanyShareMapper.deleteByExample(example);
    }
    private void deleteAdmin(Long id) {
        UmsAdmin record=new UmsAdmin();
        record.setStatus(0);
        UmsAdminExample example=new UmsAdminExample();
        example.createCriteria().andCompIdEqualTo(id);
        umsAdminMapper.updateByExampleSelective(record,example);
    }

    private void deleteCompanyShop(Long compId){
        UmsCompanyShopExample example=new UmsCompanyShopExample();
        UmsCompanyShopExample.Criteria criteria = example.createCriteria();
        criteria.andCompIdEqualTo(compId);
        umsCompanyShopMapper.deleteByExample(example);
    }

    private void deleteCompanyFile(Long compId){
        UmsCompanyFileExample example=new UmsCompanyFileExample();
        UmsCompanyFileExample.Criteria criteria = example.createCriteria();
        criteria.andCompIdEqualTo(compId);
        umsCompanyFileMapper.deleteByExample(example);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importExcel(List<UmsCompanyInfoExcel> infoExcels) {
        if (infoExcels == null || infoExcels.size() < 1) {
            return null;
        }

        List<UmsCompanyShop> listShops = new ArrayList<>();
        infoExcels.stream().forEach(item -> {
            UmsCompanyInfo umsCompanyInfo = new UmsCompanyInfo();
            BeanUtil.copyProperties(item, umsCompanyInfo);
            umsCompanyInfo.setCreateTime(new Date());
            umsCompanyInfo.setCompStatus(0);
            try {
                int i = umsCompanyInfoMapper.insertSelective(umsCompanyInfo);

                item.setId(umsCompanyInfo.getId());
                List<UmsCompanyShop> shops = getShopsFromUmsCompanyInfoExcel(item);
                listShops.addAll(shops);
            } catch (Exception e) {
                log.info("添加数据失败");
            }
        });
        if (listShops != null && listShops.size() > 0) {
            int i = umsCompanyShopDao.addUmsCompanyShopList(listShops);
        }
        return null;
    }

    @Override
    public Map<String, Object> getCompanyInfoList(CompanyWebPageParam companyWebPageParam) {
        Map<String, Object> hasp = new HashMap<>();
        PageHelper.startPage(companyWebPageParam.getPageNo(), companyWebPageParam.getPageSize());
        UmsCompanyInfoExample example = new UmsCompanyInfoExample();
        UmsCompanyInfoExample.Criteria criteria = example.createCriteria();
        criteria.andCompStatusEqualTo(0);
        String keyword = companyWebPageParam.getKeyword();
        if(!org.springframework.util.StringUtils.isEmpty(keyword)){
            criteria.andCompNameLike("%"+keyword+"%");
        }
        boolean admin = CurrUserUtil.getUmsAdmin().isAdmin();
        if(!admin){
            Long compIdInfo = CurrUserUtil.getCompIdInfo();
            if(!org.springframework.util.StringUtils.isEmpty(compIdInfo)){
                criteria.andIdEqualTo(compIdInfo);
            }
        }
        example.setOrderByClause("create_time desc");
        List<UmsCompanyInfo> companyInfos = umsCompanyInfoMapper.selectByExample(example);
        CommonPage<UmsCompanyInfo> umsCompanyInfoCommonPage = CommonPage.restPage(companyInfos);
        List<UmsCompanyInfo> list = umsCompanyInfoCommonPage.getList();
        List<UmsCompanyDto> dtos = new ArrayList<>();
        list.stream().forEach(comp -> {
            UmsCompanyDto dto = new UmsCompanyDto();
            BeanUtil.copyProperties(comp, dto);
            dto.setFiles(getCompanyFile(comp.getId()));
            dto.setShops(getCompanyShop(comp.getId()));
            dtos.add(dto);
        });
        hasp.put("total", umsCompanyInfoCommonPage.getTotal());
        hasp.put("list", dtos);
        return hasp;
    }

    @Override
    public UmsCompanyDto getDetailCompany(Long companyId) {
        UmsCompanyInfo umsCompanyInfo = umsCompanyInfoMapper.selectByPrimaryKey(companyId);
        UmsCompanyDto ums = new UmsCompanyDto();
        BeanUtil.copyProperties(umsCompanyInfo, ums);
        ums.setFiles(getCompanyFile(companyId));
        ums.setShops(getCompanyShop(companyId));
        return ums;
    }

    public List<UmsCompanyShop> getShopsFromUmsCompanyInfoExcel(UmsCompanyInfoExcel ums) {
        List<UmsCompanyShop> shops = new ArrayList<>();
        UmsCompanyShop shop = new UmsCompanyShop();

        shop.setCompId(ums.getId());
        shop.setCreateId((long) 1);
        shop.setCreateTime(new Date());
        shop.setShopStatus(0);
        if (!StringUtils.isEmpty(ums.getTbUrl())) {
            UmsCompanyShop tbShop = new UmsCompanyShop();
            BeanUtil.copyProperties(shop, tbShop);
            tbShop.setShopType("taobao");
            tbShop.setShopUrl(ums.getTbUrl());
            tbShop.setShopImg("http://fqn.hongweisoft.com/taobao.jpg ");
            shops.add(tbShop);

        }
        if (!StringUtils.isEmpty(ums.getJdUrl())) {
            UmsCompanyShop jdShop = new UmsCompanyShop();
            BeanUtil.copyProperties(shop, jdShop);
            jdShop.setShopType("jd");
            jdShop.setShopUrl(ums.getJdUrl());
            jdShop.setShopImg("http://fqn.hongweisoft.com/jingdong.jpg");
            shops.add(jdShop);
        }

        if (!StringUtils.isEmpty(ums.getOwnUrl())) {
            UmsCompanyShop ownShop = new UmsCompanyShop();
            BeanUtil.copyProperties(shop, ownShop);
            ownShop.setShopType("own");
            ownShop.setShopUrl(ums.getOwnUrl());
            ownShop.setShopImg("http://fqn.hongweisoft.com/own.jpg");
            shops.add(ownShop);
        }
        return shops;
    }

    @Override
    public List<UmsCompanyFile> getCompanyFile(Long compId) {
        UmsCompanyFileExample example = new UmsCompanyFileExample();
        UmsCompanyFileExample.Criteria criteria = example.createCriteria();
        criteria.andCompIdEqualTo(compId);
        criteria.andFileStatusEqualTo(0);
        List<UmsCompanyFile> files = umsCompanyFileMapper.selectByExample(example);
        return files;
    }

    @Override
    public List<UmsCompanyShop> getCompanyShop(Long compId) {
        UmsCompanyShopExample example = new UmsCompanyShopExample();
        UmsCompanyShopExample.Criteria criteria = example.createCriteria();
        criteria.andCompIdEqualTo(compId);
        criteria.andShopStatusEqualTo(0);
        List<UmsCompanyShop> shops = umsCompanyShopMapper.selectByExample(example);
        return shops;
    }

    @Override
    public void updateCompanyFile(UmsCompanyFile umsCompanyFile) {
        if (StringUtils.isEmpty(umsCompanyFile.getId())) {
            throw new GlobalException("缺失修改主体!");
        }
        umsCompanyFile.setUpdateTime(new Date());
        umsCompanyFileMapper.updateByPrimaryKeySelective(umsCompanyFile);
    }

    @Override
    public void deleteCompanyFile(Long shopId, Long userId) {
        if (shopId == null) {
            throw new GlobalException("缺失删除主体!");
        }
        UmsCompanyFile umsCompanyFile = new UmsCompanyFile();
        umsCompanyFile.setId(shopId);
        umsCompanyFile.setFileStatus(2);
        umsCompanyFile.setUpdateTime(new Date());
        umsCompanyFile.setUpdateId(userId);

    }

    @Override
    public void updateCompanyShop(UmsCompanyShop umsCompanyShop) {
        if (StringUtils.isEmpty(umsCompanyShop.getId())) {
            throw new GlobalException("缺失修改主体!");
        }
        umsCompanyShop.setUpdateTime(new Date());
        umsCompanyShopMapper.updateByPrimaryKeySelective(umsCompanyShop);
    }

    @Override
    public void deleteCompanyShop(Long shopId, Long userId) {
        if (shopId == null) {
            throw new GlobalException("缺失删除主体");
        }

        UmsCompanyShop umsCompanyShop = new UmsCompanyShop();
        umsCompanyShop.setId(shopId);
        umsCompanyShop.setShopStatus(2);
        umsCompanyShop.setUpdateTime(new Date());
        umsCompanyShopMapper.updateByPrimaryKeySelective(umsCompanyShop);
    }

    @Override
    public void deleteCompanyFileByCompId(Long compId, Long userId) {
        UmsCompanyFileExample fileExampleW = new UmsCompanyFileExample();
        UmsCompanyFileExample.Criteria fileCriteriaW = fileExampleW.createCriteria();
        fileCriteriaW.andCompIdEqualTo(compId);
        UmsCompanyFile file = new UmsCompanyFile();
        file.setFileStatus(2);
        file.setUpdateId(userId);
        file.setUpdateTime(new Date());
        umsCompanyFileMapper.updateByExample(file, fileExampleW);
    }

    @Override
    public void deleteCompanyShopByCompId(Long compId, Long userId) {
        UmsCompanyShop shop = new UmsCompanyShop();
        shop.setShopStatus(2);
        shop.setUpdateTime(new Date());
        UmsCompanyShopExample shopExample = new UmsCompanyShopExample();
        UmsCompanyShopExample.Criteria criteria = shopExample.createCriteria();
        criteria.andCompIdEqualTo(compId);
        umsCompanyShopMapper.updateByExample(shop, shopExample);
    }

    @Override
    public List<UmsCompanyInfo> searchCompanyInfo(String key, int pageNo, int pageSize, Long compId) {
        PageHelper.startPage(pageNo, pageSize);
        UmsCompanyInfoExample umsCompanyInfoExample = new UmsCompanyInfoExample();
        UmsCompanyInfoExample.Criteria criteria = umsCompanyInfoExample.createCriteria();
        if (compId != null) {
            criteria.andIdEqualTo(compId);
        } else {
            if (StringUtils.isEmpty(key)) {
                criteria.andCompNameLike("%" + key + "%");
            }
        }

        List<UmsCompanyInfo> umsCompanyInfos = umsCompanyInfoMapper.selectByExample(umsCompanyInfoExample);
        return umsCompanyInfos;

    }



    @Override
    public List<SelectNewVo> selectList(){
        Long compIdInfo = CurrUserUtil.getCompIdInfo();
        return umsCompanyInfoDao.selectList(compIdInfo);
    }

    @Override
    public List<SelectVo> alllist(){
        return umsCompanyInfoDao.alllist();
    }

}
