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

import com.google.common.collect.Lists;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSite;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.util.LayuiPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

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

@Repository
public class SiteInformationDao extends BaseDao<CrmSite> {

    /**
     * 获取列表
     * @param page
     * @return
     */
     public List<Record> getSite(LayuiPage page, Map<String, String> map){
         StringBuffer sf = new StringBuffer();
         sf.append("SELECT s.*,e.available_amount,d.province AS provincet,d.`city` AS cityt,d.`area` AS areat,d.`address` AS addresst ,u.login_name,(SELECT count(id) FROM crm_site_employee e where e.site_id = s.id and e.status='0') as amount FROM crm_site s ");
         sf.append("LEFT JOIN crm_site_order_default_address d ON d.site_id = s.`id` ");
         sf.append("LEFT JOIN sys_user u on s.user_id = u.id left join crm_site_asset e on s.id = e.site_id ");
         sf.append("WHERE s.status != '1' and u.user_type='3' ");
         sf.append(sqlConditions(map));
         sf.append(" order by s.create_time desc  ");
         sf.append(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
         List<Record> list=Db.find(sf.toString());
         /*String sql="SELECT site_id,name,category_name,service_type FROM  crm_site_category WHERE  del_flag='0'";
         List<Record> rds = Db.find(sql);//所有的服务商品类信息
         for(Record record:list){
             String siteId=record.getStr("id");
             List<Record> lis = Lists.newArrayList();
             for(Record rd :rds){
                 String site_id=rd.getStr("site_id");
                 if(siteId.equals(site_id)){
                     lis.add(rd);
                 }
             }
             record.set("cate",lis);
         }*/
         return list;
     }
    // 查询条件
    public String sqlConditions(Map<String, String> map) {
        StringBuilder sb = new StringBuilder("");
        if (map != null) {
            if(StringUtil.checkParamsValid(map.get("is_many"))){
                if(map.get("is_many").equals("1")){
                  if(StringUtil.checkParamsValid(map.get("provices"))){
                      String[] arr=map.get("provices").split(",");
                      StringBuffer sff=new StringBuffer();
                      for(int i=0;i<arr.length;i++){
                          if(i==arr.length-1){
                              sff.append("'"+arr[i]+"'");
                          }else{
                              sff.append("'"+arr[i]+"',");
                          }
                      }
                       sb.append("and s.province in ("+sff.toString()+")");
                  }
                }else if(map.get("is_many").equals("2")){
                    if(StringUtil.checkParamsValid(map.get("provices"))){
                        sb.append("and s.province ='"+map.get("provices")+"'");
                    }
                    if(StringUtil.checkParamsValid(map.get("city"))){
                        String[] arr=map.get("city").split(",");
                        StringBuffer sf=new StringBuffer();
                        for(int i=0;i<arr.length;i++){
                            if(i==arr.length-1){
                                sf.append("'"+arr[i]+"'");
                            }else{
                                sf.append("'"+arr[i]+"',");
                            }
                        }
                        sb.append("and s.city in ("+sf.toString()+")");
                    }
                }
            }
            if (StringUtil.checkParamsValid(map.get("name"))) {
                sb.append(" and s.name like '%" + map.get("name").trim() + "%' ");
            }
            if(StringUtil.checkParamsValid(map.get("namet"))){
                sb.append("and p.name like '%" + map.get("namet")+ "%' ");
            }
            if(StringUtil.checkParamsValid(map.get("site_type"))){
               sb.append("and s.site_type = '" + map.get("site_type")+ "'");
            }
            if(StringUtil.checkParamsValid(map.get("telephone"))){
               sb.append("and s.telephone like '%" + map.get("telephone").trim()+ "%'");
            }
          if(StringUtil.checkParamsValid(map.get("province"))){
                sb.append(" and concat_ws('',s.province,s.city,s.area,s.address) like '%"+map.get("province").trim()+"%' ");
            }
          if(StringUtil.checkParamsValid(map.get("customerId"))){
              sb.append("and s.is_crm_customer = '" + map.get("customerId")+ "'");
          }
        }
        return sb.toString();
    }

    public long getCount(Map<String, String> map){
        StringBuffer sf = new StringBuffer();
        sf.append("SELECT count(*) FROM crm_site s ");
/*        sf.append("LEFT JOIN crm_site_category p ON p.site_id = s.`id` AND p.del_flag = '0' ");*/
        sf.append("LEFT JOIN crm_site_order_default_address d ON d.site_id = s.`id` ");
        sf.append("WHERE s.status != '1' ");
        sf.append(sqlConditions(map));
        return Db.queryLong(sf.toString());
    }

    /**
     * 获取默认的服务商地址
     * @param id
     * @return
     */
   public Record getCurrentSiteAddress(String id){
        StringBuffer sf = new StringBuffer();
        sf.append("SELECT s.`province`,s.`city`,s.`area`,s.`address` FROM crm_site s WHERE s.status='0' AND s.`id`= ? ");
        return Db.findFirst(sf.toString(),id);
   }

   public String getSiteIdByCustomerId(String cusId){
       return Db.queryStr(" SELECT id FROM crm_site WHERE is_crm_customer='2' AND STATUS !='1' AND customer_id=? ",cusId);
   }



    /**
     * 获取默认的里程地址
     * @param id
     * @return
     */
    public Record getCurrentSiteEditorAddress(String id){
        StringBuffer sf = new StringBuffer();
        sf.append("SELECT d.`province`,d.`city`,d.`area`,d.`address` FROM crm_site_order_default_address d WHERE d.`site_id`= ? ");
        return Db.findFirst(sf.toString(),id);
    }

    /**
     * 获取服务商未完成工单
     * @return
     */
    public List<Record> getSiteOrder(String siteId){
        StringBuffer sf = new StringBuffer();
        sf.append("select * from crm_order where site_id ='"+siteId+"' and status in('1','2','3','4')");
        return Db.find(sf.toString());
    }

    /**
     * 获取服务商备件库存
     * @return
     */
    public Record getSiteFitting(String siteId){
        StringBuffer sf = new StringBuffer();
        sf.append("select sum(warning) as warning from crm_site_fitting where site_id ='"+siteId+"'");
        return Db.findFirst(sf.toString());
    }

    /**
     * 获取服务商工单结算
     * @return
     */
    public List<Record> getSettlement(String siteId){
        StringBuffer sf = new StringBuffer();
        sf.append("select * FROM crm_order_site_settlement s LEFT JOIN crm_order  o ON o.id = s.order_id where o.site_id ='"+siteId+"' and s.jz_flag in(0,2) ");
        return Db.find(sf.toString());
    }


    /**
     * 获取工程师未完成工单
     * @return
     */
    public List<Record> getEmployeorder(String id){
        StringBuffer sf = new StringBuffer();
        sf.append("select * from crm_order where employe_id ='"+id+"' and status in('1','2','3','4')");
        return Db.find(sf.toString());
    }

    //获取平台下所有服务商
    public  List<Record> getSiteList() {
        List<Record> list = Db.find("select id,name from crm_site where status ='0'");
        return list;
    }

    /**
     * 获取非绑定CRM客户的服务商
    */
    public  List<Record> getNotSiteCUstomerList() {
        List<Record> list = Db.find("select id,name from crm_site where status ='0' and is_crm_customer ='1' ");
        return list;
    }


    /**
     * 新增服务商之前进行校验登录账号是否已经存在
     */
    public boolean getExistsLoginName(String loginName){
        Record rd = null;
        rd = Db.findFirst(" select * from sys_user a where a.login_name = ?  and a.status = '0' ", loginName);
        if (rd != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 新增服务商之前进行校验登录账号是否已经存在
     */
    public boolean getExistsSiteName(String name){
        Record rd = null;
        rd = Db.findFirst(" select * from crm_site a where a.name = ?  and a.status = '0' ", name);
        if (rd != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 修改服务商保存之前进行校验登录账号是否已经存在
     */
    public boolean getExistsLoginNameNew(String id,String loginName){
        Record rd = null;
            rd = Db.findFirst(" select * from sys_user a where a.login_name = ? and a.status = '0' and a.id !=? ", loginName,id);
        if (rd != null) {
            return true;
        } else {
            return false;
        }
    }

}
