package com.sifang.modules.account.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.entity.CrmTraderAccountSettleDetail;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlanMaterialEntry;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Repository
public class TraderAccountSettleDetailDao extends BaseDao<CrmTraderAccountSettleDetail> {

    Logger logger= LoggerFactory.getLogger(getClass());

    public List<Record> listSettleDetails(Map<String, String> queryParams, LayuiPage page) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select d.id, d.entry_id, d.power_station_code, d.trader_name,d.unit_price,d.capacity, d.type, d.amount, e.roof_type, e.scheme_type, e.scheme_type_name")
                .line(",e.tenant_name,d.settle_number, e.mobile,e.partner_name, d.project_code, d.project_name, d.create_time, d.end_time,d.flag,e.create_trader_name as createTraderName,e.create_trader_id,e.distributor_id,e.in_coming_time,e.province ")
                .line("from crm_trader_account_settle_detail d")
                .line("left join crm_trader t on d.trader_id=t.id")
                .line("left join crm_customer_entry e on d.entry_id=e.id")
                .line("where 1=1");
        appendSettleDetailsCondition(builder, queryParams);
        builder.line("order by d.create_time desc");
        builder.limit(page.getPage(), page.getLimit());
        return Db.find(builder.build(), builder.params());
    }

    public Long countSettleDetails(Map<String, String> queryParams) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(*)")
                .line("from crm_trader_account_settle_detail d")
                .line("left join crm_trader t on d.trader_id=t.id")
                .line("left join crm_customer_entry e on d.entry_id=e.id")
                .line("where 1=1");
        appendSettleDetailsCondition(builder, queryParams);
        return Db.queryLong(builder.build(), builder.params());
    }

    private void appendSettleDetailsCondition(SqlBuilder builder, Map<String, String> queryParams){
        if (StringUtil.checkParamValid(queryParams.get("objType"))) {
            builder.line("and d.obj_type = ?", queryParams.get("objType"));
        }
        if (StringUtil.checkParamValid(queryParams.get("partner"))) {
            builder.line("and e.partner_id = ?", queryParams.get("partner"));
        }
        if (StringUtil.checkParamValid(queryParams.get("projectId"))) {
            builder.line("and e.project_id = ?", queryParams.get("projectId"));
        }
        if (StringUtil.checkParamValid(queryParams.get("powerStationCode"))) {
            builder.like("and d.power_station_code like ?", queryParams.get("powerStationCode"));
        }
        if (StringUtil.checkParamValid(queryParams.get("projectName"))) {
            builder.like("and e.project_name like ?", queryParams.get("projectName"));
        }
        if (StringUtil.checkParamValid(queryParams.get("powerStationCode"))) {
            builder.like("and d.power_station_code like ?", queryParams.get("powerStationCode"));
        }
        if (StringUtil.checkParamValid(queryParams.get("traderIds"))) {
            builder.inst("and d.trader_id in ", queryParams.get("traderIds").split(","));
        }
        if(StringUtil.checkParamValid(queryParams.get("traderId"))){
            builder.line(" and d.trader_id = ? ",queryParams.get("traderId"));
        }
        if (StringUtil.checkParamValid(queryParams.get("traderName"))) {
            builder.like("and d.trader_name like ?", queryParams.get("traderName"));
        }
        if (StringUtil.checkParamValid(queryParams.get("traderMobile"))) {
            builder.like("and t.telephone like ?", queryParams.get("traderMobile"));
        }
        if (StringUtil.checkParamValid(queryParams.get("tenantName"))) {
            builder.like("and d.tenant_name like ?", queryParams.get("tenantName"));
        }
        if (StringUtil.checkParamValid(queryParams.get("mobile"))) {
            builder.like("and d.mobile like ?", queryParams.get("mobile"));
        }
        if (StringUtil.checkParamValid(queryParams.get("roofType"))) {
            builder.line("and e.roof_type = ?", queryParams.get("roofType"));
        }
        if (StringUtil.checkParamValid(queryParams.get("type"))) {
            builder.line("and d.type = ?", queryParams.get("type"));
        }
        if (StringUtil.checkParamValid(queryParams.get("flag"))) {
            if("1".equals(queryParams.get("flag"))){
               builder.line(" and (d.flag!='2' or d.flag is null)  ");
            }else {
                builder.line("and d.flag = ?", queryParams.get("flag"));
            }
        }
        if(StringUtil.checkParamValid(queryParams.get("twoTrader"))){
            builder.line(" and e.create_trader_id =? ",queryParams.get("twoTrader"));

        }
    }

    /**
     * 查询结算明细
     *
     * @param traderId 代理商id
     * @param objType  账户类型:0.待结算账户 1.质保金账户
     * @param type     结算类型:0.预结算 1.分包并网结算 2.电站整改(减) 3.质保金
     */
    public CrmTraderAccountSettleDetail findOneByCondition(String traderId, String objType, String type,String entryId) {
//        SqlBuilder sb = new SqlBuilder();
//        sb.line("SELECT sd.*");
//        sb.line("FROM crm_trader_account_settle_detail sd");
//        sb.line("WHERE sd.trader_id = ?", traderId);
//        sb.line("AND sd.obj_type = ?", objType);
//        sb.line("AND sd.type = ?", type);
//        sb.line("ORDER BY sd.create_time DESC LIMIT 1");
//        return Db.queryColumn(sb.build(), sb.params());
        StringBuilder sb = new StringBuilder();
        sb.append("from CrmTraderAccountSettleDetail ");
        sb.append("where traderId=:p1 and objType=:p2 and type=:p3 and entryId=:p4  ");
        sb.append("ORDER BY createTime DESC");
        List<CrmTraderAccountSettleDetail> list = find(sb.toString(), new Parameter(traderId,objType,type,entryId));
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    public List<CrmTraderAccountSettleDetail> findListByEntry(String entryId, String types) {
        StringBuilder sb = new StringBuilder();
        sb.append("from CrmTraderAccountSettleDetail ");
        sb.append("where entryId=:p1  ");
        if (StringUtil.isNotBlank(types)) {
            sb.append("and type in (").append(StringUtil.joinInSql(types.split(","))).append(") ");;
        }
        sb.append("ORDER BY createTime DESC");
        return find(sb.toString(), new Parameter(entryId));
    }

    /**
     * 创建结算明细
     */
    public CrmTraderAccountSettleDetail createOne(String entryId, String powerStationCode, String traderId, String traderName, String flag,
                                                  String objType, String type, BigDecimal amount, String roogType, String schemeType, String schemeTypeId,
                                                  String schemeTypeName, String tenantName, String mobile, String projectCode, String projectName,
                                                  BigDecimal unitPrice,BigDecimal capacity,
                                                  String createBy, Date createTime) {
        CrmTraderAccountSettleDetail detail = new CrmTraderAccountSettleDetail();
        detail.setEntryId(entryId);
        detail.setPowerStationCode(powerStationCode);
        detail.setTraderId(traderId);
        detail.setTraderName(traderName);
        detail.setFlag(flag);
        detail.setObjType(objType);
        detail.setType(type);
        detail.setAmount(amount);
        detail.setRoofType(roogType);
        detail.setSchemeType(schemeType);
        detail.setSchemeTypeId(schemeTypeId);
        detail.setSchemeTypeName(schemeTypeName);
        detail.setTenantName(tenantName);
        detail.setMobile(mobile);
        detail.setProjectCode(projectCode);
        detail.setProjectName(projectName);
        detail.setCreateBy(createBy);
        detail.setCreateTime(createTime);
        detail.setNumber("ZG"+PlantformUtils.getOrderNumber());
        detail.setUnitPrice(unitPrice);
        detail.setCapacity(capacity);
        return detail;
    }

    //奖励政策(每月的定时任务生成奖励政策时调用)
    public void saveSettle(String entryId,String powerStationCode,String traderId,String traderName,BigDecimal amount,Date date,String settleNumber){
        CrmTraderAccountSettleDetail detail = new CrmTraderAccountSettleDetail();
        detail.setEntryId(entryId);
        detail.setPowerStationCode(powerStationCode);
        detail.setTraderId(traderId);
        detail.setTraderName(traderName);
        detail.setFlag("3");  //奖励政策生成的时候，是未生效状态，到了越秀的投放款付款申请状态通过后 才生效
        detail.setObjType("0");
        detail.setType("4");
        detail.setAmount(amount);
        detail.setCreateBy("系统自动生成");
        detail.setCreateTime(date);
        detail.setNumber("ZG"+PlantformUtils.getOrderNumber());
        detail.setSettleNumber(settleNumber);
        save(detail);
    }

    //修改奖励政策的生效状态(越秀投放审查状态通过后调用)
    public void changeRewardSettleStatus(String entryId){
        logger.info(">>>>>>>>>>>changeRewardSettleStatus  entryId:{}",entryId);
        SQLQuery sqlQuery = getSession().createSQLQuery(" UPDATE `crm_trader_account_settle_detail` SET flag='0' WHERE obj_type='0' AND type='4'  AND flag='3' AND entry_id=:entryId ");
        sqlQuery.setParameter("entryId", entryId);
        int cou = sqlQuery.executeUpdate();
        logger.info(">>>>>>>>>>>>changeRewardSettleStatus entryId:{},cun:{} ",entryId,cou);
    }

    // 删除记录
    public boolean deleteDetail(CrmTraderAccountSettleDetail detail){
        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT INTO crm_trader_account_settle_detail_del (id,entry_id,power_station_code,trader_id,trader_name,")
                .append("flag,obj_type,type,amount,roof_type,scheme_type,scheme_type_id,scheme_type_name,tenant_name,mobile,")
                .append("project_code,project_name,create_by,create_time,end_time,king_dee_id,number,")
                .append("settle_number,unit_price,capacity,delete_time)")
                .append(" VALUES (:id,:entry_id,:power_station_code,:trader_id,:trader_name,:flag,:obj_type,:type,:amount,")
                .append(":roof_type,:scheme_type,:scheme_type_id,:scheme_type_name,:tenant_name,:mobile,:project_code,:project_name,")
                .append(":create_by,:create_time,:end_time,:king_dee_id,:number,:settle_number,")
                .append(":unit_price,:capacity,NOW())");
        Query query = getSession().createSQLQuery(sql.toString());
        query.setParameter("id", detail.getId());
        query.setParameter("entry_id", detail.getEntryId());
        query.setParameter("power_station_code", detail.getPowerStationCode());
        query.setParameter("trader_id", detail.getTraderId());
        query.setParameter("trader_name", detail.getTraderName());
        query.setParameter("flag", detail.getFlag());
        query.setParameter("obj_type", detail.getObjType());
        query.setParameter("type", detail.getType());
        query.setParameter("amount", detail.getAmount());
        query.setParameter("roof_type", detail.getRoofType());
        query.setParameter("scheme_type", detail.getSchemeType());
        query.setParameter("scheme_type_id", detail.getSchemeTypeId());
        query.setParameter("scheme_type_name", detail.getSchemeTypeName());
        query.setParameter("tenant_name", detail.getTenantName());
        query.setParameter("mobile", detail.getMobile());
        query.setParameter("project_code", detail.getProjectCode());
        query.setParameter("project_name", detail.getProjectName());
        query.setParameter("create_by", detail.getCreateBy());
        query.setParameter("create_time", detail.getCreateTime());
        query.setParameter("end_time", detail.getEndTime());
        query.setParameter("king_dee_id", detail.getKingDeeId());
        query.setParameter("number", detail.getNumber());
        query.setParameter("settle_number", detail.getSettleNumber());
        query.setParameter("unit_price", detail.getUnitPrice());
        query.setParameter("capacity", detail.getCapacity());
        int update = query.executeUpdate();
        if (update < 1) {
            return false;
        }

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