package com.sifang.modules.insurance.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.insurance.entity.CrmCustomerEntryInsurance;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

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

/**
 * @author DQChen
 * @date 2024-01-19 10:00
 */
@Repository
public class CustomerEntryInsuranceDao extends BaseDao<CrmCustomerEntryInsurance> {

	public long queryCount(Map<String, String> queryParams) {
		SqlBuilder builder = new SqlBuilder();
		builder.line("select count(*) ")
				.line("from crm_customer_entry_insurance a")
				.line("inner join crm_customer_entry b on a.entry_id=b.id")
				.line("where a.status ='1'");
		queryCondition(queryParams, builder);
		return Db.queryLong(builder.build(), builder.params());
	}

	/**
	 * 保险记录列表
	 *
	 * @param queryParams
	 * @param page
	 * @return
	 */
	public List<Record> list(Map<String, String> queryParams, LayuiPage page) {
		SqlBuilder builder = new SqlBuilder();
		builder.line("select a.id,a.status,b.power_station_code,a.number,a.insurance_money,a.price,b.tenant_name,b.province")
				.line(",b.city,b.area,b.street,b.address,b.trader_name,b.project_name,a.insurance_company_name,a.order_status")
				.line(", (case when b.status in ('7','a') and b.merge_flag in ('3','4') and b.apply_status != '21' then '1' else '2' end) as entryStatus")
				.line(",a.policyholder,a.insurant,a.create_time,a.remarks,a.request_no,a.source,a.down_url,a.order_time,b.partner_id, b.partner_name,b.remove_sign,a.entry_id,b.partner_id,a.renewal_status,p.input_piece_id ")
				.line("from crm_customer_entry_insurance a")
				.line("inner join crm_customer_entry b on a.entry_id=b.id")
				.line("inner join crm_customer_incoming_application p on p.entry_id = b.id");
			if ("0".equals(queryParams.get("policyType"))) {
				builder.line("where a.status ='1'");
			}
		queryCondition(queryParams, builder);
		builder.line("order by create_time desc");
		builder.limit(page.getPage(), page.getLimit());
		return Db.find(builder.build(), builder.params());
	}

	/**
	 * 投保记录列表
	 */
	public List<Record> pushList(Map<String, String> queryParams, LayuiPage page) {
		SqlBuilder builder = new SqlBuilder();
		builder.line("select a.id,a.status,b.power_station_code,a.number,a.insurance_money,a.price,b.tenant_name,b.province")
				.line(",b.city,b.area,b.street,b.address,b.trader_name,b.project_name,a.insurance_company_name")
				.line(",a.policyholder,a.insurant,a.create_time,a.remarks,a.request_no,a.order_status,a.order_time ")
				.line("from crm_customer_entry_insurance a")
				.line("inner join crm_customer_entry b on a.entry_id=b.id")
				.line("where source='0'");
		queryCondition(queryParams, builder);
		builder.line("order by create_time desc");
		builder.limit(page.getPage(), page.getLimit());
		return Db.find(builder.build(), builder.params());
	}

	public long pushListCount(Map<String, String> queryParams) {
		SqlBuilder builder = new SqlBuilder();
		builder.line("select count(*) ")
				.line("from crm_customer_entry_insurance a")
				.line("inner join crm_customer_entry b on a.entry_id=b.id");
		queryCondition(queryParams, builder);
		return Db.queryLong(builder.build(), builder.params());
	}

	public void queryCondition(Map<String, String> queryParams, SqlBuilder builder) {
		if (queryParams == null || queryParams.size() == 0) {
			return;
		}
		if (StringUtil.isNotBlank(queryParams.get("insuranceCompanyName"))) {
			builder.line("and a.insurance_company_name=?", queryParams.get("insuranceCompanyName"));
		}
		if (StringUtil.isNotBlank(queryParams.get("distributorId"))) {
			builder.line("and b.distributor_id=?", queryParams.get("distributorId"));
		}
		if (StringUtil.isNotBlank(queryParams.get("province"))) {
			builder.line("and b.province=?", queryParams.get("province"));
		}
		if (StringUtil.isNotBlank(queryParams.get("city"))) {
			builder.line("and b.city=?", queryParams.get("city"));
		}
		if (StringUtil.isNotBlank(queryParams.get("area"))) {
			builder.line("and b.area=?", queryParams.get("area"));
		}
		if (StringUtil.isNotBlank(queryParams.get("powerStationCode"))) {
			builder.line("and b.power_station_code=?", queryParams.get("powerStationCode"));
		}
		if (StringUtil.isNotBlank(queryParams.get("tenantName"))) {
			builder.like("and b.tenant_name like ?", queryParams.get("tenantName"));
		}
		if (StringUtil.isNotBlank(queryParams.get("startTimeMin"))) {
			builder.like("and a.start_time >= ?", queryParams.get("startTimeMin"));
		}
		if (StringUtil.isNotBlank(queryParams.get("startTimeMax"))) {
			builder.like("and a.start_time <= ?", queryParams.get("startTimeMax"));
		}
		if (StringUtil.isNotBlank(queryParams.get("endTimeMin"))) {
			builder.like("and a.end_time >= ?", queryParams.get("endTimeMin"));
		}
		if (StringUtil.isNotBlank(queryParams.get("endTimeMax"))) {
			builder.like("and a.end_time <= ?", queryParams.get("endTimeMax"));
		}
		// 推送时间
		if (StringUtil.isNotBlank(queryParams.get("orderTimeMin"))) {
			builder.line("and a.order_time >= ?", queryParams.get("orderTimeMin"));
		}
		if (StringUtil.isNotBlank(queryParams.get("orderTimeMax"))) {
			String orderTimeMax = queryParams.get("orderTimeMax");
			Date date = DateUtils.parseDate(orderTimeMax);
			String tomorrow = DateUtils.formatDate(DateUtils.addDays(date, 1), "yyyy-MM-dd");
			builder.line("and a.order_time < ?", tomorrow);
		}
		if (StringUtil.isNotBlank(queryParams.get("orderStatus"))) {
			builder.line("and a.order_status = ?", queryParams.get("orderStatus"));
		}
		if (StringUtil.isNotBlank(queryParams.get("partner"))) {
			builder.line("and b.partner_id = ?", queryParams.get("partner").toString());
		}
		if (StringUtil.isNotBlank(queryParams.get("policyType"))) {
			builder.line("and a.policy_type = ?", queryParams.get("policyType"));
		}
		if (StringUtil.isNotBlank(queryParams.get("removeSign"))) {
			builder.line("and b.remove_sign = ?", queryParams.get("removeSign"));
		}
	}

	public Record selectDetailById(String id, String status) {
		SqlBuilder builder = new SqlBuilder();
		builder.line("select a.id,a.source,a.status,b.power_station_code,a.number,a.insurance_money,a.price,b.tenant_name,b.mobile,b.id_code,b.province")
				.line(",b.city,b.area,b.street,b.address,b.trader_name,b.project_name,a.insurance_company_name,b.project_company_name")
				.line(",a.policyholder,a.insurant,a.create_time,a.remarks,a.request_no,a.source,a.process_detail,a.insurance_type ")
				.line(",b.filing_type,a.start_time,a.end_time,a.insurance_name,a.down_url,a.insurance_id,a.entry_id,a.address as insuranceAddress ,b.partner_id ")
				.line("from crm_customer_entry_insurance a")
				.line("inner join crm_customer_entry b on a.entry_id=b.id")
				.line("where a.id=?", id);
		if (StringUtil.isNotBlank(status)) {
			builder.line(" and a.status = ?", status);
		}
		return Db.findFirst(builder.build(), builder.params());
	}

	public List<CrmCustomerEntryInsurance> findByEntryId(String entryId) {
		Query sqlQuery = getSession().createQuery("from CrmCustomerEntryInsurance where entryId=:id and status = '1' ");
		sqlQuery.setParameter("id", entryId);
		return sqlQuery.list();
	}

	public CrmCustomerEntryInsurance findByEntryId(String entryId,String type) {
		Query sqlQuery = getSession().createQuery("from CrmCustomerEntryInsurance where entryId=:id and status = '1' and insuranceType = :type");
		sqlQuery.setParameter("id", entryId);
		sqlQuery.setParameter("type", type);
		return (CrmCustomerEntryInsurance) sqlQuery.uniqueResult();
	}

	public  List<CrmCustomerEntryInsurance> findByEntryId2(String entryId) {
		Query sqlQuery = getSession().createQuery("from CrmCustomerEntryInsurance where entryId=:id and (noPush <> 1 or noPush is null) ");
		sqlQuery.setParameter("id", entryId);
		return sqlQuery.list();
	}

	/**
	 * 自主购买获取可购买的电站列表
	 * @param stationCode
	 * @return
	 */
	public List<Record> selectEntryForInsurance(String stationCode) {
		SqlBuilder sb = new SqlBuilder();
		sb.line("select b.id,b.power_station_code,b.tenant_name,b.mobile,b.id_code,b.province")
				.line("	,b.city,b.area,'' as street,b.address,b.trader_name,b.project_name,b.project_company_name")
				.line("	,b.filing_type ,b.create_time")
				.line("from crm_customer_entry b")
				.line("left join crm_customer_entry_insurance a on a.entry_id=b.id and a.status='1'");
		sb.like("where b.status in ('6','7','10') and a.id is null  and b.power_station_code like ?", stationCode);
		return Db.find(sb.build(), sb.params());
	}

	/**
	 * 购买保单页面电站数据
	 * @return
	 */
	public List<Record> findEntryForInsurance() {
		SqlBuilder sb = new SqlBuilder();
		sb.line("select b.id,b.power_station_code,b.tenant_name,b.mobile,b.id_code,b.province")
				.line("	,b.city,b.area,'' as street,b.address,b.trader_name,b.project_name,b.project_company_name")
				.line("	,b.filing_type ,b.create_time")
				.line("from crm_customer_entry b")
				.line("left join crm_customer_entry_insurance a on a.entry_id=b.id and a.status='1'")
				.line(" where b.status in ('6','7','10') and a.id is null   ");
		return Db.find(sb.build(), sb.params());
	}

	public void updatePrice(String insuranceId, String sumPremium) {
		SQLQuery sqlQuery = getSession().createSQLQuery("update crm_customer_entry_insurance set price=:price where id=:id");
		sqlQuery.setParameter("price", sumPremium);
		sqlQuery.setParameter("id", insuranceId);
		sqlQuery.executeUpdate();
	}

	public List<Record> getByIds(List<String> insuranceIds) {
		SqlBuilder sb = new SqlBuilder()
				.line("select * from crm_customer_entry_insurance")
				.inst("where id in", insuranceIds);
		return Db.find(sb.build(), sb.params());
	}

	public void delById(String insuranceId) {
		SQLQuery sqlQuery = getSession().createSQLQuery("delete from crm_customer_entry_insurance where id=:id");
		sqlQuery.setParameter("id", insuranceId);
		sqlQuery.executeUpdate();
	}
}
