package com.sifang.modules.sunshine.SystemSetting.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.entity.*;
import com.sifang.modules.sunshine.SystemSetting.form.AddAreaVo;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

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

@Repository
public class ProjectCompanyDao extends BaseDao<ProjectCompanySettings> {

    @Autowired
    TraderDao traderDao;

    public ProjectCompanySettings  getByAuthFlowId(String authFlowId){
        return getByHql(" from ProjectCompanySettings where authFlowId= :p1 ", new Parameter(authFlowId));
    }

    public Record getProjectByPCId(String pcId){
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT * ");
        builder.line("FROM crm_project_company_settings");
        builder.line("WHERE id = ?",pcId);
        return Db.findFirst(builder.build(), builder.params());
    }

    public Record getProjectCompanyByIds(String id){
        List<Record> projectList = new ArrayList<>();
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT * ");
        builder.line("FROM crm_project_company_settings");
        builder.line("WHERE type = '0' and  id = ?",id);
        return Db.findFirst(builder.build(), builder.params());
    }




    public Record getProjectCompanyDetail(String id){
        StringBuffer sb=new StringBuffer();
        sb.append("  SELECT s.id,s.name,s.enterprise_qualification_number,s.charge_person,s.charge_person_id_card ,s.authorize_province,s.authorize_city,s.authorize_area  ");
        sb.append(" ,telephone,s.province,s.city,s.area,s.address,s.status,DATE_FORMAT(s.create_time,'%Y-%m-%d %H:%i:%s')AS createTime  ");
        sb.append(",s.type,s.business_license,s.certification_img_name,s.company_code,s.partner,s.filing_type,s.insurance_name,s.insurance_id,s.insurance_url ,s.seal_external_auth");
        sb.append(" ,DATE_FORMAT(s.seal_effective_time,'%Y-%m-%d')AS effectiveTime,DATE_FORMAT(s.seal_expire_time,'%Y-%m-%d')AS expireTime,s.psn_account ");
        sb.append(" FROM `crm_project_company_settings` s ");
        sb.append(" WHERE s.status<>'2' and s.id= ? ");
        return Db.findFirst(sb.toString(),id);
    }

    public List<Record> getProjectCompany(){
        StringBuffer sb=new StringBuffer();
        sb.append(" select s.id,s.name,s.company_code from crm_project_company_settings s ");
        sb.append(" where s.status='0' ");
        return Db.find(sb.toString());
    }

    public List<Record> getProjectCompany(String type){
        StringBuffer sb=new StringBuffer();
        sb.append(" select s.id,s.name,s.company_code from crm_project_company_settings s ");
        sb.append(" where s.status='0' and type=?");
        return Db.find(sb.toString(), type);
    }
    public List<Record> getProjectCompanyById(String type,String id){
        StringBuffer sb=new StringBuffer();
        sb.append(" select s.id,s.name,s.company_code from crm_project_company_settings s ");
        sb.append(" where s.status='0' and type=?");
        return Db.find(sb.toString(), type);
    }

    public void projectCompanyList(LayuiPage<Record> page, Map<String, String> map){
        SqlBuilder sf = new SqlBuilder();
        sf.line(" SELECT s.id,s.name,s.enterprise_qualification_number,s.charge_person,s.charge_person_id_card,s.company_code,s.type ,s.filing_type ");
        sf.line(" ,telephone,CONCAT(s.province,s.city,s.area,s.address) AS address,s.status,DATE_FORMAT(s.create_time,'%Y-%m-%d %H:%i:%s')AS createTime ,p.name as partnerName,s.partner ");
        sf.line(",s.seal_external_auth,s.psn_account ");
        sf.line(" FROM `crm_project_company_settings` s ");
        sf.line(" left join crm_partner p on p.id = s.partner and p.status = '0' ");
        sf.line(" WHERE s.status<>'2' " );
        getConditionMap(map, sf);
        sf.line(" ORDER BY s.create_time DESC  ");
        if (page != null) {
            sf.line(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = getCount(map);
            page.setCount(count);
        }
        List<Record> list = Db.find(sf.build(), sf.params());
        page.setData(list);
    }

    public void projectCompanyPage(LayuiPage<Record> page, Map<String, String> map, List<AddAreaVo> areaList){
        SqlBuilder sf = new SqlBuilder();
        sf.line("  SELECT cs.* , GROUP_CONCAT(DISTINCT cp.province ORDER BY cp.province SEPARATOR ',') AS provinces,GROUP_CONCAT(DISTINCT cp.city ORDER BY cp.city SEPARATOR ',') AS citys, " +
                        " GROUP_CONCAT(DISTINCT cp.area ORDER BY cp.area SEPARATOR ',') AS areas")
                .line(" FROM crm_project_company_settings cs")
                .line(" LEFT JOIN crm_project_company_pcd cp on cp.company_id = cs.id")
                .line("where cs.`status` = '0' and cs.type = '0' and cp.`status` = '0'");
        if ( !areaList.isEmpty()){
            sf.line(" and ( ");
            for (int i=0;i< areaList.size();i++) {
                AddAreaVo addAreaVo = areaList.get(i);
                sf.line(" ( ");
                if (StringUtil.isBlank(addAreaVo.getCity())) {
                    sf.line(" cp.province = ?", addAreaVo.getProvince());
                }
                else if (StringUtil.isNotBlank(addAreaVo.getArea())) {
                    sf.line(" ( cp.province = ? and cp.city = '' and  cp.area = '' )", addAreaVo.getProvince());
                    sf.line(" or ( cp.province = ? and cp.city = ? and  cp.area = '' )", addAreaVo.getProvince(), addAreaVo.getCity());
                    sf.line(" or ( cp.province = ? and cp.city = ? and  cp.area = ?)", addAreaVo.getProvince(), addAreaVo.getCity(), addAreaVo.getArea());
                }
                else {
                    sf.line(" ( cp.province = ? and cp.city = '' ) ", addAreaVo.getProvince());
                    sf.line(" or ( cp.province = ? and cp.city = ? )", addAreaVo.getProvince(), addAreaVo.getCity());
                }
                sf.line(" ) ");
                if (i < areaList.size() - 1) {
                    sf.line(" or  ");
                }
            }
            sf.line(" ) ");
        }
        if (StringUtil.isNotBlank(map.get("code"))) {
            sf.line(" and  cs.company_code like concat('%',?,'%')",map.get("code"));
        }
        if (StringUtil.isNotBlank(map.get("name"))) {
            sf.line(" and  cs.name like concat('%',?,'%')",map.get("name"));
        }
        String prov = map.get("province");
        String city = map.get("city");
        String area = map.get("area");
        if (StringUtil.isNotBlank(area) && StringUtil.isNotBlank(city) && StringUtil.isNotBlank(prov)) {
            sf.line(" and ( (cp.area = ? and cp.city = ? and cp.province = ?) or (cp.city = ? and cp.area = '') or (cp.province = ? and cp.city = '') )",
                    area, city, prov, city, prov);
        }
        else if (StringUtil.isNotBlank(city) && StringUtil.isNotBlank(prov)) {
            sf.line(" and  (cp.city = ? or (cp.province = ? and cp.city = '') )",city, prov);
        }
        else if (StringUtil.isNotBlank(prov)) {
            sf.line(" and  cp.province = ?",prov);
        }
        sf.line(" GROUP BY cs.id");
        sf.line(" ORDER BY cs.create_time DESC  ");
        if (page != null) {
            sf.line(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = getCountPage(map,areaList);
            page.setCount(count);
        }
        List<Record> list = Db.find(sf.build(), sf.params());
        page.setData(list);
    }


    public long getCount(Map<String, String> map){
        SqlBuilder sf = new SqlBuilder();
        sf.line(" SELECT COUNT(s.id) FROM `crm_project_company_settings` s  WHERE s.status<>'2' and type = '0'  ");
        getConditionMap(map, sf);
        return Db.queryLong(sf.build(), sf.params());
    }

    public long getCountPage(Map<String, String> map, List<AddAreaVo> areaList){
        SqlBuilder sf = new SqlBuilder();
        sf.line(" SELECT COUNT(s.id) FROM `crm_project_company_settings` s  WHERE s.status<>'2' and type = '0'  ");
        if (!areaList.isEmpty()){
            sf.line(" and (");
            int i = 1;
            for (AddAreaVo addAreaVo : areaList) {
                if (i++ != 1){
                    sf.line(" or");
                }
                if (StringUtil.isNotBlank(addAreaVo.getProvince())){
                    sf.line("  s.id in (select id from crm_project_company_settings where authorize_province = ? ",addAreaVo.getProvince());
                }
                if (StringUtil.isNotBlank(addAreaVo.getCity())){
                    sf.line(" and  authorize_city = ?",addAreaVo.getCity());
                }
                if (StringUtil.isNotBlank(addAreaVo.getArea())){
                    sf.line(" and authorize_area = ?",addAreaVo.getArea());
                }
                sf.line(" )");
            }
            sf.line(" )");
        }
        getConditionMapPage(map, sf);
        return Db.queryLong(sf.build(), sf.params());
    }

    public void getConditionMap(Map<String, String> map, SqlBuilder sf) {
        if (StringUtil.isNotBlank(map.get("name"))) {
            sf.like(" AND s.name LIKE ? ", map.get("name"));
        }
        if (StringUtil.isNotBlank(map.get("type"))) {
            sf.line(" AND s.type = ? ", map.get("type"));
        }
        if (StringUtil.isNotBlank(map.get("partnerId"))) {
            sf.line(" AND s.partner = ? ", map.get("partnerId"));
        }
    }

    public void getConditionMapPage(Map<String, String> map, SqlBuilder sf) {
        if (StringUtil.isNotBlank(map.get("code"))) {
            sf.line(" and  company_code like concat('%',?,'%')",map.get("code"));
        }
        if (StringUtil.isNotBlank(map.get("name"))) {
            sf.line(" and  name like concat('%',?,'%')",map.get("name"));
        }
        if (StringUtil.isNotBlank(map.get("province"))) {
            sf.line(" and  province = ?",map.get("province"));
        }
        if (StringUtil.isNotBlank(map.get("province"))) {
            sf.line(" and  province = ?",map.get("province"));
        }
        if (StringUtil.isNotBlank(map.get("city"))) {
            sf.line(" and  city = ?",map.get("city"));
        }
        if (StringUtil.isNotBlank(map.get("area"))) {
            sf.line(" and  area = ?",map.get("area"));
        }
    }

    public long queryByName(String name) {
        return Db.queryLong("SELECT COUNT(1) FROM crm_project_company_settings WHERE status = '0' AND name = ?", name);
    }

    /**
     * 校验公司代码是否重复
     */
    public boolean checkUniqueByCode(String code,String id) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT COUNT(1) FROM crm_project_company_settings WHERE status = '0' AND company_code = ?",code);
        if(StringUtil.isNotBlank(id)){
            sql.line(" and id<>?",id);
        }
        return Db.queryLong(sql.build(),sql.params()) > 0;
    }


    public boolean checkAuth4(String id, String province, String city, String area) {
        List<ProjectCompanySettings> pcdList = find("from ProjectCompanySettings  where id = :p1 ", new Parameter(id));
        if (pcdList == null || pcdList.size() <= 0) {
            return false;
        }
        for (ProjectCompanySettings pcd : pcdList) {
            if (StringUtil.isBlank(pcd.getAuthorizeCity())){
                return true;
            }
            if (StringUtil.isBlank(pcd.getAuthorizeCity())) {
                return true;
            } else if (StringUtil.isNotBlank(city) && pcd.getAuthorizeCity().contains(city)) {
                if (StringUtil.isBlank(area)){
                    return true;
                }
                if (StringUtil.isBlank(pcd.getAuthorizeArea())
                        || pcd.getAuthorizeArea().contains(area)) {
                    return true;
                }
            }else if (!StringUtil.isBlank(province) && StringUtil.isBlank(city)){
                if (pcd.getAuthorizeProvince().contains(province) && !StringUtil.isBlank(pcd.getAuthorizeCity())){
                    return true;
                }
            }
        }
        return false;
    }

    public boolean checkAuth2(String companyId, String province, String city, String area) {
        List<CrmProjectCompanyPcd> pcdList = find("from CrmProjectCompanyPcd where companyId = :p1 AND province =:p2 and status = '0'", new Parameter(companyId, province));
        if (pcdList == null || pcdList.size() <= 0) {
            List<ProjectCompanySettings> ycxIs = find("from ProjectCompanySettings where id = :p1 ", new Parameter(companyId));
            for (ProjectCompanySettings ycxI : ycxIs) {
                if (ycxI.getName().equals("广州越创皓光伏科技有限公司")) {
                    return true;
                }
            }
            return false;
        }
        for (CrmProjectCompanyPcd pcd : pcdList) {
            if (StringUtil.isBlank(pcd.getCity())){
                return true;
            }
            if (StringUtil.isBlank(city)){
                return true;
            }
            if (StringUtil.isBlank(pcd.getCity())) {
                return true;
            } else if (pcd.getCity().contains(city)) {
                if (StringUtil.isBlank(area)){
                    return true;
                }
                if (StringUtil.isBlank(pcd.getArea())
                        || pcd.getArea().contains(area)) {
                    return true;
                }
            }else if (!StringUtil.isBlank(province) && StringUtil.isBlank(city)){
                if (pcd.getProvince().contains(province) && !StringUtil.isBlank(pcd.getCity())){
                    return true;
                }
            }
        }
        return false;
    }

    public boolean checkAuth3(String traderId, String province, String city, String area) {
        List<TraderPcd> pcdList = find("from TraderPcd  where trader_id = :p1 and province = :p2", new Parameter(traderId, province));
        if (pcdList == null || pcdList.size() <= 0) {
            return false;
        }
        for (TraderPcd pcd : pcdList) {
            if (StringUtil.isBlank(pcd.getProvince())) {
                return true;
            } else if (Objects.equals(pcd.getCity(), city)) {
                if (StringUtil.isBlank(pcd.getArea())
                        || Objects.equals(pcd.getArea(), area)) {
                    return true;
                }
            }else if (!StringUtil.isBlank(pcd.getProvince()) && StringUtil.isBlank(pcd.getCity())){
                if (province.equals(province) && !StringUtil.isBlank(city)){
                    return true;
                }
            }
        }
        return false;
    }

    //修改项目公司授权区域
    public int editAuthorizeArea(String id,String province,String city,String area){
        SqlBuilder sqlBuilder =new SqlBuilder();
        sqlBuilder.line(" update crm_project_company_settings set  authorize_province = ?")
                .line(" , authorize_city = ?")
                .line(" , authorize_area = ?")
                .line(" WHERE id = ?" );
        return Db.update(sqlBuilder.build(),province,city,area,id);
    }


    /**
     * 根据省市区获取项目公司
     * @param map
     * @return
     */
    public List<Record> getCompanyByArea( Map<String, String> map){
        SqlBuilder builder = new SqlBuilder();
        builder.line(" select s.* FROM crm_project_company_settings s ")
                .line(" left join crm_project_company_pcd p on p.company_id=s.id ")
                .line(" where p.`status` = '0' and s.status = '0' and s.type = '0' ");
        builder.line(" and ( (p.province = ? and p.city = '' )" ,map.get("province"));
        builder.line("or (p.province = ? and p.city = ? and p.area = '' )",map.get("province") ,map.get("city"));
        builder.line(" or (p.province = ? and p.city = ? and p.area = ? ))" ,map.get("province") ,map.get("city"),map.get("area"));
        if(StringUtil.isNotBlank(map.get("partner"))){
            builder .line( " and s.partner = ? ",map.get("partner"));
        }
        if(StringUtil.isNotBlank(map.get("filingType"))){
            builder .line( " and s.filing_type = ? ",map.get("filingType"));
        }
        List<Record> project = new ArrayList<>();
        project =  Db.find(builder.build(), builder.params());
        return project;
    }

    public Record queryIdByName(String name) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select s.id as ID FROM crm_project_company_settings s where status = '0' AND name = ?",name);
        return  Db.findFirst(builder.build(), builder.params());
    }

    public ProjectCompanySettings  getByName(String name){
        return getByHql(" from ProjectCompanySettings WHERE status = '0' and name= :p1 ", new Parameter(name));
    }
}
