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

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlanMaterialEntry;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyMaterialKeep;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.util.SqlBuilder;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;


/**
 *
 */
@Repository
public class PlanMaterialEntryDao extends BaseDao<CrmPlanMaterialEntry> {

    public List<Record> listMaterialByPlanEntryId(String planId, String entryId) {
        return Db.find("select * from crm_plan_material where plan_id=? and entry_id=? order by sort", planId, entryId);
    }

    /**
     * 清除当前项目下的方案物料明细信息
     */
    public void deletePlanMaterialById(String id) {
        SQLQuery sqlQuery = getSession().createSQLQuery("DELETE FROM crm_plan_material_entry WHERE id=:id");
        sqlQuery.setParameter("id", id);
        sqlQuery.executeUpdate();
    }

    /**
     * 查询已使用物料详情
     */
    public List<CrmPlanMaterialEntry> findByEntryId(String entryId) {
        return find("from CrmPlanMaterialEntry where entryId =:p1 and status = '0'", new Parameter(entryId));
    }
    public List<CrmPlanMaterialEntry> findByEntryProjectId(String entryId, String[] projectIds) {
        return find("from CrmPlanMaterialEntry where entryId =:p1 and projectId IN("+ StringUtil.joinInSql(projectIds)+") and status = '0'", new Parameter(entryId));
    }

    public CrmPlanMaterialEntry findByEntryIdMaterial(String entryId, String materialId, String barcode) {
        return getByHql("from CrmPlanMaterialEntry where entryId =:p1 and status = '0' and materialId=:p2 and barcode=:p3"
                , new Parameter(entryId, materialId, barcode));
    }
    public CrmPlanMaterialEntry findByEntryIdMaterial(String entryId, String materialId, String barcode,String projectId) {
        return getByHql("from CrmPlanMaterialEntry where entryId =:p1 and status = '0' and materialId=:p2 and barcode=:p3 and projectId = :p4"
                , new Parameter(entryId, materialId, barcode,projectId));
    }

    public CrmPlanMaterialEntry findByEntryIdProjectMaterial(String entryId, String materialId, String barcode, String[] projectIds) {
        return getByHql("from CrmPlanMaterialEntry where entryId =:p1 and status = '0' and materialId=:p2 and barcode=:p3 and projectId IN("+ StringUtil.joinInSql(projectIds)+")"
                , new Parameter(entryId, materialId, barcode));
    }

    /**
     * 查询统计已使用最多物料规格
     */
    public List<Record> findMostSpecByEntryId(String entryId) {
        return Db.find("SELECT me.material_id, any_value(me.spec) as spec, any_value(me.type) as type, SUM(me.amount) AS amount FROM crm_plan_material_entry me WHERE me.entry_id = ?  and me.status = '0' GROUP BY me.material_id", entryId);
    }

    public List<Record> findNewMostSpecByEntryId(String entryId) {
        return Db.find("SELECT me.material_id, any_value(me.spec) as spec, any_value(me.type) as type, SUM(me.amount) AS amount FROM crm_plan_material_entry me WHERE me.entry_id = ?  and me.status = '0' and me.old_flag = '1' GROUP BY me.material_id", entryId);
    }

    public Long findMaterialSnByEntryId(String entryId) {
        return Db.queryLong("SELECT count(1) FROM crm_plan_material_entry me WHERE me.entry_id = ? and me.status='0' and me.sn is not null", entryId);
    }

    public Long getOldMostSpecCnt(String entryId) {
        return Db.queryLong("SELECT count(me.material_id) FROM crm_plan_material_entry me WHERE me.entry_id = ? and me.old_flag = '2'", entryId);
    }

    /**
     * 查询已使用物料详情
     */
    public List<CrmPlanMaterialEntry> findByIds(String ids) {
        StringBuilder sb = new StringBuilder();
        sb.append("from CrmPlanMaterialEntry where id in (" + StringUtil.joinInSql(ids.split(",")) + ")");
        return find(sb.toString());
    }

    /**
     * 获取电站物料使用明细
    */
    public List<Record> findMaterialListByEntryId(String entryId){
        SqlBuilder sql  = new SqlBuilder();
        sql.line(" SELECT p.*,m.`material_brand` FROM `crm_plan_material_entry` p ");
        sql.line(" LEFT JOIN `crm_supply_material` m ON m.`id`=p.`material_id` ");
        sql.line(" WHERE p.`entry_id`=? AND p.`status`='0' ",entryId);
        sql.line(" ORDER BY p.sort");

        return Db.find(sql.build(),sql.params());
    }

    public List<Record> findMaterialListByEntryProjectId(String entryId,String projectId){
        SqlBuilder sql  = new SqlBuilder();
        sql.line(" SELECT p.*,m.`material_brand` FROM `crm_plan_material_entry` p ");
        sql.line(" LEFT JOIN `crm_supply_material` m ON m.`id`=p.`material_id` ");
        sql.line(" WHERE p.`entry_id`=? AND p.`status`='0' ",entryId);
        sql.line(" AND p.project_id = ?",projectId);
        sql.line(" ORDER BY p.sort");

        return Db.find(sql.build(),sql.params());
    }

    // 用于查华融组件
    public Record countByEntryProjectId(String entryId,String projectId){
        SqlBuilder sql  = new SqlBuilder();
        sql.line(" SELECT count(p.id) as num, sum(p.spec) as total, p.spec FROM `crm_plan_material_entry` p ");
        sql.line(" WHERE p.`entry_id`=? AND p.`status`='0' and p.type = '组件' ",entryId);
        sql.line(" AND p.project_id = ?",projectId);
        return Db.findFirst(sql.build(),sql.params());
    }

    //查询已使用的组件记录 用于第二次进件
    public List<Record> findModuleByEntryId(String entryId){
        SqlBuilder sql  = new SqlBuilder();
        sql.line("SELECT me.material_id, me.spec, me.type, me.barcode, SUM(me.amount) AS amount,m.material_brand AS brand, me.model, me.sn , m.material_model ");
        sql.line(",any_value(m.material_brand) AS brand,me.project_id ");
        sql.line("FROM crm_plan_material_entry me");
        sql.line("LEFT JOIN crm_supply_material m ON me.material_id = m.id");
        sql.line("WHERE me.entry_id = ? AND me.type = '组件' GROUP BY me.material_id",entryId);
        return Db.find(sql.build(),sql.params());
    }
    //查询已使用的组件记录 用于多产品第二次进件
    public List<Record> findModuleByEntryId2(String entryId){
        SqlBuilder sql  = new SqlBuilder();
        sql.line("SELECT me.material_id, me.spec, me.type, me.barcode, SUM(me.amount) AS amount,m.material_brand AS brand, me.model, me.sn");
        sql.line(",any_value(m.material_brand) AS brand,me.project_id ");
        sql.line("FROM crm_plan_material_entry me");
        sql.line("LEFT JOIN crm_supply_material m ON me.material_id = m.id");
        sql.line("WHERE me.entry_id = ? AND me.type = '组件' GROUP BY me.project_id",entryId);
        return Db.find(sql.build(),sql.params());
    }
    //查询已使用的逆变器记录 用于第二次进件
    public List<Record> findInverterByEntryId(String entryId){
        SqlBuilder sql  = new SqlBuilder();
        sql.line("SELECT me.material_id, me.spec, me.type, me.barcode, me.amount ,m.material_brand AS brand, me.nbq_sn,me.model, me.sn,m.material_model ");
        sql.line("FROM crm_plan_material_entry me");
        sql.line("LEFT JOIN crm_supply_material m ON me.material_id = m.id");
        sql.line("WHERE me.entry_id = ? AND me.type = '逆变器'",entryId);
        return Db.find(sql.build(),sql.params());
    }

    //查询已使用的记录 用于第二次进件
    public List<Record> findCageByEntryId(String entryId,String type){
        SqlBuilder sql  = new SqlBuilder();
        sql.line("SELECT me.material_id, me.spec,me.model, me.type, me.barcode, me.amount ,m.material_brand AS brand, me.nbq_sn, me.amount,group_concat(barcode) as sns");
        sql.line("FROM crm_plan_material_entry me");
        sql.line("LEFT JOIN crm_supply_material m ON me.material_id = m.id");
        sql.line("WHERE me.entry_id = ? AND me.type = ? group by barcode, spec ",entryId,type);
        return Db.find(sql.build(),sql.params());
    }

    //统计电站的物料使用记录数
    public Long findCountByEntryId(String entryId,String type){
        SqlBuilder sql  = new SqlBuilder();
        sql.line("SELECT count(1)");
        sql.line("FROM crm_plan_material_entry me");
        sql.line("WHERE me.entry_id = ? AND me.type = ? ",entryId,type);
        return Db.queryLong(sql.build(),sql.params());
    }

    /**
     * 查询已使用的某类型的物料详情
     */
    public List<Record> findUsedByEntryId(String entryId, String type){
        SqlBuilder sql  = new SqlBuilder();
        sql.line("SELECT me.material_id, me.spec, me.type, me.barcode, me.amount");
        sql.line(",m.material_brand AS brand");
        sql.line("FROM crm_plan_material_entry me");
        sql.line("LEFT JOIN crm_supply_material m ON me.material_id = m.id");
        sql.line("WHERE me.entry_id = ? AND me.type = '"+type+"' AND me.status = '0' ",entryId);
        return Db.find(sql.build(),sql.params());
    }

    public List<Record> findNewMostSpecByEntryId3(String entryId){
        SqlBuilder sql  = new SqlBuilder();
        sql.line("SELECT me.material_id, me.spec, me.type, me.barcode, me.amount");
        sql.line(",m.material_brand AS brand");
        sql.line("FROM crm_plan_material_entry me");
        sql.line("LEFT JOIN crm_supply_material m ON me.material_id = m.id");
        sql.line("WHERE me.entry_id = ? AND me.type IN ('逆变器','组件')",entryId);

        return Db.find(sql.build(),sql.params());
    }

    /**
     * 查询已使用物料详情
     */
    public List<Record> findRecordByEntryId(String entryId) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT a.*,b.material_brand AS brand,b.material_model");
        sql.line("FROM crm_plan_material_entry a ");
        sql.line("LEFT JOIN crm_supply_material b ON a.material_id = b.id");
        sql.line("WHERE a.entry_id = ? AND a.status = '0'", entryId);
        return Db.find(sql.build(), sql.params());
    }

    /**
     * 查询已使用物料详情
     */
    public List<Record> findRecordByEntryProjectId(String entryId, String projectId) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT a.*,b.material_brand AS brand,b.material_model");
        sql.line("FROM crm_plan_material_entry a ");
        sql.line("LEFT JOIN crm_supply_material b ON a.material_id = b.id");
        sql.line("WHERE a.entry_id = ? AND a.status = '0'", entryId);
        sql.line("AND a.project_id = ?", projectId);
        return Db.find(sql.build(), sql.params());
    }

    /**
     * 创建使用记录
     */
    public void createOne(String materialId, String type, String code, String name, String spec, String unit,
                          String barcode, Integer amount, Date createTime, String entryId,String materialModel, String projectId) {
        CrmPlanMaterialEntry materialEntry = new CrmPlanMaterialEntry();
        materialEntry.setMaterialId(materialId);
        materialEntry.setType(type);
        materialEntry.setCode(code);
        materialEntry.setName(name);
        materialEntry.setSpec(spec);
        materialEntry.setUnit(unit);
        materialEntry.setBarcode(barcode);
        materialEntry.setAmount(amount);
        materialEntry.setSort(0);
        materialEntry.setCreateTime(createTime);
        materialEntry.setEntryId(entryId);
        materialEntry.setStatus("0");
        materialEntry.setOldFlag("1");
        materialEntry.setModel(materialModel);
        materialEntry.setProjectId(projectId);
        save(materialEntry);
    }

    public Record getEntryMaterial(String entryId){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT e.specs AS nbqSpec,e.num AS nbqNum,e.nbqBrand,b.specs AS bwxSpec,b.num AS bwxNum,f.zjBrand  FROM   ");
        sb.append(" (SELECT GROUP_CONCAT(c.spec SEPARATOR '/')AS specs,GROUP_CONCAT(c.amount SEPARATOR '/') AS num,c.entry_id,c.nbqBrand ");
        sb.append(" FROM ( ");
        sb.append(" SELECT c.spec,SUM(c.amount) AS amount,c.`entry_id`,csm.material_brand as nbqBrand ");
        sb.append(" FROM `crm_plan_material_entry` c " );
        sb.append(" LEFT JOIN crm_supply_material csm on c.material_id=csm.id " );
        sb.append(" WHERE   c.status='0' AND c.type='逆变器' AND c.entry_id=? GROUP BY c.material_id ");
        sb.append(" ) AS c ");
        sb.append(" ) AS e  ");
        sb.append(" JOIN  ");
        sb.append(" (SELECT GROUP_CONCAT(c.spec  SEPARATOR '/')AS specs,GROUP_CONCAT(c.amount SEPARATOR '/') AS num,c.entry_id ");
        sb.append(" FROM ( ");
        sb.append(" SELECT c.spec,SUM(c.amount) AS amount,c.`entry_id` ");
        sb.append(" FROM `crm_plan_material_entry` c  WHERE   c.status='0' AND c.type='并网箱' AND c.entry_id=? GROUP BY c.material_id ");
        sb.append(" ) AS c");
        sb.append(" ) AS b  ");
        sb.append(" JOIN ( " );
        sb.append( "SELECT" );
        sb.append(" csm.material_brand AS zjBrand " );
        sb.append(" FROM" );
        sb.append(" crm_plan_material_entry cpm" );
        sb.append(" LEFT JOIN crm_supply_material csm ON cpm.material_id = csm.id " );
        sb.append(" WHERE" );
        sb.append(" cpm.STATUS = '0' " );
        sb.append(" AND type = '组件' " );
        sb.append(" AND cpm.entry_id =? ");
        sb.append(" LIMIT 1 " );
        sb.append(" ) AS f");
        return Db.findFirst(sb.toString(),entryId,entryId,entryId);

    }
    // 删除记录
    public boolean deleteDetail(CrmPlanMaterialEntry detail){
        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT INTO crm_plan_material_entry_del (id,plan_id,material_id,type,code,name,spec,unit,barcode,amount,")
                .append("sort,entry_id,create_time,status,old_flag,sn,nbq_sn,yz_code,model,component_shape,battery_param,project_id,delete_time) ")
                .append("VALUES (:id,:plan_id,:material_id,:type,:code,:name,:spec,:unit,:barcode,:amount,:sort,:entry_id,:create_time,")
                .append(":status,:old_flag,:sn,:nbq_sn,:yz_code,:model,:component_shape,:battery_param,:project_id,NOW())");
        Query query = getSession().createSQLQuery(sql.toString());
        query.setParameter("id", detail.getId());
        query.setParameter("plan_id", detail.getPlanId());
        query.setParameter("material_id", detail.getMaterialId());
        query.setParameter("type", detail.getType());
        query.setParameter("code", detail.getCode());
        query.setParameter("name", detail.getName());
        query.setParameter("spec", detail.getSpec());
        query.setParameter("unit", detail.getUnit());
        query.setParameter("barcode", detail.getBarcode());
        query.setParameter("amount", detail.getAmount());
        query.setParameter("sort", detail.getSort());
        query.setParameter("entry_id", detail.getEntryId());
        query.setParameter("create_time", detail.getCreateTime());
        query.setParameter("status", detail.getStatus());
        query.setParameter("old_flag", detail.getOldFlag());
        query.setParameter("sn", detail.getSn());
        query.setParameter("nbq_sn", detail.getNbqSn());
        query.setParameter("yz_code", detail.getYzCode());
        query.setParameter("model", detail.getModel());
        query.setParameter("component_shape", detail.getComponentShape());
        query.setParameter("battery_param", detail.getBatteryParam());
        query.setParameter("project_id", detail.getProjectId());
        int update = query.executeUpdate();
        if (update < 1) {
            return false;
        }

        SQLQuery deleteQuery = getSession().createSQLQuery("DELETE FROM crm_plan_material_entry WHERE id=:id");
        deleteQuery.setParameter("id", detail.getId());
        int executed = deleteQuery.executeUpdate();
        return executed > 0;
    }
}
