package com.sifang.modules.changes.dao;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.entity.CustomerEntrySupplement;
import com.sifang.modules.customer.constant.UserConstants;
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.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.springframework.stereotype.Repository;

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

@Repository
public class CustomerEntrySupplementDao extends BaseDao<CustomerEntrySupplement> {

    public Record findEntrySupplementByentryId(String entryId){

        return Db.findFirst("select * from crm_customer_entry_supplement WHERE entry_id=? ORDER BY create_time desc  LIMIT 1" ,entryId);
    }

    public Record getChangeRecord(String id){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT r.id,r.number,r.entry_id,r.power_station_code,r.change_count,r.change_reason,r.audit_remarks,e.tenant_name ");
        sb.append(" ,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 ");
        sb.append("  FROM `crm_customer_entry_supplement` r   ");
        sb.append(" LEFT JOIN `crm_customer_entry` e ON e.id=r.entry_id ");
        sb.append(" WHERE r.id=? ");
        return Db.findFirst(sb.toString(),id);
    }

    public List<Record> selectList(LayuiPage<Record> page, Map<String, String> map, User user) {
        SqlBuilder sf = new SqlBuilder();
        sf.line(" select a.id,a.number,a.power_station_code,a.`status`,a.change_count,a.creator,a.create_time,e.tenant_name,e.id_code,a.audit_time,a.create_by,m.assign_audit_user_id ");
        sf.line(" from crm_customer_entry_supplement a");
        sf.line(" inner join crm_customer_entry e on a.entry_id=e.id");
        sf.line(" left join crm_item_manage as m on m.process_instance_id=a.id");
        sf.line(" where 1=1 ");
        getOrderMap(sf, map, user);
        sf.line(" order by a.create_time desc");
        if (page != null) {
            sf.line(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = getCount(map, user);
            page.setCount(count);
        }
        List<Record> records = Db.find(sf.build(), sf.params());
        ItemDispatchUtil.setReviewFlag(records);
        return records;
    }

    public long getCount(Map<String, String> map,User user) {
        SqlBuilder sf = new SqlBuilder();
        sf.line(" select count(*)");
        sf.line(" from crm_customer_entry_supplement a");
        sf.line(" inner join crm_customer_entry e on a.entry_id=e.id");
        sf.line(" where 1=1 ");
        getOrderMap(sf, map, user);
        return Db.queryLong(sf.toString(), sf.params());
    }

    public String getOrderMap(SqlBuilder sf, Map<String, String> map, User user) {
        if ("1".equals( map.get("tabType"))) {
            sf.line("and a.status in('1','2') ");
        }else{
            sf.line("and a.status in('3','4','0') ");
        }
        if(StringUtil.equalsAny(user.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)){
            Record record= CrmUtils.getUserTrader(user.getUserType(),user.getId());
            String traderId =record.getStr("id");
            String type = record.getStr("type");
            if(UserConstants.TYPE_TRADER.equals(user.getUserType())){  //代理商
                if ("1".equals(type)){  // 1.一级代理商 2.二级代理商
                    sf.line(" and e.distributor_id =?" , traderId );
                }else{  //二级代理商
                    if (UserConstants.TYPE_TRADER.equals(user.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 a.create_by =? ", user.getId());
                    }
                }

            }
        }

        if (StringUtil.checkParamsValid(map.get("number"))) {
            sf.like("and a.number like ?", map.get("number"));
        }
        if (StringUtil.checkParamsValid(map.get("stationCode"))) {
            sf.like("and e.power_station_code like ? ", map.get("stationCode"));
        }
        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 a.create_time >= ? ", map.get("createTimeMin") + " 00:00:00");
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMax"))) {
            sf.line("and a.create_time <= ? ", map.get("createTimeMax") + " 23:59:59");
        }
        if (StringUtil.checkParamsValid(map.get("status"))) {
            sf.line("and a.status = ? ", map.get("status"));
        }
        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("areaE"))){
            sf.inst(" and e.area in  ",map.get("areaE").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(","));
        }
        return sf.toString();
    }

    public Integer selectMaxNum(String entryId) {
        return Db.queryInt("select max(change_count) from crm_customer_entry_supplement where entry_id=? and status in('1','2','3','4')", entryId);
    }

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

}
