package com.sifang.modules.changes.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.entity.CrmCustomerEntryTenantChangeRecord;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.entity.CustomerEntry;
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 com.sifang.modules.taskdispatch.util.ItemDispatchUtil;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

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

@Repository
public class CrmCustomerEntryTenantChangeRecordDao extends BaseDao<CrmCustomerEntryTenantChangeRecord> {

    public void getListData(LayuiPage<Record> page, Map<String,String> map,Operator operator){
        SqlBuilder sf = new SqlBuilder();
        sf.line(" SELECT r.id,r.number,r.entry_id,r.create_name,DATE_FORMAT(r.create_time, '%Y-%m-%d %H:%i:%s') AS createTime,r.change_count ");
        sf.line(" ,r.status,e.power_station_code,e.tenant_name,e.id_code,a.change_status,a.change_reason,a.change_type ");
        sf.line(" ,DATE_FORMAT(r.audit_time, '%Y-%m-%d %H:%i:%s') AS auditTime,r.create_by,m.assign_audit_user_id  ");
        sf.line(" FROM `crm_customer_entry_tenant_change_record` r ");
        sf.line(" LEFT JOIN `crm_customer_entry`  e ON r.entry_id=e.id");
        sf.line("left join crm_item_manage as m on m.process_instance_id=r.id");
        sf.line(" left join crm_customer_entry_change_record a on a.change_id=r.id");
        sf.line(" WHERE 1=1 ");
        getOrderMap(sf,map,operator);
        sf.line(" order by r.create_time desc");
        if (page != null) {
            sf.line(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = getListCount(map,operator);
            page.setCount(count);
        }
        List<Record> list=Db.find(sf.toString(), sf.params());
        ItemDispatchUtil.setReviewFlag(list);
        page.setData(list);
    }

    public Long getListCount(Map<String,String> map,Operator operator){
        SqlBuilder sf = new SqlBuilder();
        sf.line("SELECT COUNT(r.id) ");
        sf.line(" FROM `crm_customer_entry_tenant_change_record` r ");
        sf.line(" LEFT JOIN `crm_customer_entry`  e ON r.entry_id=e.id");
        sf.line(" WHERE 1=1 ");
        getOrderMap(sf,map,operator);
        return Db.queryLong(sf.toString(),sf.params());
    }

    public void getOrderMap(SqlBuilder sf, Map<String, String> map, 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.二级代理商
                    sf.line(" and e.distributor_id =?" , traderId );
                }else{  //二级代理商
                    if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {
                        //代理商只能查看自己的
                        sf.line(" and e.create_trader_id =?" , traderId );
                    }
                }
            }else { //代理商人员
                String dataAuthority=record.getStr("data_authority");
                if("1".equals(type) && UserConstants.DATA_AUTHORITY_ALL.equals(dataAuthority)) {
                    sf.line(" and e.distributor_id =?" , traderId );
                }else {
                    sf.line(" and e.create_trader_id =?" , traderId );
                    if(StringUtil.isBlank(dataAuthority) || UserConstants.DATA_AUTHORITY_ONLY.equals(dataAuthority)){
                        sf.line(" and r.create_by =? ", operator.getUserId());
                    }
                }
            }
        }

        if (StringUtil.checkParamsValid(map.get("authorizedId"))) {
            sf.inst("and e.project_id IN ", Arrays.asList(map.get("authorizedId").split(",")));
        }
        if (StringUtil.checkParamsValid(map.get("number"))) {
            sf.like("and r.number like ?", map.get("number"));
        }
        if (StringUtil.checkParamsValid(map.get("powerStationCode"))) {
            sf.like("and e.power_station_code like ? ", map.get("powerStationCode"));
        }
        if (StringUtil.checkParamsValid(map.get("tenantName"))) {
            sf.like("and e.tenant_name like ? ", map.get("tenantName"));
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMin"))) {
            sf.line("and r.create_time >= ? ", map.get("createTimeMin") + " 00:00:00");
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMax"))) {
            sf.line("and r.create_time <= ? ", map.get("createTimeMax") + " 23:59:59");
        }
        if (StringUtil.checkParamsValid(map.get("auditStartTime"))) {
            sf.line("and r.create_time >= ? ", map.get("auditStartTime") + " 00:00:00");
        }
        if (StringUtil.checkParamsValid(map.get("auditEndTime"))) {
            sf.line("and r.create_time <= ? ", map.get("auditEndTime") + " 23:59:59");
        }
        if (StringUtil.checkParamsValid(map.get("status"))) {
            sf.inst("and r.status in ", map.get("status").split(","));
        }
        if (StringUtil.checkParamsValid(map.get("auditStatus"))) {
            sf.line("and r.status =? ", map.get("auditStatus"));
        }

        if(StringUtil.isNotBlank(map.get("provinceE"))){
            sf.inst(" and e.province in ",map.get("provinceE").split(","));
        }
        if(StringUtil.isNotBlank(map.get("cityE"))){
            sf.inst(" and e.city in  ",map.get("cityE").split(","));
        }
        if(StringUtil.isNotBlank(map.get("traderIdsE"))){
            sf.inst(" and e.create_trader_id in ",map.get("traderIdsE").split(","));
        }
        if (StringUtil.isNotBlank(map.get("projectNumberE"))) {
            sf.inst(" and e.project_id in ", map.get("projectNumberE").split(","));
        }
    }

    public Long getNumber(String entryId){
       return Db.queryLong(" SELECT COUNT(r.id) FROM crm_customer_entry_tenant_change_record r WHERE r.entry_id=?  ",entryId);
    }

    public Long getIfHaveChangeRecord(String entryId){
        return Db.queryLong("  SELECT COUNT(r.id) FROM crm_customer_entry_tenant_change_record r WHERE r.entry_id=? AND r.status='2' ",entryId);
    }

    public Record getByChangeId(String id){
        return Db.findFirst("  SELECT r.id,r.number,r.entry_id,r.power_station_code,r.create_name,r.create_time,r.change_reason,e.first_apply_status,r.entry_status,r.audit_remarks  " +
                " ,e.tenant_name,r.status,e.trader_name,e.project_company_name,e.project_name,e.id_code,e.province,e.city,e.area,e.street,e.address,CONCAT(e.province,e.city,e.area,e.address) AS customerAddress "+
                " FROM `crm_customer_entry_tenant_change_record` r " +
                "  LEFT JOIN `crm_customer_entry` e ON e.id=r.entry_id "+
                " WHERE r.id=? ",id);
    }

    public CustomerEntry getCanChangeEntry(String powerStationCode, Map<String,String> map){
        StringBuilder sb=new StringBuilder();
        sb.append(" from CustomerEntry where powerStationCode='"+powerStationCode+"' ");
        if(StringUtil.isNotBlank(map.get("traderId"))){
            sb.append(" and  createTraderId in ("+StringUtil.joinInSql(map.get("traderId").split(","))+")");
        }
        Query query =getSession().createQuery(sb.toString());
        return (CustomerEntry)query.uniqueResult();
    }
}
