package com.sifang.modules.customer.Service;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.CustomerEntryComponentDao;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.entity.CustomerEntryComponent;
import com.sifang.modules.customer.form.CustomerEntryComponentVo;
import com.sifang.modules.sunshine.SystemSetting.dao.ElectricSetDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.form.FormSetPageVo;
import com.sifang.modules.sunshine.SystemSetting.service.FormSetService;
import com.sifang.modules.sunshine.SystemSetting.service.ProjectInfoSettingService;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.dao.FormSetDao;
import com.sifang.modules.sys.util.SqlBuilder;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CustomerEntryComponentService {

    @Autowired
    private CustomerEntryComponentDao entryComponentDao;

    @Autowired
    private ElectricSetDao electricSetDao;

    @Autowired
    private FormSetService formSetService;

    @Autowired
    private ProjectInfoSettingService projectService;
    @Autowired
    private CustomerEntryDao entryDao;

    /**
     * 保存项目电器组件
     */
    public void saveEntryComponent(List<CustomerEntryComponentVo> list, String entryId, String userId) {
        CustomerEntry entry = entryDao.get(entryId);
//        CrmProjectSetting pro = projectService.getById(entry.getProjectId());
        Record formSet = formSetService.getListByCondition("02", entry.getPartnerId());
        FormSetPageVo component3Model = formSet.get("component3_model");
        FormSetPageVo component1Model = formSet.get("component1_model");
        List<CustomerEntryComponent> components = new ArrayList<>();
        List<Record> recordList = new ArrayList<>();
        List<String> collect = list.stream().map(CustomerEntryComponentVo::getItemId).collect(Collectors.toList());
        if (collect.size() > 0){
            recordList = electricSetDao.findByIds(collect);
        }
        for (CustomerEntryComponentVo vo : list) {
            CustomerEntryComponent component = new CustomerEntryComponent();
            component.setEntryId(entryId);
            component.setItemType(vo.getItemType());
            component.setItemId(vo.getItemId());
            component.setProjectId(vo.getProjectId());
            for (Record record : recordList) {
                if (record.getStr("id").equals(vo.getItemId())){
                    component.setSpecs(record.getStr("model"));
                    //组件型号表单开启
                    if ("3".equals(vo.getItemType()) && component3Model != null &&
                            "1".equals(component3Model.getStatus())){
                        component.setMaterialModel(record.getStr("material_model"));
                    }
                    //逆变器型号表单开启
                    if ("1".equals(vo.getItemType()) && component1Model != null &&
                            "1".equals(component1Model.getStatus())){
                        component.setMaterialModel(record.getStr("material_model"));
                    }
                    break;
                }
            }
            component.setNum(vo.getNum());
            component.setCreateTime(new Date());
            component.setCreateBy(userId);
            component.setStatus("0");
            components.add(component);
        }
        entryComponentDao.save(components);
    }

    /**
     * 删除项目电器组件
     */
    public void deleteEntryComponent(String entryId) {
        SQLQuery query = entryComponentDao.getSession()
                .createSQLQuery("update crm_customer_entry_component set status = '1' where entry_id =:entryId");
        query.setParameter("entryId", entryId);
        int count = query.executeUpdate();
    }

    /**
     * 删除项目电器组件
     */
    public void deleteComponentByEntryId(String entryId) {
        SQLQuery query = entryComponentDao.getSession()
                .createSQLQuery("delete from crm_customer_entry_component where status = '1' and entry_id =:entryId");
        query.setParameter("entryId", entryId);
        int count = query.executeUpdate();
    }

    /**
     * 获取电站电器材料
     */
    public List<Record> findByEntryId(String entryId) {
        return entryComponentDao.findByEntryId(entryId);
    }
    public List<Record> findByEntryIdForSmallPrograms(String entryId) {
        return entryComponentDao.findByEntryId2ForSmallPrograms(entryId);
    }
    public List<Record> findByEntryIdByProjectId(String entryId,String projectId) {
        return entryComponentDao.findByEntryIdByProjectId(entryId,projectId);
    }
    public List<Record> findByEntryIdByProjectIdForSmallPrograms(String entryId,String projectId) {
        return entryComponentDao.findByEntryIdByProjectIdForSmallPrograms(entryId,projectId);
    }
    /**
     * 查询汇总多个电站下单物料信息
     */
    public List<Record> findByEntryIds(List<String> ids) {
        return entryComponentDao.findByEntryIds(ids);
    }

    public void designChange(String entryId, List<Record> components) {
        // 删除旧组件信息
        SqlBuilder sb2 = new SqlBuilder()
                .line("update crm_customer_entry_component")
                .line("set status='1'")
                .line("where entry_id=:entry_id and status='0'");
        SQLQuery query2 = entryComponentDao.getSession().createSQLQuery(sb2.build());
        query2.setString("entry_id", entryId);
        int affected = query2.executeUpdate();
        if (affected < 1) {
            throw new BusinessException("");
        }
        CustomerEntry entry = entryDao.get(entryId);
        Record formSet = formSetService.getListByCondition("02", entry.getPartnerId());
        FormSetPageVo component3Model = formSet.get("component3_model");
        FormSetPageVo component1Model = formSet.get("component1_model");
        List<Record> recordList = new ArrayList<>();
        List<String> collect = components.stream().map(r -> r.getStr("item_id")).collect(Collectors.toList());
        if (collect.size() > 0){
            recordList = electricSetDao.findByIds(collect);
        }
        // 重新添加新组件信息
        for (Record r : components) {
            CustomerEntryComponent component = new CustomerEntryComponent();
            component.setEntryId(entryId);
            if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                component.setProjectId(r.getStr("project_id"));
            }
            component.setItemType(r.getStr("item_type"));
            component.setItemId(r.getStr("item_id"));
            component.setNum(r.getInt("num"));
            component.setStatus("0");
            component.setCreateTime(new Date());
            component.setCreateBy(UserUtils.getUser().getId());
            for (Record record : recordList) {
                if (record.getStr("id").equals(r.getStr("item_id"))){
                    component.setSpecs(record.getStr("model"));
                    //组件型号表单开启
                    if ("3".equals(r.getStr("item_type")) && component3Model != null &&
                            "1".equals(component3Model.getStatus())){
                        component.setMaterialModel(record.getStr("material_model"));
                    }
                    //逆变器型号表单开启
                    if ("1".equals(r.getStr("item_type")) && component1Model != null &&
                            "1".equals(component1Model.getStatus())){
                        component.setMaterialModel(record.getStr("material_model"));
                    }
                    break;
                }
            }
            entryComponentDao.save(component);
        }
    }

    public List<Record> findModelByEntryId(String entryId) {
        return entryComponentDao.findModelByEntryId(entryId);
    }

    public List<Record> findModelByEntryProjectId(String entryId,String projectId) {
        return entryComponentDao.findModelByEntryProjectId(entryId,projectId);
    }
}
