package com.sckw.system.service;

import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.NumberUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.response.HttpResult;
import com.sckw.system.dao.KwsEntSpecialDao;
import com.sckw.system.dao.KwsEnterpriseDao;
import com.sckw.system.dao.KwsSpecialDao;
import com.sckw.system.dao.KwsUserDao;
import com.sckw.system.model.KwsEntSpecial;
import com.sckw.system.model.KwsEnterprise;
import com.sckw.system.model.KwsSpecial;
import com.sckw.system.model.KwsUser;
import com.sckw.system.model.vo.req.KwsSpecialAddReqVo;
import com.sckw.system.model.vo.req.KwsSpecialUpdateReqVo;
import com.sckw.system.model.vo.res.KwsSpecialEntResVo;
import com.sckw.system.model.vo.res.KwsSpecialResVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @desc 专场
 * @author zk
 * @date 2023/12/11 0011
 */
@Service
public class KwsSpecialService {

    @Autowired
    KwsSpecialDao kwsSpecialDao;

    @Autowired
    KwsEntSpecialDao kwsEntSpecialDao;

    @Autowired
    KwsUserDao kwsUserDao;

    @Autowired
    KwsEnterpriseDao kwsEnterpriseDao;

    /**
     * @param key 主键id
     * @desc 根据主键查询
     * @author zk
     * @date 2023/12/13
     **/
    public KwsSpecial selectByKey(Long key) {
        return kwsSpecialDao.selectById(key);
    }

    /**
     * @param id 车辆档案ID
     * @desc 专场详情
     * @author zk
     * @date 2023/12/13
     **/
    public KwsSpecialResVo detail(Long id){
        //车辆信息
        KwsSpecial special = kwsSpecialDao.selectById(id);
        KwsSpecialResVo specialResVo = new KwsSpecialResVo();
        BeanUtils.copyPropertiesValue(special, specialResVo);

        //数据组装
        if (special != null) {
            //客户经理
            KwsUser manager = kwsUserDao.selectByKey(special.getManager());
            //创建人
            KwsUser createBy = kwsUserDao.selectByKey(special.getCreateBy());
            //专场企业
            KwsEnterprise enterprise = kwsEnterpriseDao.selectByKey(special.getEntId());

            specialResVo.setManagerName(manager != null ? manager.getName() : null);
            specialResVo.setCreateByName(createBy != null ? createBy.getName() : null);
            specialResVo.setFirmName(enterprise != null ? enterprise.getFirmName() : null);
            return specialResVo;
        }
        return null;
    }

    /**
     * @param params 分页参数
     * @desc 分页查询
     * @author zk
     * @date 2023/12/13
     **/
    public List<KwsSpecialResVo> findPage(Map<String, Object> params) {
        return kwsSpecialDao.findPage(params);
    }

    /**
     * @param params 分页参数
     * @desc 分页查询
     * @author zk
     * @date 2023/12/13
     **/
    public List<KwsSpecialEntResVo> findSpecialPage(Map<String, Object> params) {
        return kwsSpecialDao.findSpecialPage(params);
    }

    /**
     * @param params 查询参数
     * @desc 查询
     * @author zk
     * @date 2023/12/13
     **/
    public List<KwsSpecial> findList(Map<String, Object> params) {
        return kwsSpecialDao.findList(params);
    }

    /**
     * @param domain 域名
     * @desc 通过域名查询专场信息
     * @author zk
     * @date 2023/12/13
     **/
    public Map<String, Object> findSpecial(String domain) {
        List<KwsSpecial> specials = kwsSpecialDao.findList(new HashMap<>(){{put("websiteFuzzy", domain);}});
        if (CollectionUtils.isNotEmpty(specials)) {
            KwsSpecial special1 = specials.get(NumberConstant.ZERO);
            Map<String, Object> special = new HashMap<>(NumberConstant.SIXTEEN);
            special.put("name", special1.getName());
            special.put("website", special1.getWebsite());
            special.put("code", special1.getCode());
            special.put("qrCode", special1.getQrCode());
            return special;
        }
        return null;
    }

    /**
     * @param params 参数
     * @desc 新增专场
     * @author zk
     * @date 2023/12/13
     **/
    public HttpResult add(KwsSpecialAddReqVo params) {
        /*校验*/
        List<KwsSpecial> specials = kwsSpecialDao.findList(new HashMap<>(){{put("name", params.getName());}});
        if (CollectionUtils.isNotEmpty(specials)) {
            return HttpResult.error("专场名称已存在！");
        }
        specials = kwsSpecialDao.findList(new HashMap<>(){{put("code", params.getCode());}});
        if (CollectionUtils.isNotEmpty(specials)) {
            return HttpResult.error("专场编号已存在！");
        }
        specials = kwsSpecialDao.findList(new HashMap<>(){{put("entId", params.getEntId());}});
        if (CollectionUtils.isNotEmpty(specials)) {
            return HttpResult.error("企业已属专于专场主企业！");
        }
        List<KwsEntSpecial> entSpecials = kwsEntSpecialDao.findList(new HashMap<>(){{put("entId", params.getEntId());}});
        if (CollectionUtils.isNotEmpty(entSpecials)) {
            return HttpResult.error("企业已属于专场企业！");
        }

        /*数据更新*/
        KwsSpecial special = new KwsSpecial();
        BeanUtils.copyProperties(params, special);
        special.setIsMain(NumberConstant.ZERO);
        int count = kwsSpecialDao.insert(special);
        return count > 0 ? HttpResult.ok("专场信息新增成功！") : HttpResult.error("专场信息新增失败！");
    }

    /**
     * @param params 参数
     * @desc 修改专场
     * @author zk
     * @date 2023/12/13
     **/
    public HttpResult update(KwsSpecialUpdateReqVo params) {
        /*校验*/
        KwsSpecial special = kwsSpecialDao.selectById(params.getId());
        if (special == null) {
            return HttpResult.error("专场信息不存在！");
        }
        List<KwsSpecial> specials = kwsSpecialDao.findList(new HashMap<>(){{put("name", params.getName());}});
        if (CollectionUtils.isNotEmpty(specials)) {
            KwsSpecial special1 = specials.get(NumberConstant.ZERO);
            if (!special1.getId().equals(special.getId())) {
                return HttpResult.error("专场名称已存在！");
            }
        }
        specials = kwsSpecialDao.findList(new HashMap<>(){{put("code", params.getCode());}});
        if (CollectionUtils.isEmpty(specials)) {
            KwsSpecial special1 = specials.get(NumberConstant.ZERO);
            if (!special1.getId().equals(special.getId())) {
                return HttpResult.error("专场编号已存在！");
            }
        }
        specials = kwsSpecialDao.findList(new HashMap<>(){{put("entId", params.getEntId());}});
        if (CollectionUtils.isNotEmpty(specials)) {
            KwsSpecial special1 = specials.get(NumberConstant.ZERO);
            if (!special1.getId().equals(special.getId())) {
                return HttpResult.error("企业已属专于专场主企业！");
            }
        }
        List<KwsEntSpecial> entSpecials = kwsEntSpecialDao.findList(new HashMap<>(){{put("entId", params.getEntId());}});
        if (CollectionUtils.isNotEmpty(entSpecials)) {
            return HttpResult.error("企业已属于专场企业！");
        }

        /*数据更新*/
        BeanUtils.copyProperties(params, special);
        int count = kwsSpecialDao.updateById(special);
        return count > 0 ? HttpResult.ok("专场信息修改成功！") : HttpResult.error("专场信息修改失败！");
    }

    /**
     * @param ids {ids：主键ID（多个以逗号隔开）}
     * @desc 删除
     * @author zk
     * @date 2023/12/13
     **/
    public HttpResult del(String ids) {
        /*数据校验**/
        if (StringUtils.isBlank(ids)) {
            return HttpResult.error("请选择要删除的数据！");
        }

        /*数据组装**/
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            KwsSpecial special = kwsSpecialDao.selectById(id);
            if (special != null) {
                special.setDelFlag(Global.YES);
                if (kwsSpecialDao.updateById(special) <= 0) {
                    throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.DELETE_FAIL);
                }
            } else {
                return HttpResult.error("选择删除的数据已不存在！");
            }
        }
        return HttpResult.ok("删除成功！");
    }

    /**
     * @param params {}
     * @desc 加入专场
     * @author zk
     * @date 2023/12/13
     **/
    public int joinSpecial(KwsEntSpecial params) {
        return kwsEntSpecialDao.insert(params);
    }

    /**
     * @param params {}
     * @desc 加入专场
     * @author zk
     * @date 2023/12/13
     **/
    public HttpResult joinSpecial(HashMap<String, Object> params) {
        /*校验*/
        if (StringUtils.isBlank(params.get("id")) || StringUtils.isBlank(params.get("entIds"))) {
            return HttpResult.error("参数不能为空！");
        }
        Long id = NumberUtils.parseLong(params.get("id"));
        String entIds = StringUtils.objectStr(params.get("entIds"));
        String[] idArray = entIds.split(",");
        for (String entId : idArray) {
            List<KwsSpecial> specials = kwsSpecialDao.findList(new HashMap<>(){{put("entId", entId);}});
            if (CollectionUtils.isNotEmpty(specials)) {
                return HttpResult.error("企业已属专于专场主企业！");
            }

            List<KwsEntSpecial> entSpecials = kwsEntSpecialDao.findList(new HashMap<>(){{put("entId", entId);}});
            if (CollectionUtils.isNotEmpty(entSpecials)) {
                KwsEnterprise enterprise = kwsEnterpriseDao.selectByKey(Long.parseLong(entId));
                if (enterprise != null) {
                    return HttpResult.error(enterprise.getFirmName() + "已属于专场企业！");
                }
            }
        }


        /*数据组装存储*/
        for (String entId : idArray) {
            KwsEntSpecial entSpecial = new KwsEntSpecial();
            entSpecial.setSpecialId(id);
            entSpecial.setEntId(Long.parseLong(entId));
            kwsEntSpecialDao.insert(entSpecial);
        }

        return HttpResult.ok("加入专场成功！");
    }

    /**
     * @param params {}
     * @desc 退出专场
     * @author zk
     * @date 2023/12/13
     **/
    public HttpResult exitSpecial(HashMap<String, Object> params) {
        /*校验*/
        if (StringUtils.isBlank(params.get("specialId")) || StringUtils.isBlank(params.get("entId"))) {
            return HttpResult.error("参数不能为空！");
        }
        Long specialId = NumberUtils.parseLong(params.get("specialId"));
        String entId = StringUtils.objectStr(params.get("entId"));
        KwsSpecial special = kwsSpecialDao.selectById(specialId);
        if (special == null) {
            return HttpResult.error("专场信息不存在！");
        }
        List<KwsEntSpecial> entSpecials = kwsEntSpecialDao.findList(new HashMap<>(){{put("entId", entId); put("specialId", specialId);}});
        if (CollectionUtils.isEmpty(entSpecials)) {
            return HttpResult.error("专场企业信息不存在！");
        } else {
            entSpecials.forEach(e -> {
                e.setDelFlag(Global.YES);
                kwsEntSpecialDao.updateById(e);
            });
        }

        return HttpResult.ok("企业从专场删除成功！");
    }

    /**
     * @param entId 企业ID
     * @desc 企业专场编号查询
     * @author zk
     * @date 2023/12/13
     **/
    public List<String> findSpecialByEntId(Long entId) {
        List<KwsEntSpecial> entSpecials = kwsEntSpecialDao.findList(new HashMap<>(){{put("entId", entId);}});
        if (CollectionUtils.isNotEmpty(entSpecials)) {
            List<String> specialCode = new ArrayList<>();
            entSpecials.forEach(e ->{
                KwsSpecial special = kwsSpecialDao.selectById(e.getSpecialId());
                if (special != null) {
                    specialCode.add(special.getCode());
                }
            });
            return CollectionUtils.isNotEmpty(specialCode) ? specialCode : null;
        }
        return null;
    }

    /**
     * @param code 专场编号
     * @param type 企业类型
     * @desc 专场编号查询关联企业ID
     * @author zk
     * @date 2023/12/16
     **/
    public List<Long> findEntIdsByCode(String code, String type) {
        //企业ID结果集
        List<Long> entIds = new ArrayList<>();
        //专场
        List<KwsSpecial> specials = kwsSpecialDao.findList(new HashMap<>(){{put("code", code);}});
        if (CollectionUtils.isNotEmpty(specials)) {
            KwsSpecial special = specials.get(NumberConstant.ZERO);
            entIds.add(special.getEntId());
            if (special.getIsMain() == NumberConstant.ONE) {
                //公共平台企业
                List<Long> entIdList = kwsEntSpecialDao.findListByEntType(new HashMap<>() {{
                    put("mainPlatform", NumberConstant.ONE);
                    put("type", type);
                }});
                if (entIdList.size()>0){
                    entIds.addAll(entIdList);
                }
            } else {
                //专场关联企业
                List<Long> entIdList = kwsEntSpecialDao.findListByEntType(new HashMap<>() {{
                    put("specialId", special.getId());
                    put("type", type);
                }});
                if (entIdList.size()>0){
                    entIds.addAll(entIdList);
                }
            }
            entIds = entIds.stream().distinct().collect(Collectors.toList());
        }
        return entIds;
    }

    /**
     * @param code 专场编号
     * @desc 专场编号查询是否为主平台
     * @author zk
     * @date 2023/12/16
     **/
    public boolean queryMainPlatform(String code) {
        //专场
        List<KwsSpecial> specials = kwsSpecialDao.findList(new HashMap<>(){{put("code", code);}});
        if (CollectionUtils.isNotEmpty(specials)) {
            KwsSpecial special = specials.get(NumberConstant.ZERO);
            return special.getIsMain() == NumberConstant.ONE;
        }
        return false;
    }
}
