package com.sifang.modules.quality.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.quality.entity.CrmEntryQualityAcceptanceDetail;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;


@Repository
public class CrmQualityRectificationDao extends BaseDao<CrmEntryQualityAcceptanceDetail> {

    public List<Record> getQualityRectificationList(Map<String,String> param, LayuiPage<Record> page, Operator operator){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line("  SELECT a.number,a.trader_id,a.trader_name,a.create_time,a.quality_emp_name,a.type,d.id,d.power_station_code,d.tenant_name,d.emp_user_id,d.change_emp_user_id,d.accept_status, ");
        sqlBuilder.line("  d.change_status,d.change_create_time,d.change_time,d.change_emp_name,'竣工验收' AS taskSource,d.accept_time,d.main_id,d.entry_id,c.address,c.tenant_type AS tenantType,c.create_by,c.creator ");
        sqlBuilder.line("  FROM crm_entry_quality_acceptance_detail d ");
        sqlBuilder.line("  LEFT JOIN crm_entry_quality_acceptance a ON a.id = d.main_id  ");
        sqlBuilder.line("  LEFT JOIN crm_customer_entry c ON c.power_station_code = d.power_station_code  ");
        sqlBuilder.line("  WHERE d.change_status is not null ");
        getCommonCondition(param,sqlBuilder,operator);
        sqlBuilder.line(" ORDER BY d.accept_time DESC ");
        if (page != null) {
            sqlBuilder.limit(page.getPage(), page.getLimit());
        }
        return Db.find(sqlBuilder.build(),sqlBuilder.params());
    }

    public Long getListCount(Map<String,String> param, Operator operator){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line("  SELECT COUNT(*) FROM crm_entry_quality_acceptance_detail d ");
        sqlBuilder.line("  LEFT JOIN crm_entry_quality_acceptance a ON a.id = d.main_id  ");
        sqlBuilder.line("  LEFT JOIN crm_customer_entry c ON c.id = d.entry_id ");
        sqlBuilder.line("  WHERE d.change_status is not null ");
        getCommonCondition(param,sqlBuilder,operator);
        return Db.queryLong(sqlBuilder.build(),sqlBuilder.params());
    }

    public void getCommonCondition(Map<String,String> param,SqlBuilder builder, Operator operator){

        if(StringUtil.equalsAny(operator.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)){
            Record record= CrmUtils.getUserTrader(operator.getUserType(),operator.getUserId());
            String traderId =record.getStr("id");
            String type = record.getStr("type");
            if(UserConstants.TYPE_TRADER.equals(operator.getUserType())){  //代理商
                if ("1".equals(type)){  // 1.一级代理商 2.二级代理商
                    builder.line(" AND a.trader_id IN ( SELECT id FROM crm_trader WHERE parent_id = "+"'"+traderId+"') " );
                }else{  //二级代理商
                    if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {
                        //代理商只能查看自己的
                        builder.line(" AND c.create_by ="+"'"+operator.getUserId()+"'" );
                    }
                }
            }
        }

        if (StringUtil.checkParamsValid(param.get("powerStationCode"))) {
            builder.line(" AND d.power_station_code LIKE '%"+param.get("powerStationCode")+"%' ");
        }
        if (StringUtil.checkParamsValid(param.get("tenantName"))) {
            builder.line(" AND d.tenant_name LIKE '%"+param.get("tenantName")+"%' ");
        }
        if (StringUtil.checkParamsValid(param.get("number"))) {
            builder.like(" AND a.number LIKE ?",param.get("number"));
        }
        if (StringUtil.checkParamsValid(param.get("changeStatus"))) {
            if("1".equals(param.get("changeStatus"))){
                builder.line("and d.change_status IN ('1','2','4')");
            }else {
                builder.line("and d.change_status = "+param.get("changeStatus"));
            }

        }
        if (StringUtil.checkParamsValid(param.get("traderId"))) {
            builder.line("and a.trader_id = "+"'"+ param.get("traderId")+"'");
        }
        if (StringUtil.checkParamsValid(param.get("type"))) {
            builder.line("and a.type = ", param.get("type"));
        }
        if (StringUtil.checkParamsValid(param.get("createTimeSta"))) {
            builder.line(" and d.change_create_time >= '" + param.get("createTimeSta") + " 00:00:00' ");
        }
        if (StringUtil.checkParamsValid(param.get("createTimeEnd"))) {
            builder.line(" and d.change_create_time <= '" + param.get("createTimeEnd") + " 23:59:59' ");
        }
        if (StringUtil.checkParamsValid(param.get("sign"))) {
            String sign = param.get("sign");
            if(sign.equals("work")){
                builder.line(" AND d.change_emp_user_id = '"+param.get("userId")+"'");
            }else if(sign.equals("dispatch")){
                builder.line(" AND c.distributor_id = '"+param.get("userId")+"'");
            }else if(sign.equals("examine")){
                builder.line(" AND d.emp_user_id = '"+param.get("userId")+"'");
            }
        }
        if(StringUtil.checkParamsValid(param.get("smallCondition"))){
            builder.line(" AND d.tenant_name LIKE '%"+param.get("smallCondition")+"%'  ");
            builder.line("or d.power_station_code LIKE '%"+param.get("smallCondition")+"%' ");
            builder.line(" or a.number LIKE '%"+param.get("smallCondition")+"%' ");
        }
    }

    public List<Record> getDispatchEmpList(Map<String,String> param, Operator operator){
        StringBuilder sb = new StringBuilder();
        sb.append(" SELECT e.user_id AS id,e.name,e.mobile,COUNT( q.id ) AS waitCount ");
        sb.append(" FROM crm_trader_employe e ");
        sb.append(" LEFT JOIN crm_entry_quality_acceptance_detail q ON q.change_emp_user_id = e.id AND q.change_status = '2' ");
        sb.append(" AND q.accept_status = '2' ");
        sb.append(" WHERE e.status='0' ");

        if(StringUtil.equalsAny(operator.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)){
            Record record= CrmUtils.getUserTrader(operator.getUserType(),operator.getUserId());
            String traderId =record.getStr("id");
            String type = record.getStr("type");
            if(UserConstants.TYPE_TRADER.equals(operator.getUserType())){  //代理商
                if ("1".equals(type)){  // 1.一级代理商 2.二级代理商
                    if(param.get("traderId").equals(traderId)){
                        sb.append(" AND e.trader_id =  '"+traderId+"' ");
                    }else{
                        sb.append(" AND e.trader_id IN ( SELECT id FROM crm_trader WHERE parent_id = "+"'"+traderId+"') " );
                    }
                }else{  //二级代理商
                    if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {
                        //代理商只能查看自己的
                        sb.append(" AND e.trader_id =  '"+traderId+"' ");
                    }
                }
            }
        }

        if(StringUtil.checkParamsValid(param.get("empName"))){
            sb.append(" AND e.name like '%"+param.get("empName")+"%' ");
        }
        sb.append(" GROUP BY e.id ORDER BY e.create_time ASC ");
        return Db.find(sb.toString());
    }

}