package com.sifang.modules.site.financial.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.financialManagement.entity.CrmOrderSiteSettlement;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.dao.DjxBaseDao;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.sys.util.TrimStrMap;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class FinancialManageDao extends DjxBaseDao<CrmOrderSiteSettlement> {

    /**
     * 获取列表数据
     *
     * @param parasMap
     * @param page
     */
    public void getListData(TrimStrMap parasMap, LayuiPage<Record> page, String siteId) {

        SqlBuilder sb = new SqlBuilder()
                .line("SELECT s.id, s.order_id, s.type, s.cost_detail,s.settlement_time, s.create_name, IFNULL(s.service_costs,0) AS service_costs, IFNULL(s.reward_costs,0) AS reward_costs, IFNULL(s.other_cost,0) AS other_cost,  IFNULL(s.mileage_cost,0) AS mileage_cost,  s.remarks, s.site_id, s.jz_flag, s.site_billing_id,o.number,o.site_name,o.warranty_type,o.appliance_category,o.appliance_brand,o.appliance_model,o.service_type,o.power_station_name," +
                        "SUM(s.service_costs + s.reward_costs + s.other_cost + s.mileage_cost  ) AS total_costs , o.service_measures," +
                        "o.employe_name,o.customer_name,o.customer_mobile,o.customer_telephone,o.province,o.remarks as orderRemarks ,b.checkout_type,o.order_type,o.city,o.area,o.customer_address,b.withdrawal_number,b.status as outStatus ,o.level,o.appliance_machine_code,DATE_FORMAT(o.repair_time,'%Y-%m-%d %H:%i:%s') repair_time,DATE_FORMAT(o.end_time,'%Y-%m-%d %H:%i:%s') end_time " +
                        "from crm_order_site_settlement s")
                .line("left join crm_order as o on o.id=s.order_id")
                .line("  LEFT JOIN crm_site_cash_out AS b ON b.id=s.site_billing_id and b.status in('1','2','4')")
                .line("where s.site_id =? ")
                .line(queryConds(parasMap))
                .line(" GROUP BY s.id order by s.settlement_time desc")
                .limit(page.getPage(), page.getLimit());
        List<Record> records = Db.find(sb.build(), siteId);
        page.setData(records);
        page.setCount(listDataCount(parasMap, siteId));
    }

    private long listDataCount(TrimStrMap parasMap, String siteId) {
        SqlBuilder sb = new SqlBuilder()
                .line("select count(*) as cnt from crm_order_site_settlement s")
                .line("left join crm_order as o on o.id=s.order_id")
                .line("  LEFT JOIN crm_site_cash_out AS b ON b.id=s.site_billing_id and b.status in('1','2','4') ")
                .line("where s.site_id =? ")
                .line(queryConds(parasMap));

        return Db.queryLong(sb.toString(), siteId);
    }

    /**
     * 查询条件
     *
     * @param parasMap
     * @return
     */
    public String queryConds(TrimStrMap parasMap) {
        SqlBuilder sb = new SqlBuilder();
        //电站名称
        if (parasMap.hasNonBlankValue("powerStationName")) {
            sb.line("and o.power_station_name=" + quot(parasMap.get("powerStationName")));
        }
        //是否结账
        if (parasMap.hasNonBlankValue("jzFlag")) {
            String flag = parasMap.get("jzFlag");
            if ("3".equals(flag)) {
                sb.line("and s.jz_flag='0' ");
            } else {
                sb.line("and b.status=" + quot(flag));
            }
        }
        //结账类型
        if (parasMap.hasNonBlankValue("checkoutType")) {
            sb.line(" and b.checkout_type =" + quot(parasMap.get("checkoutType")));
        }
        //保修类型
        if (parasMap.hasNonBlankValue("warrantyType")) {
            sb.line("and o.warranty_type=" + quot(parasMap.get("warrantyType")));
        }
        //服务类型
        if (parasMap.hasNonBlankValue("serviceType")) {
            sb.line("and o.service_type=" + quot(parasMap.get("serviceType")));
        }
        //产品品类
        if (parasMap.hasNonBlankValue("applianceCategory")) {
            sb.line("and o.appliance_category=" + quot(parasMap.get("applianceCategory")));
        }
        //产品品牌
        if (parasMap.hasNonBlankValue("applianceBrand")) {
            sb.line("and o.appliance_brand=" + quot(parasMap.get("applianceBrand")));
        }
        //工单编号
        if (parasMap.hasNonBlankValue("number")) {
            sb.line("and o.number like" + likeQuot(parasMap.get("number").trim()));
        }
        //请款编号
        if (parasMap.hasNonBlankValue("withdrawalNumber")) {
            sb.line("and b.withdrawal_number like" + likeQuot(parasMap.get("withdrawalNumber").trim()));
        }
        if (parasMap.hasNonBlankValue("applianceModel")) {
            sb.line("and o.appliance_model like" + likeQuot(parasMap.get("applianceModel").trim()));
        }
        //结算类型
        if (parasMap.hasNonBlankValue("type")) {
            sb.line("and s.type=" + quot(parasMap.get("type")));
        }

        //用户姓名
        if (parasMap.hasNonBlankValue("employeId")) {
            sb.line("and o.employe_id =" + quot(parasMap.get("employeId").trim()));
        }
        if (parasMap.hasNonBlankValue("customerName")) {
            sb.line("and o.customer_name like" + likeQuot(parasMap.get("customerName").trim()));
        }
        //用户电话
        if (parasMap.hasNonBlankValue("mobile")) {
            String mobile = parasMap.get("mobile").trim();
            sb.line("and (o.customer_mobile like " + likeQuot(mobile) + " or o.customer_telephone like " + likeQuot(mobile) + ")");
        }
        //发布时间
        if (parasMap.hasNonBlankValue("pubStart")) {
            sb.line("and o.repair_time>=" + quot(parasMap.get("pubStart")));
        }
        if (parasMap.hasNonBlankValue("pubEnd")) {
            sb.line("and o.repair_time<" + quot(DateUtils.nextDate(parasMap.get("pubEnd"))));
        }
        //完工时间
        if (parasMap.hasNonBlankValue("endStart")) {
            sb.line("and o.end_time>=" + quot(parasMap.get("endStart")));
        }
        if (parasMap.hasNonBlankValue("end")) {
            sb.line("and o.end_time<" + quot(DateUtils.nextDate(parasMap.get("end"))));
        }
        //结算时间
        if (parasMap.hasNonBlankValue("settlementStart")) {
            sb.line("and s.settlement_time>=" + quot(parasMap.get("settlementStart")));
        }
        if (parasMap.hasNonBlankValue("settlementEnd")) {
            sb.line("and s.settlement_time<" + quot(DateUtils.nextDate(parasMap.get("settlementEnd"))));
        }

        return sb.build();
    }

    /**
     * 获取当前服务商id
     *
     * @param userId
     * @return
     */
    public String getSiteId(String userId) {
        StringBuffer sf = new StringBuffer();
        sf.append("select s.id from crm_site s where s.status='0' and s.user_id = ? ");
        return Db.queryStr(sf.toString(), userId);
    }


}
