package com.sifang.modules.changes.dao;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.entity.CustomerEntryCompletionChangeRecord;
import com.sifang.modules.changes.entity.CustomerEntrySurveyChangeRecord;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.site.siteInfo.service.SiteEmployeeService;
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.dao.UserDao;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

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

/**
 * @author hz
 */

@Repository
public class CrmCompletionInfoChangeDao extends BaseDao<CustomerEntryCompletionChangeRecord> {

    @Autowired
    UserDao userDao;
    @Autowired
    SiteEmployeeService siteEmployeeService;

    public List<Record> selectList(LayuiPage<Record> page, Map<String, String> map, String flag, Operator operator) {
        SqlBuilder sf = new SqlBuilder();
        sf.line(" select a.id,a.number,a.power_station_code,a.`status`,a.num,a.creator,a.create_time,b.tenant_name,b.id_code,a.audit_time,a.create_by,m.assign_audit_user_id,b.partner_name");
        sf.line(" ,r.change_status,r.change_reason  from crm_customer_entry_completion_change_record a");
        sf.line(" inner join crm_customer_entry b on a.entry_id=b.id");
        sf.line("left join crm_item_manage as m on m.process_instance_id=a.id");
        sf.line(" left join crm_customer_entry_change_record r on r.change_id=a.id");
        sf.line(" where a.num>0");
        if ("1".equals(flag)) {
            sf.line(" and a.status in('1','2','3')");
        } else {
            sf.line(" and a.status ='0'");
        }
        getOrderMap(sf, map, operator);
        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, flag, operator);
            page.setCount(count);
        }
        List<Record> records = Db.find(sf.toString(), sf.params());
        ItemDispatchUtil.setReviewFlag(records);
        return records;
    }

    public long getCount(Map<String, String> map, String flag,Operator operator) {
        SqlBuilder sf = new SqlBuilder();
        sf.line(" select count(*)");
        sf.line(" from crm_customer_entry_completion_change_record a");
        sf.line(" inner join crm_customer_entry b on a.entry_id=b.id");
        sf.line(" where a.num>0 ");
        if ("1".equals(flag)) {
            sf.line(" and a.status in('1','2','3')");
        } else {
            sf.line(" and a.status ='0'");
        }
        getOrderMap(sf, map, operator);
        return Db.queryLong(sf.toString(), sf.params());
    }

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

            }
        }

        long  checkRo= userDao.isDefaultPlatRole(operator.getUserId());
        if (checkRo>0) {
            List<Record> employeeRole = siteEmployeeService.findEmployeeByUserId(operator.getUserId());
            List<String> provinceList = appendColumns(employeeRole, "provices");
            List<String> cityList = appendColumns(employeeRole, "city");
            List<String> numberList = appendColumns(employeeRole, "project_number");
            List<String> traderList = appendColumns(employeeRole, "trader_id");
            if (!provinceList.isEmpty()) {
                sf.inst("and b.province in ", provinceList);
            }
            if (!cityList.isEmpty()) {
                sf.inst("and b.city in ", cityList);
            }
            if (!numberList.isEmpty()) {
                sf.inst("and b.project_id in ", numberList);
            }

            if (!traderList.isEmpty()) {
                if (map.get("traderId") != null && !map.get("traderId").isEmpty()){
//                    builder.inst(" and e.distributor_id in ('"+ map.get("traderId") + "')");
                }else {
                    sf.inst(" and b.distributor_id in ",traderList);
                }

            }
        }

        if (StringUtil.checkParamsValid(map.get("authorizedId"))) {
            sf.inst("and b.project_id IN ", Arrays.asList(map.get("authorizedId").split(",")));
        }
        if (StringUtil.checkParamsValid(map.get("number"))) {
            sf.like("and a.number like ?", map.get("number"));
        }
        if (StringUtil.checkParamsValid(map.get("stationCode"))) {
            sf.like("and a.power_station_code like ? ", map.get("stationCode"));
        }
        if (StringUtil.checkParamsValid(map.get("tenantName"))) {
            sf.like("and b.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("auditTimeMin"))) {
            sf.line("and a.audit_time >= ? ", map.get("auditTimeMin") + " 00:00:00");
        }
        if (StringUtil.checkParamsValid(map.get("auditTimeMax"))) {
            sf.line("and a.audit_time <= ? ", map.get("auditTimeMax") + " 23:59:59");
        }
        if (StringUtil.checkParamsValid(map.get("status"))) {
            sf.line("and a.status = ? ", map.get("status"));
        }
        return sf.toString();
    }

    private List<String> appendColumns(List<Record> records, String column) {
        List<String> ret = new ArrayList<>();
        for (Record record : records) {
            String value = record.getStr(column);
            if (StrKit.notBlank(value)) {
                ret.addAll(Arrays.asList(value.split(",")));
            }
        }
        return ret;
    }

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

    public long selectNoAudited(String entryId, String id) {
        SqlBuilder sb = new SqlBuilder();
        sb.line("select count(1) from crm_customer_entry_completion_change_record where entry_id=? and status ='0'", entryId);
        if (StringUtil.isNotBlank(id)) {
            sb.line("and id <>?", id);
        }
        return Db.queryLong(sb.build(), sb.params());
    }

    public CustomerEntryCompletionChangeRecord selectPre(String entryId, int num) {
        Query query = getSession().createQuery(" from CustomerEntryCompletionChangeRecord where entryId=:p1 and num<:p2 and status='1' order by num desc");
        query.setParameter("p1", entryId);
        query.setParameter("p2", num);
        List<CustomerEntryCompletionChangeRecord> list = query.list();
        return list.get(0);
    }

}
