package com.zhongdao.jlr.business.dao.impl;

import com.dubh.common.dao.hibernate.BaseDaoHibernate;
import com.util.UtilTools;
import com.util.Vo;
import com.zhongdao.jlr.business.dao.OrderCheckDao;
import com.zhongdao.jlr.business.vo.LoginUserVo;
import com.zhongdao.jlr.business.vo.OrderCheckExcelVO;
import com.zhongdao.jlr.business.vo.PageInfo;
import com.zhongdao.jlr.business.vo.UserOrderExcelVO;
import com.zhongdao.jlr.util.MTextUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Repository
public class OrderCheckDaoImpl extends BaseDaoHibernate implements OrderCheckDao{

    @Override
    public Vo list(HttpServletRequest request, int page, int raws, String orderCode, String queryDate1, String rescueCompanyName, String queryDate2, String check_state) {
        //创建一个vo对象
        Vo vo=new Vo();
        //声明一个分页对象
        PageInfo pageInfo=new PageInfo();
        //获取页数和一页显示多少行并将其放入对象中
        pageInfo.setPage(page);
        pageInfo.setRows(raws);
        //获取用户信息
        LoginUserVo logininfo=(LoginUserVo)request.getSession().getAttribute("logininfo");
        //创建sql
        StringBuffer sql=new StringBuffer("select u.id id,u.code code,u.vin_no vin_no,s.name name,u.vehicle_point_address vehicle_point_address," +
                    "b.name serviceName,u.create_time,u.order_status,c.other_amount other_amount,c.account_status account_status," +
                    "c.settle_mileage_bc settle_mileage_bc,d.address address from user_order_his u " +
                    "left join task_order_his t on t.user_order_id = u.id " +
                    "left join supplier s on s.id = t.service_supplier_id " +
                    "left join jlr_supplier_visual j on  j.supplier_id = s.id " +
                    "left join task_order_cost_his c on c.user_order_id = u.id " +
                    "left join base_service b on b.id = u.service_id " +
                    "left join contract_destination d on d.id = u.contract_destination_id " +
                    "where c.account_status in (2,3) and j.jlr_user_id = "+logininfo.getId());
        if (StringUtils.isNotBlank(orderCode)) {
            sql.append(" and u.code like '%" + orderCode + "%'");
        }
        if (StringUtils.isNotBlank(rescueCompanyName)) {
            sql.append(" and s.name like '%" + rescueCompanyName + "%'");
        }
        if ("8".equals(check_state)){
            sql.append(" and (c.account_status = 2 or c.account_status = 3)");
        }else if(StringUtils.isNotBlank(check_state)){
            sql.append(" and c.account_status = "+check_state);
        }
        //开始时间
        if (StringUtils.isNotBlank(queryDate1)) {
            sql.append(" and u.create_time >= '"+queryDate1+"'");
        }
        // 结束时间
        if (StringUtils.isNotBlank(queryDate2)) {
            sql.append(" and u.create_time <= '"+queryDate2+"'");
        }
        String countSql=sql.toString();
        String info=sql.append(" limit "+pageInfo.getCurrentIndex()+","+pageInfo.getRows()).toString();
        try {
            //获取服务费用核对信息总数
            List lists=getRsBySql(countSql);
            //分页获取服务费用核对信息
            List list = getRsBySql(info);
            if (list != null && list.size() > 0) {
                vo.setRows(UtilTools.listTojsonArray(list, new String[]{"ID","ORDER_CODE","VIN_NO","NAME","ADDRESS","SERVICE_NAME","CREATE_TIME","RECUESTATE","MONEY","ACCOUNTSTATE","MILE","DESTINATION"}));
            }
            if(lists != null && lists.size() > 0) {
                vo.setTotal(lists.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return vo;
    }

    @Override
    public Vo lists(HttpServletRequest request, int page, int raws, String code, String orderCode, String queryDate1, String rescueCompanyName, String queryDate2, String check_state,String state) {
        //创建一个vo对象
        Vo vo=new Vo();
        //声明一个分页对象
        PageInfo pageInfo=new PageInfo();
        //获取页数和一页显示多少行并将其放入对象中
        pageInfo.setPage(page);
        pageInfo.setRows(raws);
        //获取用户信息
        LoginUserVo logininfo=(LoginUserVo)request.getSession().getAttribute("logininfo");
        //创建sql
        StringBuffer sql=null;
        System.out.println(state);
            if("0".equals(state)){
                sql=new StringBuffer("select u.id id,u.code code,u.vin_no vin_no,s.name name,u.vehicle_point_address vehicle_point_address," +
                        "b.name serviceName,u.create_time,u.order_status,c.other_amount other_amount,c.account_status account_status," +
                        "c.settle_mileage_bc settle_mileage_bc,d.address address from user_order_his u " +
                        "left join task_order_his t on t.user_order_id = u.id " +
                        "left join supplier s on s.id = t.service_supplier_id " +
                        "left join jlr_supplier_visual j on  j.supplier_id = s.id " +
                        "left join task_order_cost_his c on c.user_order_id = u.id " +
                        "left join base_service b on b.id = u.service_id " +
                        "left join contract_destination d on d.id = u.contract_destination_id " +
                        "where j.jlr_user_id = "+logininfo.getId());
            }else{
                sql=new StringBuffer("select u.id id,u.code code,u.vin_no vin_no,s.name name,u.vehicle_point_address vehicle_point_address," +
                        "b.name serviceName,u.create_time,u.order_status,c.other_amount other_amount,c.account_status account_status," +
                        "c.settle_mileage_bc settle_mileage_bc,d.address address from user_order_his u " +
                        "left join task_order_his t on t.user_order_id = u.id " +
                        "left join supplier s on s.id = t.service_supplier_id " +
                        "left join jlr_supplier_visual j on  j.supplier_id = s.id " +
                        "left join task_order_cost_his c on c.user_order_id = u.id " +
                        "left join base_service b on b.id = u.service_id " +
                        "left join contract_destination d on d.id = u.contract_destination_id " +
                        "where c.account_status in (4,6) and j.jlr_user_id = "+logininfo.getId());
            }

        if (StringUtils.isNotBlank(code)) {
            sql.append(" and u.vin_no like '%" + code + "%'");
        }
        if (StringUtils.isNotBlank(orderCode)) {
            sql.append(" and u.code like '%" + orderCode + "%'");
        }
        if (StringUtils.isNotBlank(rescueCompanyName)) {
            sql.append(" and s.name like '%" + rescueCompanyName + "%'");
        }
        if ("8".equals(check_state)){
            sql.append(" and (c.account_status = 2 or c.account_status = 3)");
        }else if(StringUtils.isNotBlank(check_state)){
            sql.append(" and c.account_status = "+check_state);
        }
        //开始时间
        if (StringUtils.isNotBlank(queryDate1)) {
            sql.append(" and u.create_time >= '"+queryDate1+"'");
        }
        // 结束时间
        if (StringUtils.isNotBlank(queryDate2)) {
            sql.append(" and u.create_time <= '"+queryDate2+"'");
        }
        String countSql=sql.toString();
        String info=sql.append(" limit "+pageInfo.getCurrentIndex()+","+pageInfo.getRows()).toString();
        try {
            //获取服务费用信息总数
            List lists=getRsBySql(countSql);
            //分页获取服务费用信息
            List list = getRsBySql(info);
            if (list != null && list.size() > 0) {
                vo.setRows(UtilTools.listTojsonArray(list, new String[]{"ID","ORDER_CODE","VIN_NO","NAME","ADDRESS","SERVICE_NAME","CREATE_TIME","RECUESTATE","MONEY","ACCOUNTSTATE","MILE","DESTINATION"}));
            }
            if(lists != null && lists.size() > 0) {
                vo.setTotal(lists.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return vo;
    }

    @Override
    public JSONObject exportData(HttpServletRequest request, String code, String orderCode, String queryDate1, String rescueCompanyName, String queryDate2, String check_state) {
        //创建集合
        List listExcel = new ArrayList();
        //声明一个json对象
        JSONObject jsonObject = new JSONObject();
        //获取用户信息
        LoginUserVo logininfo = (LoginUserVo) request.getSession().getAttribute("logininfo");
        //创建sql
        StringBuffer sql=new StringBuffer("select u.code code,u.vin_no vin_no,s.name name,u.vehicle_point_address vehicle_point_address," +
                "b.name serviceName,u.create_time,u.order_status,c.other_amount other_amount,c.account_status account_status," +
                "c.settle_mileage_bc settle_mileage_bc,d.address address from user_order_his u " +
                "left join task_order_his t on t.user_order_id = u.id " +
                "left join supplier s on s.id = t.service_supplier_id " +
                "left join jlr_supplier_visual j on  j.supplier_id = s.id " +
                "left join task_order_cost_his c on c.user_order_id = u.id " +
                "left join base_service b on b.id = u.service_id " +
                "left join contract_destination d on d.id = u.contract_destination_id " +
                "where j.jlr_user_id = "+logininfo.getId());
        //动态拼接
        if (StringUtils.isNotBlank(code)) {
            sql.append(" and u.vin_no like '%" + code + "%'");
        }
        if (StringUtils.isNotBlank(orderCode)) {
            sql.append(" and u.code like '%" + orderCode + "%'");
        }
        if (StringUtils.isNotBlank(rescueCompanyName)) {
            sql.append(" and s.name like '%" + rescueCompanyName + "%'");
        }
        if ("2".equals(check_state)){
            sql.append(" and (c.account_status = 2 or c.account_status = 3)");
        }else if(StringUtils.isNotBlank(check_state)){
            sql.append(" and c.account_status = "+check_state);
        }
        //开始时间
        if (StringUtils.isNotBlank(queryDate1)) {
            sql.append(" and u.create_time >= '"+queryDate1+"'");
        }
        // 结束时间
        if (StringUtils.isNotBlank(queryDate2)) {
            sql.append(" and u.create_time <= '"+queryDate2+"'");
        }
        List list=null;
        try {
            //获取服务费用信息
            list = getRsBySql(sql.toString());
            OrderCheckExcelVO header = new OrderCheckExcelVO("案件编号", "VIN码", "供应商", "案件事发地", "案件目的地", "服务类型", "案发时间", "案件状态", "公里数", "结算状态", "金额");
            listExcel.add(header);
            if (list != null && list.size() > 0) {
                JSONArray array = UtilTools.listTojsonArray(list, new String[]{"CODE", "VIN_NO", "NAME", "ADDRESS", "SERVICE_NAME","CREATE_TIME","RECUESTATE", "MONEY","ACCOUNTSTATE","MILE","DESTINATION"});
                for (int i = 0; i < array.size(); i++) {
                    JSONObject json = array.getJSONObject(i);
                    OrderCheckExcelVO vo = new OrderCheckExcelVO(
                            json.getString("CODE"),
                            json.getString("VIN_NO"),
                            json.getString("NAME"),
                            json.getString("ADDRESS"),
                            json.getString("DESTINATION"),
                            json.getString("SERVICE_NAME"),
                            json.getString("CREATE_TIME"),
                            MTextUtils.getRecueName(json.getString("RECUESTATE")),
                            StringUtils.isBlank(json.getString("MILE")) ? "NA" : String.valueOf(json.getInt("MILE") / 1000),
                            MTextUtils.getAccountState(json.getString("ACCOUNTSTATE")),
                            getFee(json.getInt("RECUESTATE"),
                                    StringUtils.isBlank(json.getString("MONEY")) ? 0 : json.getInt("MONEY"),
                                    StringUtils.isBlank(json.getString("MONEY")) ? 0 : json.getInt("MONEY")
                            )
                            );
                    listExcel.add(vo);
                }
            }
            //获取时间戳
            long dateTime = System.currentTimeMillis();
            //获取导出路径
            String path = request.getRealPath("attached") + File.separator
                    + logininfo.getName() + File.separator + dateTime + ".xlsx";
            String webUrl = UtilTools.getWebAddress(request) + File.separator
                    + "attached" + File.separator + logininfo.getName() + File.separator + dateTime + ".xlsx";
            boolean b = new UserOrderExcelVO().saveAll(listExcel, path);
            if (b) {
                jsonObject.put("result", "0");// 0:成功，1失败
                jsonObject.put("msg", "导出成功！");
                jsonObject.put("webUrl", webUrl);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;

    }

    @Override
    public boolean updateInfo(String uid, String totalFee) {
        String sql="update task_order_cost_his set report_amount =" +totalFee+ ",guidance_amount = 800,account_status = 3 where user_order_id ="+uid;
        try{
            updateSql(sql);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private String getFee(int state, int total2, int other2) {
        if (state == 4 || state == 6) {
            return String.valueOf(total2 + other2);
        } else {
            return "NA";
        }
    }
}
