package com.palmnest.webapp.controller.api;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants.SignType;
import com.github.wxpay.sdk.WXPayUtil;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.CommonDto;
import com.palmnest.application.dto.RepairUserDto;
import com.palmnest.application.dto.input.RepairBillInputDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.application.dto.output.RepairParamDto;
import com.palmnest.application.dto.output.RepairSupportUserDto;
import com.palmnest.model.Element;
import com.palmnest.model.User;
import com.palmnest.model.repair.*;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.repair.*;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Controller
@RequestMapping(value = "/api/repairBill")
public class ApiRepairBillController extends BaseFormController {

    @Autowired
    private ElementGroupManager elementGroupManager;
    @Autowired
    private RepairBillService repairBillService;
    @Autowired
    private RepairBillManager repairBillManager;
    @Autowired
    private UserManager userManager;
    @Autowired
    private BaseRedisService baseRedisService;
    @Autowired
    private RepairOperateRecordManager repairOperateRecordManager;
    @Autowired
    private UserRepairTypeManager userRepairTypeManager;
    @Autowired
    private RepairBillMaterialManager repairBillMaterialManager;
    @Autowired
    private RepairMaterialManager repairMaterialManager;
    @Autowired
    private RepairAddressManager repairAddressManager;
    //dz add
    @Autowired
    private RepairConfigManager repairConfigManager;

    public static String webUrl = PropertiesKit.readPropertiesValue("callbackWebUrl", "wechat.properties");
    public static String payNotifyAction = PropertiesKit.readPropertiesValue("payNotifyAction", "wechat.properties");
    public static String inprocessIndoorBillLimit = PropertiesKit.readPropertiesValue("inprocessIndoorBillLimit", "app.properties");
    public static String inprocessOutdoorBillLimit = PropertiesKit.readPropertiesValue("inprocessOutdoorBillLimit", "app.properties");

    /**
     * 发起维修首页
     *
     * @return
     */
    @RequestMapping(value = "/index")
    @ResponseBody
    public AppResultDto index(@RequestParam(value = "orgId",required = false) Integer orgId,HttpServletRequest request) {

        //报修方式 区域 类型 小类型
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }

        RepairParamDto dto = new RepairParamDto();

        User user = userManager.getUserByUsername2(userName);
        dto.setUsername(user.getFullName());
        dto.setTelephone(user.getTelephone());

        List<Element> repairWayGroup = elementGroupManager.getElementsByGroupName("repairWayGroup");
        Element element = elementGroupManager.getByItemCode("wechatRepair");

        repairWayGroup.remove(element);

        List<Element> repairAreaGroup = elementGroupManager.getElementsByGroupName("repairAreaGroup");
        dto.setRepairAreaGroup(elementGroupManager.convert(repairAreaGroup));
        dto.setRepairWayGroup(elementGroupManager.convert(repairWayGroup));

        //维修类型增加orgId隔离
        if (null != orgId) {
            //大类
            List<ElementDto> elementDtos = elementGroupManager.getOrgElementGroupInfoV2(String.valueOf(orgId), "repairTypeGroup");
            dto.setRepairTypeGroup(elementDtos);

            if (null != elementDtos && elementDtos.size() > 0) {
                //小类
                List<Element> repairTypeaDetailGroup = elementGroupManager.getElementsByGroupName(elementDtos.get(0).getItemcode());
                dto.setRepairTypeaDetailGroup(elementGroupManager.convert(repairTypeaDetailGroup));
            }

            //设置默认配置
            RepairConfig repairConfig = repairConfigManager.getByOrgId(orgId);
            if (null != repairConfig) {
                dto.setCheckFloor(repairConfig.getCheckFloor());
            }
        } else {
            List<Element> repairTypeGroup = elementGroupManager.getElementsByGroupName("repairTypeGroup");
            if (null != repairTypeGroup && repairTypeGroup.size() > 0) {
                List<Element> repairTypeaDetailGroup = elementGroupManager.getElementsByGroupName(repairTypeGroup.get(0).getItemcode());
                dto.setRepairTypeaDetailGroup(elementGroupManager.convert(repairTypeaDetailGroup));
            }
            dto.setRepairTypeGroup(elementGroupManager.convert(repairTypeGroup));
        }
        return AppResultUtil.createSuccesDto(dto);
    }


    /**
     * 根据维修类型查找维修类型详情
     * @param repairTypeId
     * @return
     */
    @RequestMapping(value = "/getRepairTypeaDetail")
    @ResponseBody
    public AppResultDto getRepairTypeaDetail(@RequestParam("repairTypeId") Long repairTypeId) {
        List<ElementDto> elementDtos = new ArrayList<>();
        Element element = elementGroupManager.getElementId(repairTypeId);
        if (null == element) {
            return AppResultUtil.createSuccesDto(elementDtos);
        }
        List<Element> repairTypeaDetailGroup = elementGroupManager.getElementsByGroupName(element.getItemcode());
        elementDtos = elementGroupManager.convert(repairTypeaDetailGroup);
        return AppResultUtil.createSuccesDto(elementDtos);
    }

    /**
     * 发起维修
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/repair")
    @ResponseBody
    public AppResultDto repair(@ModelAttribute("repairBillInputDto") RepairBillInputDto dto, MultipartHttpServletRequest request) {
        try {
            if (null == dto.getOrgId()) {
                String userName = baseRedisService.get(request.getHeader("token"));
                if (userName == null) {
                    return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
                }
                User user = userManager.getUserByUsername2(userName);
                String orgIds = getUserManageOrgIds(user);//例如:1,25,2
                if (StringUtil.isNotEmpty(orgIds)) {
                    String[] orgArr = orgIds.split(",");
                    dto.setOrgId(Integer.parseInt(orgArr[0]));
                }

            }
            if(null == dto || null == dto.getRepairType() || null == dto.getRepairTypeDetail()){
                return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_ERROR, "保存维修单失败,维修类型必填");
            }
            RepairBill bill = repairBillService.repair(dto, request);
            repairBillService.push(bill);
            return AppResultUtil.createSuccesDto(repairBillService.convert(bill));
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_ERROR, "保存维修单失败");
        }
    }


    /**
     * 修改维修单分类 并重新派单
      * @param id 维修单id
     * @param repairTypeId 维修大类id
     * @param repairTypeDetailId 维修小类id
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateBillType")
    @ResponseBody
    public AppResultDto updateBillType(@RequestParam("id") Long id,
                                       @RequestParam("repairTypeId") Long repairTypeId,
                                       @RequestParam("repairTypeDetailId") Long repairTypeDetailId,
                                       HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        if(null == repairTypeId || (null != repairTypeId && 0 == repairTypeId.intValue())){
            return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "维修大类不能为空");
        }
        if(null == repairTypeDetailId || (null != repairTypeDetailId && 0 == repairTypeDetailId.intValue())){
            return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "维修小类不能为空");
        }

        try {
            RepairBill bill = repairBillManager.get(id);
            //状态 TODO
            if (bill.getStatus().equals(CodeConstants.COMPLETED) ||
                    bill.getStatus().equals(CodeConstants.UNAUDIT) ||
                    bill.getStatus().equals(CodeConstants.CANCEL) ) {
                return AppResultUtil.createErrorDto(AppConstants.SEND_BILL_ERROR, "修改失败，该单已取消或已完成");
            }
            bill.setRepairType(repairTypeId);
            bill.setRepairTypeDetail(repairTypeDetailId);
            repairBillManager.updateModel(bill);

            User user1 = userManager.getUserByUsername2(userName);


            RepairOperateRecord operateRecord = new RepairOperateRecord(bill.getId(), userName, new Date());
            operateRecord.setUserId(user1.getId());
            operateRecord.setOperateType(CodeConstants.REPAIR);
            operateRecord.setDetail(user1.getFullName() + "修改维修单类型");
            repairOperateRecordManager.saveModel(operateRecord);

//                String title = "有维修单已派给你，请查看";
//                String content = repairBillService.getPushContent(bill);
//                repairBillService.pushMessage(bill.getId(), CodeConstants.COMMON_PUSH_CODE, title, content, Arrays.asList(user));

            return AppResultUtil.createSuccesDto();
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.SEND_ERROR, "改单失败");
        }
    }

    /**
     * 查找维修单详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/getDetail")
    @ResponseBody
    public AppResultDto getDetail(@RequestParam("id") Long id) {
        boolean bool = repairBillManager.exists(id);
        if (bool) {
            return AppResultUtil.createSuccesDto(repairBillService.findById(id));
        } else {
            return AppResultUtil.createErrorDto(AppConstants.BILL_NON_EXISTENT, "该单据不存在");
        }

    }

    /**
     * @param request
     * @return 查找维修单列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public AppResultDto list(@RequestParam("status") Integer status, HttpServletRequest request) {
        try {

            String userName = baseRedisService.get(request.getHeader("token"));

            if (userName == null) {
                return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
            }

            int pageSize = Integer.parseInt(request.getParameter("pageSize"));
            int pageNo = Integer.parseInt(request.getParameter("pageNo"));

            log.info("============token:"+request.getHeader("token")+",status:"+status+"," +
                    "pageSize:"+pageSize+",pageNo:"+pageNo+",orgId:"+request.getParameter("orgId"));

            //如果是可抢单，则查找同维修类型的单
            //如果是其他状态，则查找自己名下的单
            String repairTypeIds = "";
            User user = userManager.getUserByUsername2(userName);
            Long serviceUser = user.getId();
            if (status.equals(CodeConstants.IS_SINGLE)) {
                List<Element> types = userRepairTypeManager.findByUser(user.getId());
                for (Element e : types) {
                    if (e != null) {
                        repairTypeIds += "," + e.getId();
                    }
                }
                if (repairTypeIds.length() > 1) {
                    repairTypeIds = repairTypeIds.substring(1);
                }
                serviceUser = null;
            } else {
                repairTypeIds = null;
            }

            Integer orgId = null;
            if (!StringUtil.isNotEmpty(request.getParameter("orgId"))) {
                String orgIds = getUserManageOrgIds(user);//例如:1,25,2
                if (StringUtil.isNotEmpty(orgIds)) {
                    String[] orgArr = orgIds.split(",");
                    orgId = Integer.parseInt(orgArr[0]);
                }
            }
            Page page = repairBillService.findPageByStatus(status, repairTypeIds, serviceUser, pageSize, pageNo, orgId);
            return AppResultUtil.createSuccesDto(page);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_LIST_ERROR, "查询列表失败");
        }
    }

    /**
     *
     * @param code 管理列表 状态(100:全部;200:待抢单;300:可派单;400:已完成600:进行中700:待确认)
     * @param listType 列表类型 listType 2：管理列表 3：我的派单
     * @param request
     * @return
     */
    @RequestMapping(value = "/managerList")
    @ResponseBody
    public AppResultDto managerList(@RequestParam("code") Integer code,
                                    @RequestParam(value = "listType",required = false)Integer listType ,HttpServletRequest request) {

        try {
            String userName = baseRedisService.get(request.getHeader("token"));
            if (userName == null) {
                return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
            }
            int pageSize = Integer.parseInt(request.getParameter("pageSize"));
            int pageNo = Integer.parseInt(request.getParameter("pageNo"));
            //如果是可抢单，则查找同维修类型的单
            //如果是其他状态，则查找自己名下的单

            User user = userManager.getUserByUsername2(userName);
            log.info("========token:" + request.getHeader("token") + "   username:" + userName + "   user:" + user+" listType:"+listType);

            //状态(100:全部;200:待抢单;300:可派单;400:已完成;500:待审核)  新增待派单 201
            Map<String, Object> params = new HashMap<String, Object>();

            String status = null;
            if (code.intValue() == 200) { //可抢单
                status = CodeConstants.IS_SINGLE + "";
            }
            //新增待派单状态
            if (code.intValue() == 201) {//待派单
                status = CodeConstants.TO_SEND + "";
            }
            if (code.intValue() == 300) {//待完成 进行中+挂单中
                status = CodeConstants.IN_PROGRESS + "," + CodeConstants.IN;
            }
            if (code.intValue() == 400) { //已完成
                status = CodeConstants.COMPLETED + "";
            }
            if (code.intValue() == 500) { //待审核
                status = CodeConstants.TO_AUDIT + "";
            }
            if (code.intValue() == 600) { //进行中
                status = CodeConstants.IN_PROGRESS + "";
            }
            if (code.intValue() == 700) { //待确认
                status = CodeConstants.IN_PROGRESS + "";
                params.put("confirmStatus", 1); //待确认
            }

            params.put("status", status);
            Integer orgId = null;
            if (!StringUtil.isNotEmpty(request.getParameter("orgId"))) {
                String orgIds = getUserManageOrgIds(user);//例如:1,25,2
                if (StringUtil.isNotEmpty(orgIds)) {
                    String[] orgArr = orgIds.split(",");
                    orgId = Integer.parseInt(orgArr[0]);
                }
            }
            params.put("orgIds", orgId);

            Page page;
            if(listType != null && listType == 3){
                params.put("userId",user.getId());
                page = repairBillService.findPageByRepairUser(params, pageSize, pageNo);
            }else { //管理列表
                String repairTypeIds = "";
                List<Element> types = userRepairTypeManager.findByUser(user.getId());
                for (Element e : types) {
                    repairTypeIds += "," + e.getId();
                }
                if (repairTypeIds.length() > 1) {
                    repairTypeIds = repairTypeIds.substring(1);
                }
                params.put("repairTypeIds", repairTypeIds);
                page = repairBillService.findPageBy(params, pageSize, pageNo);
            }

            return AppResultUtil.createSuccesDto(page);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_LIST_ERROR, "查询列表失败");
        }
    }

    /**
     * 抢单
     */
    @RequestMapping(value = "/grabBill")
    @ResponseBody
    public AppResultDto grabBill(@RequestParam("id") Long id, HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        RepairBill bill = repairBillManager.get(id);
        if (!bill.getStatus().equals(CodeConstants.IS_SINGLE)) {
            return AppResultUtil.createErrorDto(AppConstants.GRAB_BILL_ERROR, "抢单失败，该单不是可抢单状态");
        }
        //TODO 判断室内单有1个 或者 公共区域/空置房有3个时 不让抢单
        Integer version = bill.getVersion();
        try {
//			Element e1 = elementGroupManager.getByItemCode(CodeConstants.INDOOR);
//			Element e2 = elementGroupManager.getByItemCode(CodeConstants.PUBLIC);
//			Element e3 = elementGroupManager.getByItemCode(CodeConstants.VACANCYRATE);
            User user = userManager.getUserByUsername2(userName);
//			List<RepairBill> indoorBills = repairBillManager.findBy(user.getId(), e1.getId());
//			List<RepairBill> publicBills = repairBillManager.findBy(user.getId(), e2.getId());
//			List<RepairBill> vacancyRateBills = repairBillManager.findBy(user.getId(), e3.getId());
//			if(indoorBills.size() >= Integer.parseInt(inprocessIndoorBillLimit)) {
//				return AppResultUtil.createErrorDto(AppConstants.TOO_MANY_BILL_ERROR, "抢单失败,进行中的室内维修单超出数量限制");
//			}
//			if(publicBills.size()+vacancyRateBills.size() >= Integer.parseInt(inprocessOutdoorBillLimit)) {
//				return AppResultUtil.createErrorDto(AppConstants.TOO_MANY_BILL_ERROR, "抢单失败,进行中的公区和空置房维修单超出数量限制");
//			}

            //dz add 1113
            RepairConfig s_con = repairConfigManager.getByOrgId(bill.getOrgId());
            Integer c = repairBillManager.findCountBy(CodeConstants.IN_PROGRESS, null, user.getId(), null);
            int max_bills = 3;
            if (s_con != null) {
                max_bills = s_con.getMax_bills();
            }
            if (c >= max_bills) {

                return AppResultUtil.createErrorDto(AppConstants.SEND_ERROR, "抢单失败， 进行中工单数量已达上限！");
            }


            //场景：当工程人员用正确的账号登录,正常收到通知后切换账号,再点击抢单,抢单成功,
            // 这时需要做校验判断是否是正确的人接单，否则抢单失败
            UserRepairType userRepairType =userRepairTypeManager.findByRepair(user.getId(),bill.getRepairType());
            if(null == userRepairType){
                return AppResultUtil.createErrorDto(AppConstants.SEND_ERROR,
                        "抢单失败，"+(StringUtils.isEmpty(userName)?"":userName)+" 用户无该抢单权限！");
            }

            //------------longmeizhen--------------
            //有预约时间的时候单据的状态为挂单，没有预约时间的时候单据为进行中
            if (bill.getMeetingTime() != null) {
                bill.setStatus(CodeConstants.IN);//抢单成功设置状态为进行中
            } else {
                bill.setStatus(CodeConstants.IN_PROGRESS);//抢单成功设置状态为进行中
            }

            if(null == bill.getSingleTime()){//记录 抢单时间
                bill.setSingleTime(new Date());
            }

            bill.setServiceUser(user.getId().toString());
            bill.setModifyTime(new Date());
            bill.setVersion(version == null ? 1 : version + 1);
            //repairBillManager.updateModel(bill);
            Integer count = repairBillManager.updateGrabBill(bill, version);
            if (count == 0) {
                return AppResultUtil.createErrorDto(AppConstants.GRAB_BILL_ERROR, "抢单失败,订单已被抢！");
            }
            RepairOperateRecord operateRecord = new RepairOperateRecord(id, user.getId(), userName, new Date());
            operateRecord.setOperateType(CodeConstants.GRAB);
//			operateRecord.setDescription(user.getFullName()+"抢单");
            operateRecord.setDetail(user.getFullName() + "抢单");
            //------------longmeizhen--------------
            //将挂单重新开始时间等于预约时间
            if (bill.getMeetingTime() != null) {

                RepairOperateRecord opRecord = new RepairOperateRecord(id, user.getId(), userName, new Date());
                opRecord.setExpectedTime(DateHelper.formatDate(bill.getMeetingTime(), DateHelper.DATE_STRING));
                opRecord.setOperateType(CodeConstants.PENDING);
                opRecord.setDetail(user.getFullName() + "挂单");
                repairOperateRecordManager.saveModel(opRecord);
            }


            repairOperateRecordManager.saveModel(operateRecord);

            if (bill.getBillFrom().intValue() == 2) {
                repairBillService.pushWechatTemplateMsg(bill, 1);
            }
            return AppResultUtil.createSuccesDto();
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.GRAB_BILL_ERROR, "抢单失败，数据错误！");
        }

    }

    /**
     * 转单
     */
    @RequestMapping(value = "/transferBill")
    @ResponseBody
    public AppResultDto transferBill(@RequestParam("id") Long id, @RequestParam("receiverId") Long receiverId, @RequestParam(required = false) String description, HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        try {
            RepairBill bill = repairBillManager.get(id);
            if (!bill.getStatus().equals(CodeConstants.IN_PROGRESS) && !bill.getStatus().equals(CodeConstants.IN)) {
                return AppResultUtil.createErrorDto(AppConstants.TRANFER_BILL_ERROR, "转单失败，该单不是可转单状态");
            }
            //TODO 判断室内单有1个 或者 公共区域/空置房有3个时 不让抢单
//			Element e1 = elementGroupManager.getByItemCode(CodeConstants.INDOOR);
//			Element e2 = elementGroupManager.getByItemCode(CodeConstants.PUBLIC);
//			Element e3 = elementGroupManager.getByItemCode(CodeConstants.VACANCYRATE);
            User user1 = userManager.getUserByUsername2(userName);
            User user = userManager.get(receiverId);
//			List<RepairBill> indoorBills = repairBillManager.findBy(user.getId(), e1.getId());
//			List<RepairBill> publicBills = repairBillManager.findBy(user.getId(), e2.getId());
//			List<RepairBill> vacancyRateBills = repairBillManager.findBy(user.getId(), e3.getId());
//			if(indoorBills.size() >= 1 || (publicBills.size()+vacancyRateBills.size()) >=3) {
//				return AppResultUtil.createErrorDto(AppConstants.TOO_MANY_BILL_ERROR, "转单失败,接收者名下待处理单过多,请转给其他人处理");
//			}

            //dz add 1113
            RepairConfig s_con = repairConfigManager.getByOrgId(bill.getOrgId());
            Integer c = repairBillManager.findCountBy(CodeConstants.IN_PROGRESS, null, user.getId(), null);
            int max_bills = 3;
            if (s_con != null) {
                max_bills = s_con.getMax_bills();
            }
            if (c >= max_bills) {

                return AppResultUtil.createErrorDto(AppConstants.SEND_ERROR, "转单失败，所选转单人工单数量已达上限！");
            }

            bill.setStatus(CodeConstants.TRANSFERED);//转单成功设置状态为转单中
            bill.setServiceUser(user.getId().toString());
            repairBillManager.updateModel(bill);
            RepairOperateRecord operateRecord = new RepairOperateRecord(id, user1.getId(), userName, new Date());
            operateRecord.setOperateType(CodeConstants.TRANSFER);
//			operateRecord.setDescription(description);
            operateRecord.setDetail(user1.getFullName() + "转单给" + user.getFullName() + "转单原因：" + description);
            repairOperateRecordManager.saveModel(operateRecord);

            //给接收人推送消息
            String title = "有维修单已转给你，请进行接收或拒绝";
            String content = repairBillService.getPushContent(bill);
            repairBillService.pushMessage(bill.getId(), CodeConstants.COMMON_PUSH_CODE, title, content, Arrays.asList(user));
            return AppResultUtil.createSuccesDto();
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.TRANFER_ERROR, "转单失败");
        }
    }

    /**
     * 处理转单请求
     */
    @RequestMapping(value = "/handleTransferBill")
    @ResponseBody
    public AppResultDto handleTransferBill(@RequestParam("id") Long id, Integer operateType, HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        try {
            RepairBill bill = repairBillManager.get(id);
            RepairOperateRecord record = repairOperateRecordManager.findBy(id, CodeConstants.TRANSFER);
            if (record == null) {
                return AppResultUtil.createErrorDto(AppConstants.HANDLE_TRANSFER_ERROR, "处理转单失败");
            }
            User user = userManager.getUserByUsername2(userName);
            if (operateType.intValue() == 1) {//接受
                RepairConfig s_con = repairConfigManager.getByOrgId(bill.getOrgId());
                Integer c = repairBillManager.findCountBy(CodeConstants.IN_PROGRESS, null, user.getId(), null);
                int max_bills = 3;
                if (s_con != null) {
                    max_bills = s_con.getMax_bills();
                }
                if (c >= max_bills) {
                    return AppResultUtil.createErrorDto(AppConstants.SEND_ERROR, "接单失败，接单数量超出上限！");
                }


                bill.setServiceUser(user.getId().toString());
            } else if (operateType.intValue() == 2) {//拒绝
                bill.setServiceUser(record.getUserId().toString());
            }
            bill.setStatus(CodeConstants.IN_PROGRESS);//转单成功设置状态为进行中
            repairBillManager.updateModel(bill);

            RepairOperateRecord operateRecord = new RepairOperateRecord(id, user.getId(), userName, new Date());
            operateRecord.setOperateType(CodeConstants.TRANSFER_OPERATE);
            operateRecord.setDetail(user.getFullName() + "接受转单");
            if (operateType.intValue() == 2) {
                operateRecord.setDetail(user.getFullName() + "拒绝转单");
            }
            repairOperateRecordManager.saveModel(operateRecord);

            //拒绝后给转单发起人推送消息
            if (operateType.intValue() == 2) {
                String title = "您的转单已被拒绝，请及时处理";
                String content = repairBillService.getPushContent(bill);
                User user1 = userManager.get(record.getUserId());
                repairBillService.pushMessage(bill.getId(), CodeConstants.COMMON_PUSH_CODE, title, content, Arrays.asList(user1));
            }
            return AppResultUtil.createSuccesDto();
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.HANDLE_TRANSFER_ERROR, "处理转单失败");
        }
    }

    /**
     * 查找所有维修类型
     * @return
     */
    @RequestMapping(value = "/getRepairType")
    @ResponseBody
    public AppResultDto getRepairType() {
        List<Element> repairTypeGroup = elementGroupManager.getElementsByGroupName("repairTypeGroup");
        return AppResultUtil.createSuccesDto(elementGroupManager.convert(repairTypeGroup));
    }

    /**
     * 查找对应维修类型下的人员
     * @param repairTypeId
     * @return
     */
    @RequestMapping(value = "/getRepairTypeUser")
    @ResponseBody
    public AppResultDto getRepairTypeUser(@RequestParam("repairTypeId") Long repairTypeId) {
        return AppResultUtil.createSuccesDto(repairBillService.findByTypeId(repairTypeId));
    }

    /**
     * 查找维修单对应维修类型下的人员
     * @param id
     * @return
     */
    @RequestMapping(value = "/getRepairUser")
    @ResponseBody
    public AppResultDto getRepairUser(@RequestParam("id") Long id) {
        RepairBill bill = repairBillManager.get(id);
        List<RepairUserDto> ls = repairBillService.getRepairUsers(bill.getRepairType(), bill.getOrgId());
        return AppResultUtil.createSuccesDto(ls);
    }

    /**
     * 查找维修单对应维修类型下的人员
     * @return
     */
    @RequestMapping(value = "/getPendReason")
    @ResponseBody
    public AppResultDto getPendReason() {
        List<Element> repairPendReasonGroup = elementGroupManager.getElementsByGroupName("repairPendReasonGroup");
        List<CommonDto> dtos = new ArrayList<CommonDto>();
        for (Element e : repairPendReasonGroup) {
            dtos.add(new CommonDto(e.getId(), e.getItemname()));
        }
        return AppResultUtil.createSuccesDto(dtos);
    }

    /**
     * 挂单
     */
    @RequestMapping(value = "/pendBill")
    @ResponseBody
    public AppResultDto pendBill(@RequestParam Long id, @RequestParam String reasonIds, @RequestParam(required = false) String description, @RequestParam String expectedTime, HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        try {
            RepairBill bill = repairBillManager.get(id);
            if (!bill.getStatus().equals(CodeConstants.IN_PROGRESS)) {
                return AppResultUtil.createErrorDto(AppConstants.PEND_BILL_ERROR, "挂单失败，该单不是可挂单状态");
            }
            User user = userManager.getUserByUsername2(userName);
            bill.setStatus(CodeConstants.IN);//抢单成功设置状态为挂单中
            repairBillManager.updateModel(bill);
            RepairOperateRecord operateRecord = new RepairOperateRecord(id, user.getId(), userName, new Date());
            operateRecord.setOperateType(CodeConstants.PENDING);
            operateRecord.setDescription(description);
            String pendReason = "";
            String[] reStrings = reasonIds.split(",");
            for (String reasonId : reStrings) {
                Element e6 = elementGroupManager.getElementId(Long.parseLong(reasonId));
                pendReason += "," + e6.getItemname();
            }
            if (pendReason.length() > 0) {
                pendReason = pendReason.substring(1);
            }
            operateRecord.setDetail(user.getFullName() + "挂单;挂单原因：" + pendReason);
            operateRecord.setExpectedTime(expectedTime);
            operateRecord.setPendBillReason(reasonIds);
            repairOperateRecordManager.saveModel(operateRecord);

            return AppResultUtil.createSuccesDto();
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.PEND_ERROR, "挂单失败");
        }
    }

    /**
     * 取消挂单
     */
    @RequestMapping(value = "/cancelPendBill")
    @ResponseBody
    public AppResultDto cancelPendBill(@RequestParam Long id, HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        try {
            User user = userManager.getUserByUsername2(userName);
            RepairBill bill = repairBillManager.get(id);
            bill.setStatus(CodeConstants.IN_PROGRESS);//取消挂单设置状态为进行中
            repairBillManager.updateModel(bill);
            RepairOperateRecord operateRecord = new RepairOperateRecord(id, user.getId(), userName, new Date());
            operateRecord.setOperateType(CodeConstants.CANCLE_PENDING);
            operateRecord.setDetail(user.getFullName() + "取消挂单");
            repairOperateRecordManager.saveModel(operateRecord);
            return AppResultUtil.createSuccesDto();
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.CANCEL_PEND_ERROR, "取消挂单失败");
        }
    }

    /**
     * 派单
     */
    @RequestMapping(value = "/sendBill")
    @ResponseBody
    public AppResultDto sendBill(@RequestParam("id") Long id, @RequestParam("receiverId") String receiverId, HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        try {
            RepairBill bill = repairBillManager.get(id);
            //状态 TODO
            if (!bill.getStatus().equals(CodeConstants.IN_PROGRESS) && !bill.getStatus().equals(CodeConstants.IS_SINGLE)
                    && !bill.getStatus().equals(CodeConstants.IN) && !bill.getStatus().equals(CodeConstants.TO_SEND)) {
                return AppResultUtil.createErrorDto(AppConstants.SEND_BILL_ERROR, "派单失败，该单不是可派单状态");
            }
            String[] users = receiverId.split(",");
            if (users.length == 0) {
                return AppResultUtil.createErrorDto(AppConstants.SEND_ERROR, "请选择维修工程师！");
            }
            RepairConfig s_con = repairConfigManager.getByOrgId(bill.getOrgId());
            if (s_con == null) {
                s_con = new RepairConfig();
                s_con.setIspay((byte) 1);
                s_con.setIspersons((byte) 2);
                s_con.setMax_bills(3);
                s_con.setRepair_type(1);
            }
            if (users.length > 1) {
                //一单多人判断

                if (s_con.getIspersons() == 2 || s_con.getRepair_type() == 1) {
                    return AppResultUtil.createErrorDto(AppConstants.SEND_ERROR, "本项目不可派给多个工程师！");
                }
            }
            //判断是否超过接单数量
            for (int i = 0; i < users.length; i++) {
                Integer c = repairBillManager.findCountBy(CodeConstants.IN_PROGRESS, null, Long.parseLong(users[i]), null);
                if (c >= s_con.getMax_bills()) {
                    User user = userManager.get(Long.parseLong(users[i]));
                    return AppResultUtil.createErrorDto(AppConstants.SEND_ERROR, user.getFullName() + " 进行中的工单数量超过 " + s_con.getMax_bills() + " ，请重新选择工程师！");
                }
            }
            bill.setConfirmStatus(1); //待确认
            bill.setStatus(CodeConstants.IN_PROGRESS);//派单成功设置状态为进行中
            bill.setServiceUser(receiverId);
            if(null == bill.getSingleTime()){
                bill.setSingleTime(new Date()); //抢单时间
            }
            repairBillManager.updateModel(bill);

            User user1 = userManager.getUserByUsername2(userName);
            for (int i = 0; i < users.length; i++) {
                User user = userManager.get(Long.parseLong(users[i]));
                RepairOperateRecord operateRecord = new RepairOperateRecord(id, user1.getId(), userName, new Date());
                operateRecord.setOperateType(CodeConstants.TRANSFER);
                operateRecord.setIsConfirm(0); //只有派单需要 确认
                operateRecord.setDetail(user1.getFullName() + "派单给" + user.getFullName());
                repairOperateRecordManager.saveModel(operateRecord);
                String title = "有维修单已派给你，请查看";
                String content = repairBillService.getPushContent(bill);
                repairBillService.pushMessage(bill.getId(), CodeConstants.COMMON_PUSH_CODE, title, content, Arrays.asList(user));
            }

            return AppResultUtil.createSuccesDto();
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.SEND_ERROR, "派单失败");
        }
    }


    /**
     * 不支付
     */
    @RequestMapping(value = "/noPay")
    @ResponseBody
    public AppResultDto noPay(@RequestParam("id") Long id, HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        RepairBill bill = repairBillManager.get(id);
        bill.setHasPaid(2);
        bill.setRepairCost(new BigDecimal(0));
        repairBillManager.updateModel(bill);
        return AppResultUtil.createSuccesDto();
    }

    /**
     * 完成
     */
    @RequestMapping(value = "/completeBill")
    @ResponseBody
    public AppResultDto completeBill(@RequestParam("id") Long id,HttpServletRequest request) {


        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        try {

            String completeDesc = request.getParameter("completeDesc");

            RepairBill bill = repairBillManager.get(id);
            //状态 TODO
            if (!bill.getStatus().equals(CodeConstants.IN_PROGRESS)) {
                return AppResultUtil.createErrorDto(AppConstants.COMPLETE_BILL_ERROR, "完成失败，该单不是进行中状态");
            }
            User user = userManager.getUserByUsername2(userName);
            bill.setStatus(CodeConstants.COMPLETED);//完成成功设置状态为完成
            bill.setEndTime(new Date());//表示单已经完结


            //完成订单增加两个字段
            bill.setCompleteDesc(completeDesc);

            if (request instanceof MultipartHttpServletRequest){

                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

                String           completePhotoUrl     = "";
                Iterator<String> fileNames  = multiRequest.getFileNames();
                while (fileNames.hasNext()) {
                    MultipartFile multipartFile = multiRequest.getFile(fileNames.next());

                    //获得文件原始名称
                    InputStream stream   = null;
                    String      fileExt  = null;
                    String      fileName = "";
                    if (multipartFile != null) {
                        stream = multipartFile.getInputStream();
                        fileName = multipartFile.getOriginalFilename();
                        fileName = new String(fileName.getBytes(), "utf-8");
                        fileExt = StringUtils.isNotEmpty(fileName) ? fileName
                                .substring(fileName.lastIndexOf("."))
                                : StringUtils.EMPTY;
                    }

                    FileUploadUtils fileUploadUtils = new FileUploadUtils();
                    fileUploadUtils.init();
                    String url = fileUploadUtils.uploadFile(stream, fileExt);
                    completePhotoUrl += ";" + fileUploadUtils.fullVisitPath(url);
                }
                if (completePhotoUrl.length() > 1) {
                    bill.setCompletePhotoUrl(completePhotoUrl.substring(1));
                }

            }


            repairBillManager.updateModel(bill);
            RepairOperateRecord operateRecord = new RepairOperateRecord(id, user.getId(), userName, new Date());
            operateRecord.setOperateType(CodeConstants.COMPLETE);
            operateRecord.setDetail(user.getFullName() + "完成单");
            repairOperateRecordManager.saveModel(operateRecord);
            //http://wx.palmnest.com/wechat/dist/index.html?id=45#/Evaluate
            String host = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
            String wxCommentUrl = PropertiesKit.readPropertiesValue("wxCommentUrl", "wechat.properties");
            String commentUrl = host + wxCommentUrl.replaceAll("@id", bill.getId().toString());
            if (bill.getBillFrom().intValue() == 2) {
                repairBillService.pushWechatTemplateMsg(bill, 3);
            }
            return AppResultUtil.createSuccesDto(commentUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.COMPLETE_BILL_ERROR, "完成单失败");
        }
    }

    @RequestMapping(value = "/getSupportUser")
    @ResponseBody
    public AppResultDto getSupportUser(@RequestParam("id") Long id) {
        try {
            RepairSupportUserDto dto = new RepairSupportUserDto();
            RepairBill bill = repairBillManager.get(id);
            Set<User> users = bill.getSupportUsers();
            List<CommonDto> dtos = new ArrayList<CommonDto>();
            for (User user : users) {
                dtos.add(new CommonDto(user.getId(), user.getFullName()));
            }
            dto.setSupportUsers(dtos);
            List<CommonDto> repairUsers = repairBillService.findByTypeId(bill.getRepairType(), bill.getOrgId());
            repairUsers.removeAll(dtos);
            dto.setRepairUsers(repairUsers);
            return AppResultUtil.createSuccesDto(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.GET_SUPPORT_ERROR, "获取协办人失败");
        }
    }

    @RequestMapping(value = "/addSupportUser")
    @ResponseBody
    public AppResultDto addSupportUser(@RequestParam("id") Long id, @RequestParam("supportUserIds") String supportUserIds, HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        try {
            String[] ids = supportUserIds.split(",");
            Set<User> users = new HashSet<User>();
            for (String uid : ids) {
                users.add(userManager.getUser(uid));
            }
            RepairBill bill = repairBillManager.get(id);
            bill.setSupportUsers(users);
            repairBillManager.updateModel(bill);
            return AppResultUtil.createSuccesDto("");
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.ADD_SUPPORT_ERROR, "添加协办人失败");
        }
    }

    /**
     * 获取耗材列表
     *
     * @param orgId
     * @param request
     * @return
     */
    @RequestMapping(value = "/getMaterialList")
    @ResponseBody
    public AppResultDto getMaterialList(
            @RequestParam(value = "orgId") Integer orgId, HttpServletRequest request) {
        try {
            List<Map<String, Object>> reuslt = new ArrayList<>();
//            User user = (User) request.getSession().getAttribute("UserCache");
            List<RepairMaterial> repairMaterialList = repairMaterialManager.getMaterialListByOrgId(orgId);

            if (null != repairMaterialList && repairMaterialList.size() > 0) {
                for (RepairMaterial repairMaterial :
                        repairMaterialList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", repairMaterial.getId());
                    map.put("materialName", repairMaterial.getMaterialName());
                    reuslt.add(map);
                }
            }

            return AppResultUtil.createSuccesDto(reuslt);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.GET_MATERIAL_ERROR, "查询耗材失败");
        }
    }

    /**
     * @param orgId
     * @param request
     * @return
     */
    @RequestMapping(value = "/getAddressList")
    @ResponseBody
    public AppResultDto getAddressList(
            @RequestParam(value = "orgId") Integer orgId, HttpServletRequest request) {
        try {
            List<Map<String, Object>> reuslt = new ArrayList<>();
//            User user = (User) request.getSession().getAttribute("UserCache");
            List<RepairAddress> repairAddresses = repairAddressManager.getListByOrgId(orgId);

            if (null != repairAddresses && repairAddresses.size() > 0) {
                for (RepairAddress repairAddress :
                        repairAddresses) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", repairAddress.getId());
                    map.put("address", repairAddress.getAddress());
                    reuslt.add(map);
                }
            }

            return AppResultUtil.createSuccesDto(reuslt);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.GET_MATERIAL_ERROR, "查询耗材失败");
        }
    }

    /**
     * 获取耗材
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getMaterial")
    @ResponseBody
    public AppResultDto getMaterial(@RequestParam("id") Long id) {
        try {
            List<RepairBillMaterial> list = repairBillMaterialManager.findBy(id);
            return AppResultUtil.createSuccesDto(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.GET_MATERIAL_ERROR, "获取耗材失败");
        }
    }

    /**
     * 新增耗材
     *
     * @param id
     * @param materialName
     * @param amount
     * @return
     */
    @RequestMapping(value = "/addMaterial")
    @ResponseBody
    public AppResultDto addMaterial(@RequestParam("id") Long id, @RequestParam(value = "materialsId", required = false) Long materialsId, String materialName, Integer amount) {
        try {
            if(null != materialsId){
                RepairMaterial repairMaterial = repairMaterialManager.get(materialsId);
                if (null != repairMaterial) {
                    materialName = repairMaterial.getMaterialName();
                }
            }
            RepairBillMaterial material = new RepairBillMaterial(id, materialsId, materialName, amount);
            repairBillMaterialManager.saveModel(material);
            List<RepairBillMaterial> list = repairBillMaterialManager.findBy(id);

            return AppResultUtil.createSuccesDto(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.ADD_MATERIAL_ERROR, "添加耗材失败");
        }
    }

    @RequestMapping(value = "/deleteMaterial")
    @ResponseBody
    public AppResultDto deleteMaterial(@RequestParam("id") Long id, @RequestParam("billId") Long billId) {
        try {
            repairBillMaterialManager.remove(id);
            List<RepairBillMaterial> list = repairBillMaterialManager.findBy(billId);
            return AppResultUtil.createSuccesDto(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.DELETE_MATERIAL_ERROR, "删除耗材失败");
        }
    }

    /**
     * 审核
     */
    @RequestMapping(value = "/auditBill")
    @ResponseBody
    public AppResultDto auditBill(@RequestParam("id") Long id, Integer operateType, HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        try {
            RepairBill bill = repairBillManager.get(id);
            //状态 TODO
            if (!bill.getStatus().equals(CodeConstants.TO_AUDIT)) {
                return AppResultUtil.createErrorDto(AppConstants.AUDIT_BILL_ERROR, "审核失败，该单不是可审核状态");
            }
            User user = userManager.getUserByUsername2(userName);
            repairBillService.audit(id, operateType, user);
            repairBillService.auditPush(operateType, bill);
            return AppResultUtil.createSuccesDto();
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.AUDIT_BILL_ERROR, "审核失败");
        }
    }


    @RequestMapping("/getWeiXinPayCode")
    @ResponseBody
    public AppResultDto getWeiXinPayCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            WXConfig config = new WXConfig();
            WXPay wxPay = new WXPay(config);
            //金额
            BigDecimal money = new BigDecimal(request.getParameter("money")).multiply(new BigDecimal(100));
            //订单号
            RepairBill bill = repairBillManager.get(Long.parseLong(request.getParameter("id")));
            Map<String, String> data = new HashMap<String, String>();
            data.put("body", "维修单收款");
            data.put("out_trade_no", bill.getCode() + "-" + String.valueOf(money.intValue()));
            //data.put("device_info", "");
            data.put("fee_type", "CNY");
            data.put("total_fee", String.valueOf(money.intValue()));
            data.put("spbill_create_ip", "127.0.0.1");
            data.put("notify_url", webUrl + payNotifyAction);//异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数。
            data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
            data.put("product_id", bill.getId().toString());
            String sign = WXPayUtil.generateSignature(data, config.getKey(), SignType.MD5);
            System.out.println(sign);
            System.out.println(config.getAppID());
            System.out.println(config.getMchID());
            System.out.println(config.getKey());
            //boolean isSign = wxPay.isPayResultNotifySignatureValid(data);
            //System.out.println(isSign);
            Map<String, String> resp = wxPay.unifiedOrder(data);
            System.out.println(resp);
            if ("SUCCESS".equals(resp.get("result_code"))) {
                bill.setRepairCost(new BigDecimal(request.getParameter("money")));
                repairBillManager.updateModel(bill);
                return AppResultUtil.createSuccesDto(resp.get("code_url"));
            } else {
                return AppResultUtil.createErrorDto(AppConstants.PAY_CODE_URL_ERROR, resp.get("err_code_des"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.PAY_CODE_URL_ERROR, "生成支付码失败");
        }
    }


    /**
     * 工程维修首页脚标数量
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/indexTotal")
    @ResponseBody
    public AppResultDto indexTotal(HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        try {
            return AppResultUtil.createSuccesDto(repairBillService.findBy(userName));
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.REPAIR_INDEX_ERROR, "工程维修首页脚标查询失败");
        }
    }


    /**
     * 获得派单用户数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getSendUserData")
    @ResponseBody
    public AppResultDto getSendUserData(HttpServletRequest request) {
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        try {
            return AppResultUtil.createSuccesDto(repairBillService.getSendUserData(userName));
        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.REPAIR_INDEX_ERROR, "获得派单用户数据失败");
        }
    }


    /**
     * 修改派单用户数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateSendUserData")
    @ResponseBody
    public AppResultDto updateSendUserData(HttpServletRequest request) {

        String sendBillIds = request.getParameter("sendBillIds");
        if(StringUtils.isEmpty(sendBillIds)){
            return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "参数错误");
        }

        try {
            Integer count = repairBillManager.updateSendUserData(sendBillIds);
            if(count > 0){
                return AppResultUtil.createSuccesDto("");
            }else{
                return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "更新失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "修改派单用户数据失败");
        }
    }

    /**
     * 维修单是否支付判断
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/hasPaid")
    @ResponseBody
    public AppResultDto hasPaid(Long id) {
        RepairBill bill = repairBillManager.get(id);
        if (bill.getHasPaid() != null && bill.getHasPaid().intValue() == 2) {
            return AppResultUtil.createSuccesDto(200);
        } else {
            return AppResultUtil.createSuccesDto(-1);
        }
    }

    //add dz 1029

    /**
     * @param request
     * @return 查找维修单对应维修类型下的人员
     */
    @RequestMapping(value = "/getconfig")
    @ResponseBody
    public AppResultDto getconfig(@RequestParam("org_id") Integer org_id, HttpServletRequest request) {
        RepairConfig s_con = repairConfigManager.getByOrgId(org_id);
        Integer repairMode;//1-抢单模式 2-派单模式 0-无模式
        Integer repairPersons;//1-开启一单多人 2-关闭一单多人
        Integer repairPay;

        Integer isCompleteDesc ;     //完成描述 1-选填 2-必填 3-不展示
        Integer isCompletePhoto ;	  //完成照片 1-选填 2-必填 3-不展示
        Integer isDeliveryConfirm;  //派单确认 0-关闭 1-开启


        if (s_con != null) {
            repairMode = (s_con.getRepair_type());
            repairPersons = (s_con.getIspersons().intValue());
            repairPay = (s_con.getIspay() == 1 ? 1 : 0);

            isCompleteDesc = (s_con.getIsCompleteDesc());
            isCompletePhoto = (s_con.getIsCompletePhoto());
            isDeliveryConfirm = (s_con.getIsDeliveryConfirm());

        } else {
            repairMode = (1);
            repairPersons = (2);
            repairPay = (1);

            isCompleteDesc = (1);
            isCompletePhoto = (1);
            isDeliveryConfirm = (0);
        }
        Map<String, Object> resMap = new HashMap<String, Object>();

        resMap.put("repairMode", repairMode);
        resMap.put("repairPersons", repairPersons);
        resMap.put("repairPay", repairPay);


        resMap.put("isCompleteDesc", isCompleteDesc);
        resMap.put("isCompletePhoto", isCompletePhoto);
        resMap.put("isDeliveryConfirm", isDeliveryConfirm);

        return AppResultUtil.createSuccesDto(resMap);
    }
}
