package com.sifang.modules.sunshine.SystemSetting.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectInstallDao;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectTypeReferenceDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectInstallWay;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectTypeReference;
import com.sifang.modules.sunshine.SystemSetting.form.AddProjectInstallWay;
import com.sifang.modules.sunshine.SystemSetting.form.ProjectTypeDetailVo;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hongzq
 */
@Service
public class ProjectInstallService extends BaseService {

    @Autowired
    ProjectInstallDao projectInstallDao;
    @Autowired
    private ProjectTypeReferenceDao referenceDao;

    public CrmProjectInstallWay getById(String id){
        return projectInstallDao.get(id);
    }

    public void listProjectInstallWays(LayuiPage<Record> page) {
        List<Record> list = projectInstallDao.selectProjectInstalls(page);
        Long count = projectInstallDao.countProjectInstalls();
        page.setData(list);
        page.setCount(count);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(AddProjectInstallWay way) {
        CrmProjectInstallWay projectSetting = new CrmProjectInstallWay();
        projectSetting.setName(way.getName());
        projectSetting.setIsOpenReference(way.getIsOpenReference());
        checkNameExists(projectSetting.getName(), "");
        projectSetting.setId(null);
        projectSetting.setStatus(SourceConstants.ZERO);
        projectSetting.setCreateBy(UserUtils.getUser().getId());
        projectSetting.setCreator(CrmUtils.getUserXM(UserUtils.getUser()));
        projectSetting.setCreateTime(new Date());
        projectInstallDao.save(projectSetting);
        if(way.getIsOpenReference().equals("1")){
            List<CrmProjectTypeReference> reference = way.getReferences();
            for(CrmProjectTypeReference ref :reference){
                ref.setInstallWayId(projectSetting.getId());
            }
            referenceDao.save(reference);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(AddProjectInstallWay setting) {
        checkNameExists(setting.getName(), setting.getId());
        CrmProjectInstallWay projectSetting = projectInstallDao.get(setting.getId());
        projectSetting.setName(setting.getName());
        projectSetting.setUpdateBy(UserUtils.getUser().getId());
        projectSetting.setUpdator(CrmUtils.getUserXM(UserUtils.getUser()));
        projectSetting.setUpdateTime(new Date());
        projectSetting.setIsOpenReference(setting.getIsOpenReference());
        projectInstallDao.save(projectSetting);
        referenceDao.deleteVariable(setting.getId());
        if(setting.getIsOpenReference().equals("1")){
            List<CrmProjectTypeReference> reference = setting.getReferences();
            for(CrmProjectTypeReference ref :reference){
                ref.setInstallWayId(projectSetting.getId());
            }
            referenceDao.save(reference);
        }
    }

    public List<CrmProjectTypeReference> getProjectReference(String installWayId){
      return   referenceDao.getProjectReference(installWayId);
    }

    public List<ProjectTypeDetailVo> getProjectReference2(String installWayId){
        List<CrmProjectTypeReference> list=getProjectReference(installWayId);
        Map<String,List<CrmProjectTypeReference>> map=new HashMap<>();
        for(CrmProjectTypeReference c:list){
            List<CrmProjectTypeReference> list1=map.get(c.getItemCode());
            if(list1==null){
                list1=new ArrayList<>();
            }
            list1.add(c);
            map.put(c.getItemCode(),list1);
        }
        List<ProjectTypeDetailVo> detailVos=new ArrayList<>();
        for(Map.Entry<String,List<CrmProjectTypeReference>> entry: map.entrySet()){
             String key=entry.getKey();
             List<CrmProjectTypeReference> value=entry.getValue();
             ProjectTypeDetailVo vo=new ProjectTypeDetailVo();
             vo.setItemCode(key);
             vo.setList(value);
             detailVos.add(vo);
        }
        return detailVos;
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String ids) {
        List<CrmProjectInstallWay> installWays = new ArrayList<>();
        for(String id: ids.split(",")){
            CrmProjectInstallWay setting = projectInstallDao.get(id);
            setting.setStatus(SourceConstants.ONE);
            setting.setUpdateBy(UserUtils.getUser().getId());
            setting.setUpdator(CrmUtils.getUserXM(UserUtils.getUser()));
            setting.setUpdateTime(new Date());
            if(checkIfUse(id)){
                throw new IllegalArgumentException(setting.getName()+"该方案类型正在使用中，不能删除!");
            }
            installWays.add(setting);
        }
        projectInstallDao.save(installWays);
    }

    public void checkNameExists(String name, String excludeId) {
        if (projectInstallDao.countExistsName(name, excludeId) > 0) {
            throw new BusinessException("安装方式名称已存在");
        }
    }

    public List<Record> findProjectInstalls(){
        return projectInstallDao.findProjectInstalls("");
    }
    public List<Record> findProjectInstalls(String id){
        return projectInstallDao.findProjectInstalls(id);
    }
    /**
     * 获取添加过方案的安装方式
    */
    public List<Record> findPlanProInsta(){
        return Db.find("SELECT plan_type_id AS id ,plan_type AS name FROM crm_plan WHERE  STATUS='0' AND TYPE='2' AND plan_type_id  IS NOT NULL GROUP BY plan_type_id");
    }

    public boolean checkIfUse(String id){
        Long count=Db.queryLong("SELECT COUNT(e.id) FROM `crm_customer_entry` e WHERE scheme_type_id LIKE '%"+id+"%' AND design_audit_flag IN('1','2','3','4','5','7') ");
        return count>0?true:false;
    }

    //保存表单设置里面设置的示例图
    @Transactional(rollbackFor = Exception.class)
    public void saveSetExampleImg(AddProjectInstallWay setting){
        referenceDao.deleteVariable(setting.getId());
        List<CrmProjectTypeReference> reference = setting.getReferences();
        for(CrmProjectTypeReference ref :reference){
            ref.setInstallWayId(setting.getId());
        }
        referenceDao.save(reference);
    }
}
