package com.sifang.modules.customer.dao;

import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.entity.Customer;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

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

@Repository
public class CustomerDao extends BaseDao<Customer> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public List<Record> getCustomerList(LayuiPage<Record> page, Map<String, String> map) {
        StringBuilder sf = new StringBuilder();
        String sqlMap = getOrderMap(map);
        sf.append(" SELECT s.id as psId,a.id as cuId,a.user_type,a.remarks,a.status,a.mobile_tel,a.user_account,a.login_times,a.login_last_date,a.is_warranty " +
                ",s.ps_name,s.install_date,s.user_id,s.province,s.city,s.area,s.location FROM crm_customer a  left join crm_power_station s on a.user_id = s.user_id where 1=1 ");
        sf.append(sqlMap);
        if (page != null) {
            sf.append(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = getCount(map, sqlMap);
            page.setCount(count);
        }
        logger.info("getCustomerList  :  sql :  {}",sf.toString());
        return Db.find(sf.toString());
    }

    public long getCount(Map<String, String> map, String sqlMap) {
        StringBuilder sf = new StringBuilder();
        sf.append(" SELECT count(*) FROM crm_customer a  left join crm_power_station s on a.user_id = s.user_id where 1=1 ");
        sf.append(sqlMap);
        return Db.queryLong(sf.toString());
    }

    public String getOrderMap(Map<String, String> map) {
        StringBuilder sf = new StringBuilder();
        if (map == null) {
            return "";
        }

        if (!StringUtil.checkParamsValid(map.get("psname")) && !StringUtil.checkParamsValid(map.get("location")) && !StringUtil.checkParamsValid(map.get("userAccount"))
                && !StringUtil.checkParamsValid(map.get("isWarranty")) && !StringUtil.checkParamsValid(map.get("mobileTel")) && !StringUtil.checkParamsValid(map.get("remarks"))
                && !StringUtil.checkParamsValid(map.get("updateTimeSta")) && !StringUtil.checkParamsValid(map.get("updateTimeEnd"))&&!StringUtil.checkParamsValid(map.get("stationBuildingStart"))
        &&!StringUtil.checkParamsValid(map.get("stationBuildingEnd"))&&!StringUtil.checkParamsValid(map.get("customerId"))&&!StringUtil.checkParamsValid(map.get("province"))&&!StringUtil.checkParamsValid(map.get("city"))
           &&!StringUtil.checkParamsValid(map.get("loginNumMin"))&&!StringUtil.checkParamsValid(map.get("loginNumMax"))
        ) {
            sf.append(" and DATE_SUB(CURDATE(), INTERVAL 2 MONTH) <= DATE(s.install_date)  ");
            return sf.toString();
        }

        if (StringUtil.checkParamsValid(map.get("psname"))) {
            String psname = map.get("psname");
            sf.append(" and s.ps_name like '%" + psname + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("location"))) {
            String location = map.get("location");
            sf.append(" and concat_ws('',s.province,s.city,s.area,s.location) like '%" + location.trim() + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("userAccount"))) {
            sf.append(" and a.user_account = '" + map.get("userAccount") + "'");
        }
        if (StringUtil.checkParamsValid(map.get("isWarranty"))) {
            sf.append(" and a.is_warranty = '" + map.get("isWarranty") + "'");
        }
        if (StringUtil.checkParamsValid(map.get("userType"))) {
            sf.append(" and a.user_type = '" + map.get("userType") + "'");
        }
        if (StringUtil.checkParamsValid(map.get("mobileTel"))) {
            sf.append(" and a.mobile_tel like '%" + map.get("mobileTel") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("remarks"))) {
            sf.append(" and a.remarks like '%" + map.get("remarks") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("updateTimeSta"))) {
            sf.append(" and s.install_date >= '" + map.get("updateTimeSta") + " 00:00:00' ");
        }
        if (StringUtil.checkParamsValid(map.get("updateTimeEnd"))) {
            sf.append(" and s.install_date <= '" + map.get("updateTimeEnd") + " 23:59:59' ");
        }
        //主要是通知公告的条件查询用户
        if (StringUtil.checkParamsValid(map.get("stationBuildingStart"))) {
            sf.append(" and s.install_date >= '" + map.get("stationBuildingStart") + " 00:00:00' ");
        }
        if (StringUtil.checkParamsValid(map.get("stationBuildingEnd"))) {
            sf.append(" and s.install_date <= '" + map.get("stationBuildingEnd") + " 23:59:59' ");
        }
        if (StringUtil.checkParamsValid(map.get("customerId"))) {
            sf.append(" and a.id in (" + StringUtil.joinInSql(map.get("customerId").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("province"))) {
            sf.append(" and s.province in (" + StringUtil.joinInSql(map.get("province").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("city"))) {
            sf.append(" and s.city in (" + StringUtil.joinInSql(map.get("city").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("loginNumMin"))) {
            sf.append(" and a.login_times >= " + map.get("loginNumMin"));
        }
        if (StringUtil.checkParamsValid(map.get("loginNumMax"))) {
            sf.append(" and a.login_times <= " + map.get("loginNumMax"));
        }


        return sf.toString();
    }

    public Customer getCustomerBuserId(String userId) {
        return getByHql(" from Customer where userId =:p1", new Parameter(userId));
    }

    public void saveCustomer(Map<String, String> map) {
        String userId = map.get("userId");
        Customer cus = getCustomerBuserId(userId);
        if (cus == null) {
            cus = new Customer();
            cus.setUserId(userId);
        }
        cus.setMobileTel(map.get("mobileTel"));
        cus.setUserAccount(map.get("userAccount"));
        cus.setLoginLastDate(map.get("disableTime"));
        cus.setToken(map.get("token"));
        cus.setLoginTimes(map.get("loginTimes"));
        cus.setLoginLastDate(map.get("loginLastDate"));
        cus.setLoginLastIp(map.get("loginLastIp"));
        cus.setPassword(HashKit.md5(map.get("user_password")));
        cus.setStatus("1");
        cus.setUserType("1");
        save(cus);
    }
/*

    public Customer getByUserId(String userId){
        return getByHql(" from  Customer  where userId = :p1 ",new Parameter(userId));
    }
*/

    public long getCustimerByMoblie(String mobile, String userType) {
        StringBuilder sf = new StringBuilder();
        sf.append("select count(*) from crm_customer where (mobile_tel =? or user_account=?) and status='1' ");
        if (StringUtil.isNotEmpty(userType)) {
            sf.append(" and user_type ='" + userType + "' ");
        }
        return Db.queryLong(sf.toString(), mobile, mobile);
    }

    /**
     * 修改标注
     */
    public void updateRemark(String id, String remark) {
        Customer customer = get(id);
        customer.setRemarks(remark.trim());
        save(customer);
    }

}
