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.CaseDao;
import com.zhongdao.jlr.business.vo.LoginUserVo;
import com.zhongdao.jlr.business.vo.PageInfo;
import com.zhongdao.jlr.pojo.JLRepqr;
import org.apache.commons.lang.StringUtils;
import org.apache.http.util.TextUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Repository;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository("caseDaoImpl")
public class CaseDaoImpl extends BaseDaoHibernate implements CaseDao {

    private final static SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

    @Override
    public Vo casesListService(String state,HttpServletRequest request, String caseCode, String frame_code, String rescueState, String createTime, String finishTime, String companyName,String plateNumber) {
        //获取登录信息
        LoginUserVo logininfo=(LoginUserVo)request.getSession().getAttribute("logininfo");
        Vo vo=new Vo();
        //声明一个分页对象
        PageInfo pageInfo=new PageInfo();
        //获取页数和一页显示多少行并将其放入对象中
        pageInfo.setPage(UtilTools.getPage(request));
        pageInfo.setRows(UtilTools.getRows(request));
        //sql动态拼接
        StringBuffer sql=null;
        //如果state为0则证明此操作为管理员，否则是经销商
                if("0".equals(state)){
                    if("1".equals(rescueState)){
                        sql = new StringBuffer("select DISTINCT u.code orderCode,u.create_time create_time," +
                                "u.vin_no vin_no,s.name name," +
                                "s.code code,b.name serviceName,u.order_status order_status,t.task_status task_status,u.plate_number plate_number from user_order u " +
                                "left join task_order t on t.user_order_id=u.id " +
                                "left join supplier s on t.service_supplier_id=s.id " +
                                "left join base_service b on b.id=u.service_id " +
                                "and u.order_status not in (51,53,55) " +
                                "where u.contract_id in (select contract_id from jlr_contract_visual where jlr_user_id ="+logininfo.getId()+")");
                    }else if("2".equals(rescueState)){
                        sql = new StringBuffer("select DISTINCT u.code orderCode,u.create_time create_time," +
                                "u.vin_no vin_no,s.name name," +
                                "s.code code,b.name serviceName,u.order_status order_status,t.task_status task_status,u.plate_number plate_number from user_order_his u " +
                                "left join task_order_his t on t.user_order_id=u.id " +
                                "left join supplier s on t.service_supplier_id=s.id " +
                                "left join base_service b on b.id=u.service_id " +
                                "where u.contract_id in (select contract_id from jlr_contract_visual where jlr_user_id ="+logininfo.getId()+") " +
                                "and u.order_status = 55");
                    }else if("3".equals(rescueState)){
                        sql = new StringBuffer("select DISTINCT u.code orderCode,u.create_time create_time," +
                                "u.vin_no vin_no,s.name name," +
                                "s.code code,b.name serviceName,u.order_status order_status,t.task_status task_status,u.plate_number plate_number from user_order_his u " +
                                "left join task_order_his t on t.user_order_id=u.id " +
                                "left join supplier s on t.service_supplier_id=s.id  " +
                                "left join base_service b on b.id=u.service_id " +
                                "where u.contract_id in (select contract_id from jlr_contract_visual where jlr_user_id ="+logininfo.getId()+") " +
                                "and u.order_status = 51");
                    }else {
                        sql = new StringBuffer("select DISTINCT u.code orderCode,u.create_time " +
                                "create_time,u.vin_no vin_no,s.name name, " +
                                "s.code code,b.name serviceName,u.order_status order_status,u.task_status task_status,u.plate_number plate_number from " +
                                "(select u.code code,u.create_time,u.vin_no,u.id,u.order_status," +
                                "u.service_id,t.service_supplier_id,u.contract_id contract_id,t.task_status task_status,u.plate_number plate_number from user_order_his u " +
                                "left join task_order_his t on t.user_order_id=u.id " +
                                "union select u.code code,u.create_time create_time,u.vin_no vin_no," +
                                "u.id id,u.order_status order_status,u.service_id service_id " +
                                ",t.service_supplier_id service_supplier_id,u.contract_id contract_id,t.task_status task_status,u.plate_number plate_number from user_order u " +
                                "left join task_order t on t.user_order_id=u.id " +
                                ") u " +
                                "left join supplier s on u.service_supplier_id=s.id " +
                                "left join base_service b on b.id=u.service_id " +
                                "left join jlr_supplier_visual v on v.supplier_id=s.id " +
                                "where " +
                                "u.contract_id in (select contract_id from jlr_contract_visual where jlr_user_id =" + logininfo.getId() + ") ");
                    }
                }else if("1".equals(state)){
                    if("1".equals(rescueState)){
                        sql = new StringBuffer("select DISTINCT u.code orderCode,u.create_time create_time," +
                                "u.vin_no vin_no,s.name name," +
                                "s.code code,b.name serviceName,u.order_status order_status,t.task_status task_status,u.plate_number plate_number from user_order u " +
                                "left join task_order t on t.user_order_id=u.id " +
                                "left join supplier s on t.service_supplier_id=s.id " +
                                "left join base_service b on b.id=u.service_id " +
                                "left join jlr_supplier_visual v on v.supplier_id=s.id " +
                                "where u.contract_id in (select contract_id from jlr_contract_visual where jlr_user_id ="+logininfo.getId()+") " +
                                "and u.order_status not in (51,53,55)");
//                                "and u.order_status = 31 " +
//                                "and v.jlr_user_id =" + logininfo.getId());
                    }else if("2".equals(rescueState)){
                        sql = new StringBuffer("select DISTINCT u.code orderCode,u.create_time create_time," +
                                "u.vin_no vin_no,s.name name," +
                                "s.code code,b.name serviceName,u.order_status order_status,t.task_status task_status,u.plate_number plate_number from user_order_his u " +
                                "left join task_order_his t on t.user_order_id=u.id " +
                                "left join supplier s on t.service_supplier_id=s.id  " +
                                "left join base_service b on b.id=u.service_id " +
                                "left join jlr_supplier_visual v on v.supplier_id=s.id " +
                                "where u.contract_id in (select contract_id from jlr_contract_visual where jlr_user_id ="+logininfo.getId()+") ");
//                                "and u.order_status = 55 " +
//                                "and v.jlr_user_id =" + logininfo.getId());
                    }else if("3".equals(rescueState)){
                        sql = new StringBuffer("select DISTINCT u.code orderCode,u.create_time create_time," +
                                "u.vin_no vin_no,s.name name," +
                                "s.code code,b.name serviceName,u.order_status order_status,t.task_status task_status,u.plate_number plate_number from user_order_his u " +
                                "left join task_order_his t on t.user_order_id=u.id " +
                                "left join supplier s on t.service_supplier_id=s.id  " +
                                "left join base_service b on b.id=u.service_id " +
                                "left join jlr_supplier_visual v on v.supplier_id=s.id " +
                                "where u.contract_id in (select contract_id from jlr_contract_visual where jlr_user_id ="+logininfo.getId()+") ");
//                                "and u.order_status = 51 " +
//                                "and v.jlr_user_id =" + logininfo.getId());
                    }else {
                        sql = new StringBuffer("select DISTINCT u.code orderCode,u.create_time " +
                                "create_time,u.vin_no vin_no,s.name name, " +
                                "s.code code,b.name serviceName,u.order_status order_status,u.task_status task_status,u.plate_number plate_number from " +
                                "(select u.code code,u.create_time,u.vin_no,u.id,u.order_status," +
                                "u.service_id,t.service_supplier_id,u.contract_id contract_id,t.task_status task_status,u.plate_number plate_number from user_order_his u " +
                                "left join task_order_his t on t.user_order_id=u.id " +
                                "union select u.code code,u.create_time create_time,u.vin_no vin_no," +
                                "u.id id,u.order_status order_status,u.service_id service_id " +
                                ",t.service_supplier_id service_supplier_id,u.contract_id contract_id,t.task_status task_status,u.plate_number plate_number from user_order u " +
                                "left join task_order t on t.user_order_id=u.id " +
                                ") u " +
                                "left join supplier s on u.service_supplier_id=s.id " +
                                "left join base_service b on b.id=u.service_id " +
                                "left join jlr_supplier_visual v on v.supplier_id=s.id " +
                                "where " +
                                "u.contract_id in (select contract_id from jlr_contract_visual where jlr_user_id =" + logininfo.getId() + ")") ;
//                                "and u.order_status in (31,53,51,55) " +
//                                "and v.jlr_user_id =" + logininfo.getId());
                    }
                }
        if (StringUtils.isNotBlank(frame_code)) {
            sql.append(" and u.vin_no like '%" + frame_code + "%'");
        }
        if (StringUtils.isNotBlank(caseCode)) {
            sql.append(" and u.code like '%" + caseCode + "%'");
        }
        if (StringUtils.isNotBlank(companyName)) {
            sql.append(" and s.name like '%" + companyName + "%'");
        }
        if (StringUtils.isNotBlank(plateNumber)) {
                sql.append(" and u.plate_number like '%" + plateNumber + "%'");
        }
        //开始时间
        if (StringUtils.isNotBlank(createTime)) {
            sql.append(" and u.create_time >= '"+createTime+"'");
        }
        // 结束时间
        if (StringUtils.isNotBlank(finishTime)) {
            sql.append(" and u.create_time <= '"+finishTime+"'");
        }
        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[]{"ORDER_CODE","CREATE_TIME","VIN_NO","NAME","CODE","SERVICE_NAME","STATUS","TASK_STATUS","PLATE_NUMBER"}));
            }
            if(lists != null && lists.size() > 0) {
                vo.setTotal(lists.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return vo;
    }

    @Override
    public Vo caseEnterQuery(String state,HttpServletRequest request, String caseCode, String frame_code, String createTime, String finishTime) {
        //获取登录信息
        LoginUserVo logininfo=(LoginUserVo)request.getSession().getAttribute("logininfo");
        Vo vo=new Vo();
        //声明一个分页对象
        PageInfo pageInfo=new PageInfo();
        //获取页数和一页显示多少行并将其放入对象中
        pageInfo.setPage(UtilTools.getPage(request));
        pageInfo.setRows(UtilTools.getRows(request));
        //sql动态拼接
        StringBuffer sql=null;
        if("0".equals(state)){
            sql = new StringBuffer("select DISTINCT u.tid tid,u.id id,u.code orderCode,u.create_time " +
                    "create_time,u.vin_no vin_no,s.name name, "+
                    "s.code code,b.name serviceName,u.order_status order_status,w.state state,w.update_time update_time from "+
                    "(select t.create_time createTime,t.code taskCode,u.code code,u.create_time,u.vin_no,u.id id,u.order_status," +
                    "u.service_id,t.service_supplier_id,u.contract_id contract_id,t.id tid from user_order_his u "+
                    "left join task_order_his t on t.user_order_id=u.id "+
                    "union select t.create_time createTime,t.code taskCode,u.code code,u.create_time create_time,u.vin_no vin_no," +
                    "u.id id,u.order_status order_status,u.service_id service_id "+
                    ",t.service_supplier_id service_supplier_id,u.contract_id contract_id,t.id tid from user_order u "+
                    "left join task_order t on t.user_order_id=u.id "+
                    ") u "+
                    "left join supplier s on u.service_supplier_id=s.id "+
                    "left join base_service b on b.id=u.service_id "+
                    "left join jlr_epqr w on w.task_order_id = u.tid " +
                    "where b.id in (1041,1050,1500,1501,1520,1521) " +
                    "and u.order_status in (21,23,25,28,31) " +
                    "and w.state = 1 " +
                    "and u.contract_id in (select contract_id from jlr_contract_visual where jlr_user_id ="+logininfo.getId()+")");
        }else{
            sql = new StringBuffer("select DISTINCT u.tid tid,u.id id,u.code orderCode,u.create_time " +
                    "create_time,u.vin_no vin_no,s.name name, "+
                    "s.code code,b.name serviceName,u.order_status order_status,w.state state,w.update_time update_time from "+
                    "(select t.create_time createTime,t.code taskCode,u.code code,u.create_time,u.vin_no,u.id id,u.order_status," +
                    "u.service_id,t.service_supplier_id,u.contract_id contract_id,u.contract_destination_id destination_code,t.id tid from user_order_his u "+
                    "left join task_order_his t on t.user_order_id=u.id "+
                    "union select t.create_time createTime,t.code taskCode,u.code code,u.create_time create_time,u.vin_no vin_no," +
                    "u.id id,u.order_status order_status,u.service_id service_id "+
                    ",t.service_supplier_id service_supplier_id,u.contract_id contract_id,u.contract_destination_id destination_code,t.id tid from user_order u "+
                    "left join task_order t on t.user_order_id=u.id "+
                    ") u "+
                    "left join supplier s on u.service_supplier_id=s.id "+
                    "left join jlr_epqr w on w.task_order_id = u.tid " +
                    "left join base_service b on b.id=u.service_id "+
                    "where b.id in (1041,1050,1500,1501,1520,1521) " +
                    "and u.order_status in (21,23,25,28,31) " +
                    "and u.destination_code in (select contract_destination_id from jlr_destination_visual where jlr_user_id ="+logininfo.getId()+")");
        }
        if (StringUtils.isNotBlank(frame_code)) {
            sql.append("  and u.vin_no like '%" + frame_code + "%'");
        }
        if (StringUtils.isNotBlank(caseCode)) {
            sql.append("  and u.code like '%" + caseCode + "%'");
        }
        //开始时间
        if (StringUtils.isNotBlank(createTime)) {
            sql.append("  and u.create_time >= '"+createTime+"'");
        }
        // 结束时间
        if (StringUtils.isNotBlank(finishTime)) {
            sql.append("  and u.create_time <= '"+finishTime+"'");
        }
        String countSql=sql.append(" order by w.update_time desc").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[]{"TID","ID","ORDER_CODE","CREATE_TIME","VIN_NO","NAME","CODE","SERVICE_NAME","STATUS","STATE"}));
            }
            if(lists != null && lists.size() > 0) {
                vo.setTotal(lists.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return vo;
    }

    @Override
    public Vo caseEnterInfo(HttpServletRequest request, String caseCode,String tid) {
        //获取用户信息
        LoginUserVo logininfo=(LoginUserVo)request.getSession().getAttribute("logininfo");
        //声明一个vo对象
        Vo vo=new Vo();
        //创建sql
        StringBuffer sql=new StringBuffer("select DISTINCT u.id uid,u.tid tid,u.code orderCode,u.create_time " +
                    "create_time,u.vin_no vin_no,s.name name, "+
                    "s.code code,b.name serviceName,u.model model,u.plate_number plate_number,m.start_time start_time,j.level_name levelName," +
                    "u.finish_time finish_time,j.level_name levelNames,d.name dName,d.brand_name brandName,e.dms_code dms_code," +
                    "e.trouble_reason trouble_reason,e.mileage mileage,e.dphm dphm,e.arrive_time arrive_time,e.remaer remaer," +
                    "e.choice_type choice_type,e.trouble_code trouble_code,e.repair repair,e.ref_time ref_time,e.finish_time finishes_time" +
                    ",e.hand_time hand_time,e.use_time use_time,e.state state from "+
                    "(select u.code code,u.create_time,u.vin_no,u.order_status," +
                    "u.service_id,t.service_supplier_id,u.contract_id contract_id,u.contract_destination_id destination_code," +
                    "u.model model,u.plate_number plate_number,u.member_service_group_id member_service_group_id,u.finish_time finish_time," +
                    "u.malfunction_level1 malfunction_level1,u.malfunction_level2 malfunction_level2,u.id id,u.contract_destination_id contract_destination_id,t.id tid " +
                    "from user_order_his u "+
                    "left join task_order_his t on t.user_order_id=u.id "+
                    "union select u.code code,u.create_time create_time,u.vin_no vin_no," +
                    "u.order_status order_status,u.service_id service_id "+
                    ",t.service_supplier_id service_supplier_id,u.contract_id contract_id,u.contract_destination_id destination_code," +
                    "u.model model,u.plate_number plate_number,u.member_service_group_id member_service_group_id,u.finish_time finish_time," +
                    "u.malfunction_level1 malfunction_level1,u.malfunction_level2 malfunction_level2,u.id id,u.contract_destination_id contract_destination_id,t.id tid " +
                    "from user_order u "+
                    "left join task_order t on t.user_order_id=u.id "+
                    ") u "+
                    "left join supplier s on u.service_supplier_id = s.id "+
                    "left join base_service b on b.id = u.service_id " +
                    "left join contract_member_service_group m on u.member_service_group_id=m.id " +
                    "left join contract_trouble_level j on j.id = u.malfunction_level1 " +
                    "left join contract_destination d on d.id = u.contract_destination_id " +
                    "left join jlr_epqr e on e.task_order_id = u.tid " +
                    "where u.id = '" + caseCode+"'");
        if (StringUtils.isNotBlank(tid)) {
            sql.append("  and u.tid = '" + tid +"'");
        }
        try {
            //获取案件详情信息
            List list = getRsBySql(sql.toString());
                if (list != null && list.size() > 0) {
                    vo.setRows(UtilTools.listTojsonArray(list, new String[]{"UID","TID","ORDER_CODE", "CREATE_TIME", "VIN_NO", "NAME", "CODE", "SERVICE_NAME", "MODEL", "PLATENUMBER", "STARTTIME", "LEVELNAME1", "FINISHTIME", "LEVELNAME2", "DNAME", "BRANDNAME", "DMS", "REASON", "MILEAGE", "DNUMBER", "ARRIVETIME", "REMARK", "CHOICE", "PART", "REPAIR", "REFTIME", "FINTIME", "HANDTIME", "USETIME","STATE"}));
                }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return vo;
    }

    @Override
    public JSONObject getTroubleCode(HttpServletRequest request) throws Exception {
        //获取参数
        String firstParam = request.getParameter("firstParam");
        String flag = request.getParameter("flag");
        //声明一个对象
        JSONObject jsonObject = new JSONObject();
        //创建集合
        List<String> idList = new ArrayList<String>();
        List<String> listfirst = new ArrayList<String>();// 祖
        List<String> listSecond = new ArrayList<String>();// 父

        // 第一级系统
        if ("1".equals(flag)) {
            String sql = "select id,name from jlr_trouble_parts where parent_id = 0";
            //获取一级故障信息
            List list = getRsBySql(sql);
            //遍历获取到的信息将其放入对象中并将对象放入集合中
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Object[] objects = (Object[]) list.get(i);
                    listfirst.add(objects[1].toString());
                    idList.add(objects[0].toString());
                }
                jsonObject.put("listfirst", listfirst);
                jsonObject.put("idList", idList);
            }
        }
        // 第二级系统和第三级
        if ("2".equals(flag) || "3".equals(flag)) {
            String sql = "select id,name from jlr_trouble_parts where parent_id ="+firstParam;
            //获取二级故障和三级故障信息将其放入对象中并将对象放入集合中
            List list = getRsBySql(sql);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Object[] objects = (Object[]) list.get(i);
                    listSecond.add(objects[1].toString());
                    idList.add(objects[0].toString());
                }
                jsonObject.put("listSecond", listSecond);
                jsonObject.put("idList", idList);
            }
        }
        return jsonObject;
    }

    @Override
    public JSONObject caseDetailSave(HttpServletRequest request) throws Exception {
        //声明一个object对象
        JSONObject jsonObject = new JSONObject();
        //获取参数
        String uid = request.getParameter("uid");
        String tid = request.getParameter("tid");
        String mileage = request.getParameter("mileage");
        String dphm = request.getParameter("dphm");
        Date arriveTime = TextUtils.isBlank(request.getParameter("arriveTime")) ? null : df.parse(request.getParameter
                ("arriveTime"));
        Date refTime = TextUtils.isBlank(request.getParameter("refTime")) ? null : df.parse(request.getParameter
                ("refTime"));
        Date repairFinishTime = TextUtils.isBlank(request.getParameter("repairFinishTime")) ? null : df.parse(request
                .getParameter("repairFinishTime"));
        Date handTime = TextUtils.isBlank(request.getParameter("handTime")) ? null : df.parse(request.getParameter
                ("handTime"));
        String finalChoice = request.getParameter("finalChoice");
        Date useTime = TextUtils.isBlank(request.getParameter("useTime")) ? null : df.parse(request.getParameter
                ("useTime"));
        String troubleCodeValue = request.getParameter("troubleCodeValue");
        String troubleReasonVaule = request.getParameter("troubleReasonValue");
        String repair = request.getParameter("repair");
        String remark = request.getParameter("remark");
        String dmsCode = request.getParameter("dmsCode");
        String state = request.getParameter("state");
        JLRepqr epqrJlr = null;
        //创建一个时间对象
        Date date=new Date();
        try {
            //创建一个sql
            StringBuffer hql =new StringBuffer("from JLRepqr where order_id= " + uid);
            if(tid != null && tid != ""){
                hql.append(" and task_order_id ="+tid);
            }
            //根据订单id获取案件详情信息
            List list = getRsByHql(hql.toString());
            if (list != null && list.size() > 0) {
                epqrJlr = (JLRepqr) list.get(0);
            } else {
                //若信息为空则证明该操作为添加
                epqrJlr = new JLRepqr();
                //生成主键id并放入对象中
                epqrJlr.setId(Integer.valueOf((System.currentTimeMillis() + "").substring(4)));
                epqrJlr.setCreate_time(date);
            }
            if(!TextUtils.isBlank(tid)){
                epqrJlr.setTask_order_id(Integer.valueOf(tid));
            }else {
                epqrJlr.setTask_order_id(0);
            }
                epqrJlr.setUpdate_time(date);
                epqrJlr.setHand_time(handTime);
                epqrJlr.setState(Integer.valueOf(state));
                epqrJlr.setMileage(TextUtils.isBlank(mileage) ? 0 : Integer.valueOf(mileage));
                epqrJlr.setDphm(dphm);
                epqrJlr.setArrive_time(arriveTime);
                epqrJlr.setRef_time(refTime);
                epqrJlr.setFinish_time(repairFinishTime);
                epqrJlr.setChoice_type(finalChoice);
                epqrJlr.setUse_time(useTime);
                epqrJlr.setTrouble_reason(troubleReasonVaule);
                epqrJlr.setTrouble_code(troubleCodeValue);
                epqrJlr.setRepair(repair);
                epqrJlr.setRemaer(remark);
                epqrJlr.setOrder_id(Integer.valueOf(uid));
                epqrJlr.setDms_code(dmsCode);
            saveOrUpdate(epqrJlr);
            jsonObject.put("sign", true);
            //回传json对象
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("sign", false);
            return jsonObject;
        }
    }
}
