package com.palmnest.dao.washcar.impl;

import cn.jiguang.common.utils.StringUtils;
import com.palmnest.application.bean.Page;
import com.palmnest.application.dto.input.WashCarOrderDto;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.dao.washcar.WashCarOrderDao;
import com.palmnest.model.washcar.WashCarOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

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

/**
 * 洗车订单实现类
 *
 * @author longmeizhen
 */
@Slf4j
@Repository("washCarOrderDao")
public class WashCarOrderDaoImpl extends GenericDaoHibernate<WashCarOrder, Long> implements WashCarOrderDao {


	public WashCarOrderDaoImpl() {
		super(WashCarOrder.class);
	}

	@Override
	public Page findSearch(WashCarOrderDto dto, int pageNo, int pageSize) throws Exception {

		StringBuilder sql = new StringBuilder("");

		sql.append(" select was.id,was.status,was.orderNo,date_format(was.createTime,'%Y-%m-%d %H:%i:%s') createTime,was.carWasherId,apu.username usName,apu.FULL_NAME fullName ");
		sql.append(" ,was.custId,cus.userName,was.carNumber,cus.mobile,was.source,was.orgId  ");
		sql.append(" from tb_car_washorder was ");
		sql.append(" left join tb_customer cus on was.custId=cus.id ");
		sql.append(" left join tb_app_user apu on was.carWasherId=apu.id ");
		sql.append(" where 1=1 ");

		if (dto != null) {

			if (StringUtils.isNotEmpty(dto.getSearchStr())) {
				sql.append(" and (cus.userName like '%" + dto.getSearchStr() + "%'  or was.carNumber like '%"
						+ dto.getSearchStr() + "%' or cus.mobile like '%" + dto.getSearchStr() + "%' or was.orderNo like '%" + dto.getSearchStr() + "%' ) ");
			}
			if (StringUtils.isNotEmpty(dto.getOrgId())) {
				String[] orgStr = dto.getOrgId().split(";");
				String   str    = "";
				if (orgStr != null && orgStr.length > 0) {
					for (int i = 0; i < orgStr.length; i++) {
						str = str + orgStr[i] + ",";
					}
				}
				if (StringUtils.isNotEmpty(str)) {
					str = str.substring(0, str.length() - 1);
					sql.append(" and was.orgId in (" + str + ") ");
				}

			}
			if (StringUtils.isNotEmpty(dto.getCustId())) {
				sql.append(" and was.custId=" + dto.getCustId() + " ");
			}
			if (StringUtils.isNotEmpty(dto.getCustName())) {
				sql.append(" and cus.userName like '%" + dto.getCustName() + "%' ");
			}
			if (StringUtils.isNotEmpty(dto.getCarNumber())) {
				sql.append(" and was.carNumber like '%" + dto.getCarNumber() + "%' ");
			}
			if (StringUtils.isNotEmpty(dto.getMobile())) {
				sql.append(" and cus.mobile like '%" + dto.getMobile() + "%' ");
			}
			if (StringUtils.isNotEmpty(dto.getOrderNo())) {
				sql.append(" and was.orderNo like '%" + dto.getOrderNo() + "%' ");
			}
			if (StringUtils.isNotEmpty(dto.getSource()) && !"0".equals(dto.getSource())) {
				sql.append(" and was.source=" + dto.getSource() + " ");
			}
			if (StringUtils.isNotEmpty(dto.getStatus()) && !"0".equals(dto.getStatus())) {
				if ("1".equals(dto.getStatus())) {//待接单
					sql.append(" and was.status='" + dto.getStatus() + "' ");
				} else if ("2".equals(dto.getStatus())) {//进行中
					sql.append(" and was.status in ('2','3','5') ");
				} else if ("3".equals(dto.getStatus())) {//已完成
					sql.append(" and was.status ='4' ");
				} else if ("4".equals(dto.getStatus())) {
					if (StringUtils.isNotEmpty(dto.getAppUserId())) {//洗车员的全部只能看到洗车中和已完成状态的单据
						sql.append(" and was.status in ('2','3','4','5') ");
					}
				} else if ("5".equals(dto.getStatus())) {//微信端进行中
					sql.append(" and was.status in ('1','2','3','5') ");
				}
			}
			if (StringUtils.isNotEmpty(dto.getBeginTime())) {
				String beginTime = dto.getBeginTime() + " 00:00:00";
				if (StringUtils.isNotEmpty(dto.getEndTime())) {
					String endTime = dto.getEndTime() + " 23:59:59";
					sql.append("    and was.createTime BETWEEN '" + beginTime + "' and '" + endTime + "' ");
				} else {
					sql.append("    and was.createTime >='" + beginTime + "'");
				}
			} else {
				if (StringUtils.isNotEmpty(dto.getEndTime())) {
					String endTime = dto.getEndTime() + " 00:00:00";
					sql.append("    and was.createTime<='" + endTime + "' ");
				}
			}

			if (StringUtils.isNotEmpty(dto.getAppUserId())) {//洗车工
				sql.append(" and was.carWasherId ='" + dto.getAppUserId() + "' ");
			}
		}
		sql.append(" order by was.createTime desc");
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}

	@Override
	public List<Map<String, Object>> getWashCaeService(String orgId, String syscode) throws Exception {
		StringBuilder sql = new StringBuilder("");
		sql.append(" select distinct aus.id,aus.USERNAME,aus.FULL_NAME,aus.is_online,aus.USER_CODE from tb_app_user aus ");
		//tr_app_user_orgnization
		sql.append(" left join tr_app_user_orgnization org on org.user_id=aus.ID ");
		sql.append(" left join tr_app_user_role aur on aur.USER_ID=aus.ID ");
		sql.append(" left join tr_app_role_function arf on arf.ROLEID=aur.ROLE_ID ");
		sql.append(" left join tb_app_function afc on afc.ID=arf.FUNCTION_ID ");
		sql.append(" where afc.SYSTEMCODE=" + syscode + " ");
		//在岗
		sql.append(" and aus.is_online=2 ");
		sql.append(" and org.org_id= " + orgId);
		sql.append(" and aus.ISENABLED='1' ");
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		return list;
	}

	/**
	 * 根据洗车员获取他的洗车的订单
	 * carWashId 洗车员的id
	 * status状态，查询不同状态的单据（status不传，代表查询该洗车工所有的订单）
	 */
	@Override
	public List<WashCarOrder> getWashOrderByCarWasherId(String carWashId, String status, Integer type)
			throws Exception {
		StringBuilder sql = new StringBuilder("from WashCarOrder where carWasherId=? ");
		if (StringUtils.isNotEmpty(status)) {
			if (type == 1) {//type等于1代表in
				sql.append(" and status in (" + status + ") ");
			} else {//代表 not in
				sql.append(" and status not in (" + status + ") ");
			}

		}
		return getSession().createQuery(sql.toString()).setString(0, carWashId).list();
	}

	@Override
	public List<WashCarOrder> getWashListByDas(String userId, String status, int type) throws Exception {
		//查出所有在今天创建的不为取消的订单
		StringBuilder sql = new StringBuilder("from WashCarOrder where TO_DAYS(createTime)=TO_DAYS(NOW())  ");
		if (StringUtils.isNotEmpty(userId)) {
			sql.append(" and custId= " + userId);
		}
		if (StringUtils.isNotEmpty(status)) {
			if (type == 1) {
				sql.append(" and status in (" + status + ") ");
			} else {
				sql.append(" and status not in (" + status + ") ");
			}
		}

		return getSession().createQuery(sql.toString()).list();
	}

	@Override
	public String isPower(String syscode, String userId) throws Exception {
		StringBuilder sql = new StringBuilder("");
		sql.append(" select distinct aus.id,aus.USERNAME,aus.FULL_NAME,aus.is_online,aus.USER_CODE from tb_app_user aus ");
		sql.append(" left join tr_app_user_role aur on aur.USER_ID=aus.ID ");
		sql.append(" left join tr_app_role_function arf on arf.ROLEID=aur.ROLE_ID ");
		sql.append(" left join tb_app_function afc on afc.ID=arf.FUNCTION_ID ");
		sql.append(" where afc.SYSTEMCODE=" + syscode + " and aus.id=" + userId + " ");
//		//在岗
//		sql.append(" and aus.is_online=2 ");
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		String                    res  = "NOT";
		if (list != null && list.size() > 0) {
			res = "HAVE";
		}
		return res;
	}

	/**
	 * 查询操作用户为当前登录用户的状态为已接单、洗车中转单
	 */
	@Override
	public int getWashByUserId(String carWashId, String orgIds) {
		if (StringUtils.isNotEmpty(orgIds)) {
			StringBuilder sql = new StringBuilder("select COUNT(id)  from tb_car_washorder where carWasherId='" + carWashId + "' and "
					+ " status in ('2','3','5')  and orgId in (" + orgIds + ")  ");
			String count = getSession().createSQLQuery(sql.toString()).uniqueResult().toString();
			return Integer.parseInt(count);
		}
		return 0;
	}

	/**
	 * 管理员的排队中的洗车订单
	 */
	@Override
	public int getWashByManager(String orgId) {
		if (StringUtils.isNotEmpty(orgId)) {
			StringBuilder sql   = new StringBuilder("select COUNT(id)  from tb_car_washorder where status='1' and orgId in (" + orgId + ")  ");
			String        count = getSession().createSQLQuery(sql.toString()).uniqueResult().toString();
			return Integer.parseInt(count);
		}
		return 0;
	}


}
