package com.ghy.web.controller.order;

import cn.hutool.db.sql.Order;
import com.alibaba.fastjson.JSONObject;
import com.ghy.common.adapay.model.AdapayStatusEnum;
import com.ghy.common.adapay.model.PayParam;
import com.ghy.common.annotation.Log;
import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.domain.entity.SysUser;
import com.ghy.common.core.page.PageDomain;
import com.ghy.common.core.page.TableDataInfo;
import com.ghy.common.core.page.TableSupport;
import com.ghy.common.enums.*;
import com.ghy.common.utils.*;
import com.ghy.common.utils.poi.ExcelUtil;
import com.ghy.customer.domain.Customer;
import com.ghy.customer.domain.CustomerAddress;
import com.ghy.customer.service.CustomerAddressService;
import com.ghy.customer.service.CustomerService;
import com.ghy.goods.domain.*;
import com.ghy.goods.service.*;
import com.ghy.order.domain.*;
import com.ghy.order.service.*;
import com.ghy.payment.domain.FinancialChangeRecord;
import com.ghy.payment.domain.FinancialDetail;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.domain.PaymentRelation;
import com.ghy.payment.service.FinancialChangeRecordService;
import com.ghy.payment.service.FinancialDetailService;
import com.ghy.payment.service.FinancialMasterService;
import com.ghy.payment.service.OrderFineRecordService;
import com.ghy.system.domain.SysArea;
import com.ghy.system.service.ISysAreaService;
import com.ghy.web.pojo.vo.OrderListResponse;
import com.ghy.web.pojo.vo.OrderMasterResponseVo;
import com.ghy.web.pojo.vo.OrderStandard;
import com.ghy.web.pojo.vo.OrderStandardDetail;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.domain.WorkerCertification;
import com.ghy.worker.service.IWorkerCertificationService;
import com.ghy.worker.service.WorkerService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 主订单API
 *
 * @author HH 2022/4/25
 */
@Controller
@RequestMapping("/order/master")
public class OrderMasterController extends BaseController {

    private final String prefix = "order/master";

    @Resource
    private OrderMasterService orderMasterService;
    @Resource
    private GoodsAreaService goodsAreaService;
    @Resource
    private WorkerService workerService;
    @Resource
    private IWorkerCertificationService workerCertificationService;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private CustomerAddressService addressService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private GoodsImgsService goodsImgsService;
    @Resource
    private DeptGoodsCategoryService deptGoodsCategoryService;
    @Resource
    private GoodsCategoryService goodsCategoryService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private IOrderCallRecordService orderCallRecordService;

    @Resource
    private FinancialMasterService financialMasterService;
    @Resource
    private FinancialDetailService financialDetailService;
    @Resource
    private GoodsStandardService goodsStandardService;
    @Resource
    private OrderFineRecordService orderFineRecordService;
    @Resource
    private ISysAreaService sysAreaService;
    @Resource
    private IAfterServiceRecordService afterServiceRecordService;
    @Resource
    private FinancialChangeRecordService financialChangeRecordService;


//    @RequiresPermissions("order:master:view")
    @GetMapping()
    public String orderMaster() {
        return prefix;
    }

    @PostMapping("/changeIsCharge")
    @ResponseBody
    public AjaxResult changeIsCharge(OrderMaster orderMaster)
    {
        return toAjax(orderMasterService.updateOrderMaster(orderMaster));
    }

    @PostMapping("/changeIsContact")
    @ResponseBody
    public AjaxResult changeIsContact(OrderMaster orderMaster)
    {
        return toAjax(orderMasterService.updateOrderMaster(orderMaster));
    }

    /**
     * 修改详细订单
     */
    @GetMapping("/payQrcode/{orderId}")
    public String payQrcode(@PathVariable("orderId") String orderId, ModelMap mmap) {
        mmap.put("orderId", orderId);
        return "order/master-qrcode";
    }

    @GetMapping("/pc")
    public String orderPcMaster() {
        return "order/pc-master";
    }

    @GetMapping("/manager")
    public String orderManager() {
        return "order/orderManager";
    }

    @GetMapping("/pcOrderWorker/{orderIds}")
    public String addMasterQrPay(@PathVariable(value = "orderIds") String orderIds, ModelMap mmap) {
        // 不知道为啥参数可能会带上双引号 这里去掉再转Long
        orderIds = orderIds.replace("\"", "");
        List<Worker> workList = workerService.getWorkList(new Worker());
        mmap.put("orderIds", orderIds);
        mmap.put("workers", workList);
        return "order/pcOrderWorker";
    }

    @PostMapping("/assign")
    @ResponseBody
    public AjaxResult assign(@RequestBody OrderMaster orderMaster){
        OrderMaster param = new OrderMaster();
        param.setOrderMasterIds(orderMaster.getOrderMasterIds());
        List<OrderMaster> masters = orderMasterService.selectOrderMasterList(param);
        long count = masters.stream().filter(x->!x.getOrderStatus().equals(OrderStatus.RECEIVE.code())|| x.getWorkerId() != null).count();
        if(count > 0){
            return AjaxResult.error("请选择待接单且无师傅接单订单指派");
        }
        masters.forEach(master->{
            OrderMaster updateEntity = new OrderMaster();
            updateEntity.setId(master.getId());
            updateEntity.setWorkerId(orderMaster.getWorkerId());
            orderMasterService.updateOrderMaster(updateEntity);
            // 推送公众号通知数据。
            try {
                Worker assignWorker = workerService.selectById(orderMaster.getWorkerId());
                // 消息组装。
                Map<String, Object> params = new HashMap<>();
                // 订单编号
                params.put("character_string6", master.getCode());
                // 名称
                params.put("thing14", "收到新订单");
                // 预约时间
                params.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", master.getExpectTimeStart()));
                // 消息推送
                WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), assignWorker.getWxOpenId(), WxMsgEnum.TEXT, params);
            } catch (Exception e) {
                // 暂时不做任何操作。
                logger.error(e.getMessage(), e);
            }

        });
        return AjaxResult.success();
    }

    @GetMapping("/orderWorker/{orderId}")
    public String orderWorker(@PathVariable("orderId") Long orderId, ModelMap mmap) {
        List<Worker> workList = workerService.getWorkList(new Worker());
        mmap.put("orderId", orderId);
        mmap.put("workers", workList);
        return "order/orderWorker";
    }

    @GetMapping("/assignWholeOrder/{orderId}")
    public String assignWholeOrder(@PathVariable("orderId") Long orderId, ModelMap mmap) {
        mmap.put("orderId", orderId);
        return "order/assignWholeOrder";
    }

    @PostMapping("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestBody OrderMaster orderMaster) {
//        TableDataInfo rspData = new TableDataInfo();
        List<OrderListResponse> orderListResponses = new ArrayList<>();
        // 入参中的城市id存在时，查询符合条件的地址id
        if (CollectionUtils.isNotEmpty(orderMaster.getDistrictIds())
                || CollectionUtils.isNotEmpty(orderMaster.getCityIds())
                || CollectionUtils.isNotEmpty(orderMaster.getStreetIds())) {

            CustomerAddress customerAddress = new CustomerAddress();
            customerAddress.setDistrictIds(orderMaster.getDistrictIds());
            customerAddress.setCityIds(orderMaster.getCityIds());
            customerAddress.setStreetIds(orderMaster.getStreetIds());
            customerAddress.setNeedNameFlag(true);
            List<CustomerAddress> addressList = addressService.getCustomerAddressList(customerAddress);
            orderMaster.setAddressIds(addressList.stream().map(CustomerAddress::getCustomerAddressId).collect(Collectors.toList()));
            if (CollectionUtils.isEmpty(orderMaster.getAddressIds())) {
                return voDataTable(orderListResponses, new ArrayList<>());
            }
        }
        startPage();
        List<OrderMaster> list = orderMasterService.selectOrderMasterList(orderMaster);
        list.forEach(master -> {
            //子单
            List<OrderDetail> detailList = orderDetailService.selectByOrderMasterId(master.getId());

            // 初始化属性
            OrderListResponse orderListResponse = new OrderListResponse();
            List<OrderStandard> standardList = new ArrayList<>();

            // 师傅信息
            Worker worker = master.getWorkerId() != null ? workerService.selectById(master.getWorkerId()) : null;

            // 消费者信息
//            Customer customer = customerService.selectByCustomerId(master.getCustomerId());

            // 商品规格及信息
            List<OrderGoods> orderStandardList = orderGoodsService.selectByOrderMasterId(master.getId());

            // 商品信息
            GoodsStandard goodsStandard = goodsStandardService.selectById(orderStandardList.get(0).getGoodsStandardId());

            Goods goods = goodsService.selectById(goodsStandard.getGoodsId());

            // 财务信息
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(master.getId());
            BigDecimal totalPayMoney = financialMaster.getPayMoney();
            BigDecimal totalChangeMoney = new BigDecimal(0);
            for (OrderDetail detail : detailList) {
                // 查询子单加价记录
                FinancialChangeRecord record = financialChangeRecordService.selectNotPayRecordByDetailId(detail.getId());
                if (record != null) {
                    totalChangeMoney = totalChangeMoney.add(record.getChangeMoney());
                }
            }

            // 地址信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(master.getAddressId());
            SysArea sysArea = sysAreaService.selectById(customerAddress.getCountryId());
            String completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();

            // 查询售后记录
            List<AfterServiceRecord> afterServiceRecords = new ArrayList<>();
            List<OrderDetail> detailOrderList = orderDetailService.selectByOrderMasterId(master.getId());
            detailOrderList.forEach(detail -> {
                AfterServiceRecord afterServiceRecordQry = new AfterServiceRecord();
                afterServiceRecordQry.setOrderDetailId(detail.getId());
                List<AfterServiceRecord> records = afterServiceRecordService.selectAfterServiceRecordList(afterServiceRecordQry);
                afterServiceRecords.addAll(records);
            });

            for (OrderGoods orderGoods : orderStandardList) {
                OrderStandard orderStandard = new OrderStandard();
                orderStandard.setStandardName(orderGoods.getGoodsName());
                orderStandard.setStandardNum(orderGoods.getGoodsNum());
                standardList.add(orderStandard);
            }

            // 编辑返回属性
            orderListResponse.setOrderMasterId(master.getId());
            orderListResponse.setGoodsName(goods.getGoodsName());
            orderListResponse.setGoodsLogoUrl(goods.getGoodsImgUrl());
            orderListResponse.setDiscountMoney(financialMaster.getDiscountMoney());
            orderListResponse.setTotalMoney(financialMaster.getTotalMoney());
            orderListResponse.setPayMoney(totalPayMoney);
            orderListResponse.setChangeMoney(totalChangeMoney);
            orderListResponse.setWorkerName(worker == null ? "" : worker.getName());
            orderListResponse.setWorkerPhone(worker == null ? "" : worker.getPhone());
            orderListResponse.setCustomerName(customerAddress.getName());
            orderListResponse.setCustomerPhone(customerAddress.getPhone());
            orderListResponse.setServerTime(master.getRevTime());
            orderListResponse.setExpectTimeStart(master.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(master.getExpectTimeEnd());
            orderListResponse.setExpectTimeStartFront(master.getExpectTimeStart());
            orderListResponse.setExpectTimeEndFront(master.getExpectTimeEnd());
            orderListResponse.setOrderStatus(master.getOrderStatus());
            orderListResponse.setPayStatus(financialMaster.getPayStatus());
            orderListResponse.setPayType(master.getPayType());
            orderListResponse.setOrderMasterCode(master.getCode());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(completeAddress);
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(master.getRemark());
            orderListResponse.setTimeout(master.getTimeout());
            orderListResponse.setTimeoutFineTimes(master.getTimeoutFineTimes());
            orderListResponse.setAfterServiceRecordList(afterServiceRecords);
            orderListResponse.setServerMoney(master.getServerMoney());
            orderListResponse.setIsCall(master.getIsCall());
            orderListResponses.add(orderListResponse);

        });

//        PageDomain pageDomain = TableSupport.buildPageRequest();
//        if (null == pageDomain.getPageNum() || null == pageDomain.getPageSize()) {
//            rspData.setRows(orderListResponses);
//            rspData.setTotal(orderListResponses.size());
//            return rspData;
//        }
//        Integer pageSize = pageDomain.getPageNum();
//        if (pageSize > orderListResponses.size()) {
//            pageSize = orderListResponses.size();
//        }
//        rspData.setRows(orderListResponses.subList(0, pageSize));
//        rspData.setTotal(orderListResponses.size());
        return voDataTable(orderListResponses, list);
    }

    @PostMapping("/app/count")
    @ResponseBody
    public AjaxResult countAppList(@RequestBody OrderMaster orderMaster) {
        return AjaxResult.success(orderMasterService.countOrderMasterList(orderMaster));
    }

    @PostMapping("/after/list")
    @ResponseBody
    public TableDataInfo afterList(@RequestBody OrderMaster orderMaster) {

        // 查所有售后的单
        AfterServiceRecord afterServiceRecord = new AfterServiceRecord();
        afterServiceRecord.setExcludeAfterServiceFinished(Boolean.TRUE);
        List<AfterServiceRecord> afterServiceRecordList = afterServiceRecordService.selectAfterServiceRecordList(afterServiceRecord);
        // 踢重后的子单ids
        List<Long> detailIds = afterServiceRecordList.stream().map(AfterServiceRecord::getOrderDetailId).distinct().collect(Collectors.toList());
        StringBuilder orderDetailIds = new StringBuilder();
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setCustomerId(orderMaster.getCustomerId());
        orderDetail.setDeptId(orderMaster.getDeptId());
        detailIds.forEach(id -> {
            orderDetailIds.append(id).append(",");
        });
        String ids = orderDetailIds.toString();
        if (StringUtils.isNotEmpty(ids)) {
            orderDetail.setOrderDetailIds(ids.substring(0, ids.length() - 1));
        } else {
            orderDetail.setOrderDetailIds("0");
        }
        // 所有售后的子单
        List<OrderDetail> orderDetailList = orderDetailService.selectOrderDetailList(orderDetail);
        StringBuilder orderMasterIds = new StringBuilder();
        orderDetailList.stream().map(OrderDetail::getOrderMasterId).distinct()
                .collect(Collectors.toList()).forEach(id -> {
            orderMasterIds.append(id).append(",");
        });
        String orderIds = orderMasterIds.toString();
        if (StringUtils.isNotEmpty(orderIds)) {
            orderMaster.setOrderMasterIds(orderIds.substring(0, orderIds.length() - 1));
        } else {
            orderMaster.setOrderMasterIds("0");
        }

        startPage();
        List<OrderListResponse> orderListResponses = new ArrayList<>();
        List<OrderMaster> list = orderMasterService.selectOrderMasterList(orderMaster);
        list.forEach(master -> {
            //子单
//            List<OrderDetail> detailList = orderDetailService.selectByOrderMasterId(master.getId());

            // 初始化属性
            OrderListResponse orderListResponse = new OrderListResponse();
            List<OrderStandard> standardList = new ArrayList<>();

            // 师傅信息
            Worker worker = master.getWorkerId() != null ? workerService.selectById(master.getWorkerId()) : null;

            // 消费者信息
//            Customer customer = customerService.selectByCustomerId(master.getCustomerId());

            // 商品规格及信息
            List<OrderGoods> orderStandardList = orderGoodsService.selectByOrderMasterId(master.getId());

            // 商品信息
            GoodsStandard goodsStandard = goodsStandardService.selectById(orderStandardList.get(0).getGoodsStandardId());

            Goods goods = goodsService.selectById(goodsStandard.getGoodsId());

            // 财务信息
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(master.getId());
            BigDecimal totalPayMoney = financialMaster.getPayMoney();
//            BigDecimal totalChangeMoney = new BigDecimal(0);
//            for (OrderDetail detail: detailList) {
//                // 查询子单加价记录
//                FinancialChangeRecord changeRecordQry = new FinancialChangeRecord();
//                changeRecordQry.setOrderDetailId(detail.getId());
//                List<FinancialChangeRecord> financialChangeRecords = financialChangeRecordService.selectFinancialChangeRecordList(changeRecordQry);
//                if (CollectionUtils.isNotEmpty(financialChangeRecords)) {
//                    totalChangeMoney = totalChangeMoney.add(financialChangeRecords.get(0).getChangeMoney());
//                }
//            }
//            totalPayMoney = totalPayMoney.add(totalChangeMoney);

            // 地址信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(master.getAddressId());
            SysArea sysArea = sysAreaService.selectById(customerAddress.getCountryId());
            String completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();

            for (OrderGoods orderGoods : orderStandardList) {
                OrderStandard orderStandard = new OrderStandard();
                orderStandard.setStandardName(orderGoods.getGoodsName());
                orderStandard.setStandardNum(orderGoods.getGoodsNum());
                standardList.add(orderStandard);
            }

            // 编辑返回属性
            orderListResponse.setOrderMasterId(master.getId());
            orderListResponse.setGoods(goods);
            orderListResponse.setGoodsName(goods.getGoodsName());
            orderListResponse.setGoodsLogoUrl(goods.getGoodsImgUrl());
            orderListResponse.setDiscountMoney(financialMaster.getDiscountMoney());
            orderListResponse.setTotalMoney(financialMaster.getTotalMoney());
            orderListResponse.setPayMoney(totalPayMoney);
//            orderListResponse.setChangeMoney(totalChangeMoney);
            orderListResponse.setWorkerName(worker == null ? "" : worker.getName());
            orderListResponse.setWorkerPhone(worker == null ? "" : worker.getPhone());
            orderListResponse.setCustomerName(customerAddress.getName());
            orderListResponse.setCustomerPhone(customerAddress.getPhone());
            orderListResponse.setServerTime(master.getRevTime());
            orderListResponse.setExpectTimeStart(master.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(master.getExpectTimeEnd());
            orderListResponse.setExpectTimeStartFront(master.getExpectTimeStart());
            orderListResponse.setExpectTimeEndFront(master.getExpectTimeEnd());
            orderListResponse.setOrderStatus(master.getOrderStatus());
            orderListResponse.setPayStatus(master.getPayStatus());
            orderListResponse.setPayType(master.getPayType());
            orderListResponse.setOrderMasterCode(master.getCode());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(completeAddress);
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(master.getRemark());
            orderListResponse.setTimeout(master.getTimeout());
            orderListResponse.setTimeoutFineTimes(master.getTimeoutFineTimes());
            orderListResponses.add(orderListResponse);

        });

//        PageDomain pageDomain = TableSupport.buildPageRequest();
//        if (null == pageDomain.getPageNum() || null == pageDomain.getPageSize()) {
//            rspData.setRows(orderListResponses);
//            rspData.setTotal(orderListResponses.size());
//            return rspData;
//        }
//        Integer pageSize = pageDomain.getPageNum();
//        if (pageSize > orderListResponses.size()) {
//            pageSize = orderListResponses.size();
//        }
//        rspData.setRows(orderListResponses.subList(0, pageSize));
//        rspData.setTotal(orderListResponses.size());
        return voDataTable(orderListResponses, list);
    }

    @PostMapping("/after/count")
    @ResponseBody
    public AjaxResult countAfterList(@RequestBody OrderMaster orderMaster) {
        // 查所有售后的单
        AfterServiceRecord afterServiceRecord = new AfterServiceRecord();
        afterServiceRecord.setExcludeAfterServiceFinished(Boolean.TRUE);
        List<AfterServiceRecord> afterServiceRecordList = afterServiceRecordService.selectAfterServiceRecordList(afterServiceRecord);
        // 踢重后的子单ids
        List<Long> detailIds = afterServiceRecordList.stream().map(AfterServiceRecord::getOrderDetailId).distinct().collect(Collectors.toList());
        StringBuilder orderDetailIds = new StringBuilder();
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setCustomerId(orderMaster.getCustomerId());
        orderDetail.setDeptId(orderMaster.getDeptId());
        detailIds.forEach(id -> {
            orderDetailIds.append(id).append(",");
        });
        String ids = orderDetailIds.toString();
        if (StringUtils.isNotEmpty(ids)) {
            orderDetail.setOrderDetailIds(ids.substring(0, ids.length() - 1));
        } else {
            orderDetail.setOrderDetailIds("0");
        }
        // 所有售后的子单
        List<OrderDetail> orderDetailList = orderDetailService.selectOrderDetailList(orderDetail);
        StringBuilder orderMasterIds = new StringBuilder();
        orderDetailList.stream().map(OrderDetail::getOrderMasterId).distinct()
                .collect(Collectors.toList()).forEach(id -> {
            orderMasterIds.append(id).append(",");
        });
        String orderIds = orderMasterIds.toString();
        if (StringUtils.isNotEmpty(orderIds)) {
            orderMaster.setOrderMasterIds(orderIds.substring(0, orderIds.length() - 1));
        } else {
            orderMaster.setOrderMasterIds("0");
        }

        return AjaxResult.success(orderMasterService.countOrderMasterList(orderMaster));
    }

    @PostMapping("/app/detail")
    @ResponseBody
    public AjaxResult appDetail(@RequestBody OrderMaster request) {
        try {
            // 主单信息
            OrderMaster orderMaster = orderMasterService.selectById(request.getId());

            List<OrderDetail> orderDetailList = orderDetailService.selectByOrderMasterId(orderMaster.getId());
            List<OrderStandardDetail> orderStandardDetails = new ArrayList<>();

            // 财务信息
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(orderMaster.getId());
            // 计算总额
            BigDecimal totalPayMoney = financialMaster.getPayMoney();

            for (OrderDetail orderDetail : orderDetailList) {
                List<OrderStandard> standardList = new ArrayList<>();
                // 子单施工师傅信息
                Worker detailWorker = workerService.selectById(orderDetail.getWorkerId());
                // 师傅实名信息
                WorkerCertification detailWorkerRealInfo = workerCertificationService.selectByWorkerId(orderDetail.getWorkerId());

                // 子单商品规格及信息
                List<OrderGoods> orderStandardList = orderGoodsService.selectByOrderDetailId(orderDetail.getId());
                for (OrderGoods orderGoods : orderStandardList) {
                    OrderStandard orderStandard = new OrderStandard();
                    orderStandard.setStandardName(orderGoods.getGoodsName());
                    orderStandard.setStandardNum(orderGoods.getGoodsNum());
                    orderStandard.setServerNum(orderGoods.getServerGoodsNum() == null ? 0 : orderGoods.getServerGoodsNum());
                    orderStandard.setWaitServerNum(orderStandard.getStandardNum() - orderStandard.getServerNum());
                    standardList.add(orderStandard);
                }

                // 完工图片
                List<String> finishImgList = null;
                if (orderMaster.getOrderStatus() > 3) {
                    GoodsImgs qryImgsObj = new GoodsImgs();
                    qryImgsObj.setRemark(orderDetail.getId().toString());
                    qryImgsObj.setImgType(ImgType.FINISH_IMG.getId());
                    qryImgsObj.setGoodsId(0L);
                    List<GoodsImgs> goodsImgs = goodsImgsService.qryGoodsImgs(qryImgsObj);
                    finishImgList = goodsImgs.stream().map(GoodsImgs::getImgUrl).collect(Collectors.toList());
                }

                FinancialDetail financialDetail = financialDetailService.selectByOrderDetailId(orderDetail.getId());
                BigDecimal detailPayMoney = financialDetail.getPayMoney();
                // 查询子单加价记录
                FinancialChangeRecord changeRecordQry = new FinancialChangeRecord();
                changeRecordQry.setOrderDetailId(orderDetail.getId());
                List<FinancialChangeRecord> financialChangeRecords = financialChangeRecordService.selectFinancialChangeRecordList(changeRecordQry);
//                if (CollectionUtils.isNotEmpty(financialChangeRecords)) {
//                    financialChangeRecord = financialChangeRecords.get(0);
//                    totalPayMoney = totalPayMoney.add(financialChangeRecord.getChangeMoney());
//                    detailPayMoney = detailPayMoney.add(financialChangeRecord.getChangeMoney());
//                }

                OrderStandardDetail orderStandardDetail = new OrderStandardDetail();
                orderStandardDetail.setOrderDetailId(orderDetail.getId());
                orderStandardDetail.setOrderDetailCode(orderDetail.getCode());
                orderStandardDetail.setWorkBeginTime(orderDetail.getWorkBeginTime());
                orderStandardDetail.setWorkFinishTime(orderDetail.getWorkFinishTime());
                orderStandardDetail.setWorkerName(detailWorkerRealInfo != null ? detailWorkerRealInfo.getName() : detailWorker.getName());
                orderStandardDetail.setWorkerPhone(detailWorker.getPhone());
                orderStandardDetail.setRevTime(orderDetail.getRevTime());
                orderStandardDetail.setExpectTimeStart(orderDetail.getExpectTimeStart());
                orderStandardDetail.setExpectTimeEnd(orderDetail.getExpectTimeEnd());
                orderStandardDetail.setExpectTimeStartFront(orderDetail.getExpectTimeStart());
                orderStandardDetail.setExpectTimeEndFront(orderDetail.getExpectTimeEnd());
                orderStandardDetail.setOrderStandardList(standardList);
                orderStandardDetail.setFinishImgList(finishImgList);
                orderStandardDetail.setRemark(orderDetail.getRemark());
                orderStandardDetail.setPayMoney(detailPayMoney);
                orderStandardDetail.setFinancialChangeRecord(financialChangeRecords);
                orderStandardDetail.setOrderStatus(orderDetail.getOrderStatus());
                orderStandardDetail.setTimeout(orderDetail.getTimeout());
                orderStandardDetail.setTimeoutFineTimes(orderDetail.getTimeoutFineTimes());
                orderStandardDetail.setServerMoney(financialMaster.getServerMoney());
                AfterServiceRecord afterServiceRecord = new AfterServiceRecord();
                afterServiceRecord.setOrderDetailId(orderDetail.getId());
                List<AfterServiceRecord> records = afterServiceRecordService.selectAfterServiceRecordList(afterServiceRecord);
                orderStandardDetail.setAfterServiceRecordList(records);

                orderStandardDetail.setIsOnlyServ(this.checkIsOnlyServer(orderMaster.getId(), orderDetail.getWorkerId()) ? Boolean.TRUE : Boolean.FALSE);

                orderStandardDetail.setDrawCashStatus(orderDetail.getDrawCashStatus());
                orderStandardDetail.setDrawCashTime(orderDetail.getDrawCashTime());

                orderStandardDetails.add(orderStandardDetail);
            }

            // 初始化属性
            OrderListResponse orderListResponse = new OrderListResponse();
            List<OrderStandard> standardList = new ArrayList<>();

            // 师傅信息
            Worker worker = workerService.selectById(orderMaster.getWorkerId());

            WorkerCertification workerRealInfo = null;
            String workerName = "";
            if (worker != null) {
                // 师傅实名信息
                workerRealInfo = workerCertificationService.selectByWorkerId(orderMaster.getWorkerId());
                workerName = workerRealInfo == null ? worker.getName() : workerRealInfo.getName();
            }

            // 消费者信息
//            Customer customer = customerService.selectByCustomerId(orderMaster.getCustomerId());

            // 商品规格及信息
            List<OrderGoods> orderStandardList = orderGoodsService.selectByOrderMasterId(orderMaster.getId());

            // 商品信息
            GoodsStandard goodsStandard = goodsStandardService.selectById(orderStandardList.get(0).getGoodsStandardId());

            Goods goods = goodsService.selectById(goodsStandard.getGoodsId());
            // 补全商品服务区域
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(goods.getGoodsId());
            goods.setGoodsAreaList(goodsAreas);

            // 地址信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(orderMaster.getAddressId());
            SysArea sysArea = sysAreaService.selectById(customerAddress.getCountryId());
            String completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();

            for (OrderGoods orderGoods : orderStandardList) {
                OrderStandard orderStandard = new OrderStandard();
                orderStandard.setStandardName(orderGoods.getGoodsName());
                orderStandard.setStandardNum(orderGoods.getGoodsNum());
                orderStandard.setServerNum(orderGoods.getServerGoodsNum() == null ? 0 : orderGoods.getServerGoodsNum());
                orderStandard.setWaitServerNum(orderStandard.getStandardNum() - orderStandard.getServerNum());
                standardList.add(orderStandard);
            }

            // 查询主单师傅的最终收益
            FinancialDetail fdQry = new FinancialDetail();
            fdQry.setPayeeId(orderMaster.getWorkerId());
            fdQry.setFinancialMasterId(financialMaster.getId());
            List<FinancialDetail> financialDetailList = financialDetailService.selectFinancialDetailList(fdQry);
            BigDecimal finalRecvMoney = BigDecimal.ZERO;
            for (FinancialDetail financialDetail : financialDetailList) {
                finalRecvMoney = finalRecvMoney.add(financialDetail.getPayMoney());
            }

            // 编辑返回属性
            orderListResponse.setOrderMasterId(orderMaster.getId());
            orderListResponse.setOrderMasterCode(orderMaster.getCode());
            orderListResponse.setGoodsName(goods.getGoodsName());
            orderListResponse.setGoodsLogoUrl(goods.getGoodsImgUrl());
            orderListResponse.setDiscountMoney(financialMaster.getDiscountMoney());
            orderListResponse.setTotalMoney(financialMaster.getTotalMoney());
            orderListResponse.setPayMoney(totalPayMoney);
            orderListResponse.setWorkerName(workerName);
            orderListResponse.setWorkerPhone(worker == null ? "" : worker.getPhone());
            orderListResponse.setCustomerName(customerAddress.getName());
            orderListResponse.setCustomerPhone(customerAddress.getPhone());
            orderListResponse.setOrderStatus(orderMaster.getOrderStatus());
            orderListResponse.setPayStatus(orderMaster.getPayStatus());
            orderListResponse.setPayType(orderMaster.getPayType());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(completeAddress);
            orderListResponse.setServerTime(orderMaster.getRevTime());
            orderListResponse.setServerMoney(financialMaster.getServerMoney());
            orderListResponse.setExpectTimeStart(orderMaster.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(orderMaster.getExpectTimeEnd());
            orderListResponse.setExpectTimeStartFront(orderMaster.getExpectTimeStart());
            orderListResponse.setExpectTimeEndFront(orderMaster.getExpectTimeEnd());
            orderListResponse.setCreateTime(orderMaster.getCreateTime());
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(orderMaster.getRemark());
            orderListResponse.setOrderStandardDetailList(orderStandardDetails);
            orderListResponse.setTimeout(orderMaster.getTimeout());
            orderListResponse.setTimeoutFineTimes(orderMaster.getTimeoutFineTimes());
            orderListResponse.setFinalRecvMoney(finalRecvMoney);
            orderListResponse.setGoodsAreaList(goods.getGoodsAreaList());
            orderListResponse.setOrderMode(orderMaster.getOrderMode());
            orderListResponse.setIsCall(orderMaster.getIsCall());

            return AjaxResult.success(orderListResponse);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

//    @RequiresPermissions("order:master:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(OrderMaster orderMaster) {
        if (orderMaster.getSearchAfterList() !=null && orderMaster.getSearchAfterList()) {
            return this.afterList(orderMaster);
        }

        startPage();
        // 非管理员
        if (this.getSysUser().getRoles().get(0).getRoleId() != 1) {
            orderMaster.setDeptId(this.getSysUser().getDeptId());
        }
        // PC师傅
        if (this.getSysUser().getRoles().get(0).getRoleId() == 101L) {
            orderMaster.setCreateBy(this.getSysUser().getUserId().toString());
        }
        List<OrderMaster> orderMasterList = orderMasterService.selectOrderMasterList(orderMaster);
        Set<Long> orderMasterIds = orderMasterList.stream().map(OrderMaster::getId).collect(Collectors.toSet());

        Set<Long> customerIds = orderMasterList.stream().map(OrderMaster::getCustomerId).collect(Collectors.toSet());
        Map<Long, Customer> customerMap = customerService.selectByIds(customerIds)
                .stream().collect(Collectors.toMap(Customer::getCustomerId, x -> x, (x, y) -> y));

        List<FinancialMaster> financialMasters = financialMasterService.selectByOrderMasterIds(orderMasterIds);
        Map<Long, FinancialMaster> financialMasterMap = financialMasters
                .stream().collect(Collectors.toMap(FinancialMaster::getOrderMasterId, x -> x, (x, y) -> y));

        Set<Long> goodsIds = orderMasterList.stream().map(OrderMaster::getGoodsId).collect(Collectors.toSet());
        List<Goods> goods = goodsService.selectByIds(goodsIds);
        Map<Long, Goods> goodsMap = goods.stream().collect(Collectors.toMap(Goods::getGoodsId, x -> x, (x, y) -> y));

        Set<Long> workerIds = orderMasterList.stream().map(OrderMaster::getWorkerId).collect(Collectors.toSet());
        workerIds.addAll(goods.stream().map(Goods::getWorkerId).collect(Collectors.toSet()));
        Map<Long, Worker> workerMap = workerService.selectByIds(workerIds)
                .stream().collect(Collectors.toMap(Worker::getWorkerId, x -> x, (x, y) -> y));

        for (OrderMaster master : orderMasterList) {
            Customer customer = customerMap.get(master.getCustomerId());
            master.setWorker(workerMap.get(master.getWorkerId()));
            if (customer != null) {
                master.setCustomerName(customer.getName());
                master.setCustomerPhone(customer.getPhone());
            }
            FinancialMaster fm = financialMasterMap.get(master.getId());
            if (fm != null) {
                master.setFinancialMasterMoney(fm.getPayMoney());
                master.setFinancialMasterPayMoney(fm.getServerMoney());
            }
            OrderCallRecord orderCallRecordParam = new OrderCallRecord();
            orderCallRecordParam.setOrderType("01");
            orderCallRecordParam.setOrderId(master.getId());
            List<OrderCallRecord> orderCallRecords = orderCallRecordService.selectOrderCallRecordList(orderCallRecordParam);
            if(CollectionUtils.isNotEmpty(orderCallRecords)){
                OrderCallRecord newOne = orderCallRecords.stream().sorted(Comparator.comparing(OrderCallRecord::getCallTime).reversed()).collect(Collectors.toList()).get(0);
                master.setLastCallTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",newOne.getCallTime()));
            }
            Goods good = goodsMap.get(master.getGoodsId());
            if (good != null) {
                master.setGoods(good);
                // 填充商品三级类目
                if(good.getDeptGoodsCategoryId() != null){
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(good.getDeptGoodsCategoryId());
                    if(deptGoodsCategory != null){
                        GoodsCategory one = goodsCategoryService.selectById(deptGoodsCategory.getGoodsCategoryId());
                        if(one != null && one.getParentCategoryId() != null){
                            GoodsCategory two = goodsCategoryService.selectById(one.getParentCategoryId());
                            if(two != null && two.getParentCategoryId() != null){
                                GoodsCategory three = goodsCategoryService.selectById(two.getParentCategoryId());
                                if(three != null){
                                    int totalNum = orderGoodsService.selectByOrderMasterId(master.getId()).stream().mapToInt(OrderGoods::getGoodsNum).sum();
                                    master.setConsoleGoodsName("【" + three.getGoodsCategoryName()
                                            + "-" + two.getGoodsCategoryName()
                                            + "-" + one.getGoodsCategoryName() + "】x" + totalNum);
                                }
                            }
                        }
                    }
                }
            }
            // 地址信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(master.getAddressId());
            if (customerAddress != null) {
                SysArea sysArea = sysAreaService.selectById(customerAddress.getCountryId());
                String completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();
                master.setAddressName(customerAddress.getName());
                master.setAddressPhone(customerAddress.getPhone());
                master.setAddress(completeAddress);
            }
        }
        return getDataTable(orderMasterList);
    }

    @Log(title = "主订单管理", businessType = BusinessType.EXPORT)
//    @RequiresPermissions("order:master:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(OrderMaster orderMaster) {
        List<OrderMaster> list = orderMasterService.selectOrderMasterList(orderMaster);
        ExcelUtil<OrderMaster> util = new ExcelUtil<>(OrderMaster.class);
        return util.exportExcel(list, "主订单数据");
    }

//    @RequiresPermissions("order:master:remove")
    @Log(title = "主订单管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(orderMasterService.deleteOrderMasterByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 修改主订单
     */
//    @RequiresPermissions("order:master:edit")
    @GetMapping("/edit/{orderMasterId}")
    public String edit(@PathVariable("orderMasterId") Long orderMasterId, ModelMap mmap) {
        mmap.put("orderMaster", orderMasterService.selectById(orderMasterId));
        return prefix + "/edit";
    }

    /**
     * 修改保存主订单
     */
//    @RequiresPermissions("order:master:edit")
    @Log(title = "主订单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated OrderMaster orderMaster) throws BaseAdaPayException {
        if (UserConstants.ORDER_CODE_NOT_UNIQUE.equals(orderMasterService.checkOrderMasterCodeUnique(orderMaster))) {
            return error("修改主订单'" + orderMaster.getCode() + "'失败，主订单编码已存在");
        }
        orderMaster.setUpdateBy(getLoginName());
        return toAjax(orderMasterService.updateOrderMaster(orderMaster));
    }

    /**
     * 修改保存主订单信息
     */
    @PostMapping("/editOrderMaster")
    @ResponseBody
    public AjaxResult editOrderMaster(@RequestBody OrderMaster orderMaster) {
        try {
            int result = orderMasterService.updateOrderMaster(orderMaster);
            if (result > 0) {
                List<OrderDetail> orderDetails = orderDetailService.selectByOrderMasterId(orderMaster.getId());
                orderDetails.forEach(orderDetail -> {
                    orderDetail.setOrderStatus(orderMaster.getOrderStatus());
                    orderDetailService.updateOrderDetail(orderDetail);
                });
            }
            return AjaxResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("");
        }
    }

    @PostMapping("/callCustomer")
    @ResponseBody
    public AjaxResult callCustomer(@RequestBody OrderMaster orderMaster) {
        try {
            OrderMaster result = orderMasterService.selectById(orderMaster.getId());
            if (result.getTimeout() == 1 && OrderStatus.PLAIN.code() == result.getOrderStatus()) {
                orderMaster.setTimeout(0);
            }
            int i = orderMasterService.updateOrderMaster(orderMaster);
            if(i > 0){
                OrderCallRecord param = new OrderCallRecord();
                param.setOrderId(orderMaster.getId());
                param.setCallTime(new Date());
                param.setOrderType("01");
                orderCallRecordService.insertOrderCallRecord(param);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 校验主订单编码
     */
    @PostMapping("/checkOrderMasterCodeUnique")
    @ResponseBody
    public String checkOrderMasterCodeUnique(OrderMaster orderMaster) {
        return orderMasterService.checkOrderMasterCodeUnique(orderMaster);
    }

    /**
     * 消费者申请取消主订单
     *
     * @param orderMasterId 主订单ID
     */
    @PostMapping("/cancel")
    @ResponseBody
    public AjaxResult applyForCancel(Long orderMasterId) throws BaseAdaPayException {
        logger.info("消费者申请取消主订单，orderMasterId={}", orderMasterId);
        List<OrderDetail> orderDetails = orderDetailService.selectByOrderMasterId(orderMasterId);
        for (OrderDetail detail : orderDetails) {
            if (detail.getOrderStatus() == 6 || detail.getOrderStatus() == 0 || detail.getOrderStatus() == 1) {

            }else {
                return AjaxResult.error("请详情内退单退款！");
            }
        }
        orderMasterService.applyForCancel(orderMasterId);
        return AjaxResult.success();
    }

    /*
    *  主单退单
    * */
    @PostMapping("/console/cancel")
    @ResponseBody
    public AjaxResult consoleCancel(Long id) {
        if(id == null){
            return AjaxResult.error("订单编码id不能为空!");
        }
        // 判断该主单状态
        OrderMaster orderMaster = orderMasterService.selectById(id);
        if(!orderMaster.getOrderStatus().equals(OrderStatus.PLAIN.code()) && !orderMaster.getOrderStatus().equals(OrderStatus.RECEIVE.code())){
            return AjaxResult.error("该订单处于无法退单状态!");
        }
        // 含有子单
        List<OrderDetail> orderDetails = orderDetailService.selectByOrderMasterId(id);
        if(CollectionUtils.isNotEmpty(orderDetails)){
            return AjaxResult.error("该订单已经派发过子单,无法退单状态!");
        }
        // 清空id
        orderMasterService.removeWorker(orderMaster.getId());
        // 更新状态待接单
        orderMasterService.updateStatus(orderMaster.getId(), OrderStatus.RECEIVE.code());
        return AjaxResult.success();
    }

    /**
     * 师傅审核取消主订单申请
     *
     * @param orderMasterId 主订单ID
     * @param agree         0=不同意 1=同意
     */
    @PostMapping("/cancel/agree")
    @ResponseBody
    public AjaxResult cancelAgree(Long orderMasterId, Integer agree) {
        logger.info("师傅审核取消主订单申请，orderMasterId={}, agree={}", orderMasterId, agree);
        orderMasterService.cancelAgree(orderMasterId, agree);
        return AjaxResult.success();
    }

    @PostMapping("/app/getDetailListByMasterId")
    @ResponseBody
    public AjaxResult getDetailListByMasterId(@RequestBody Long orderMasterId) {
        try {
            List<OrderStandardDetail> orderStandardDetails = new ArrayList<>();
            List<OrderDetail> detailList = orderDetailService.selectByOrderMasterId(orderMasterId);
            // 查询主单金额
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(orderMasterId);
            BigDecimal totalMoney = financialMaster.getPayMoney();
            for (OrderDetail detail : detailList) {
                // 师傅信息
                Worker worker = workerService.selectById(detail.getWorkerId());

                WorkerCertification workerRealInfo = null;
                String workerName = "";
                if (worker != null) {
                    // 师傅实名信息
                    workerRealInfo = workerCertificationService.selectByWorkerId(detail.getWorkerId());
                    workerName = workerRealInfo == null ? worker.getName() : workerRealInfo.getName();
                }

                // 查询子单加价记录
//                FinancialChangeRecord changeRecordQry = new FinancialChangeRecord();
//                changeRecordQry.setOrderDetailId(detail.getId());
//                List<FinancialChangeRecord> financialChangeRecords = financialChangeRecordService.selectFinancialChangeRecordList(changeRecordQry);
//                if (CollectionUtils.isNotEmpty(financialChangeRecords)) {
//                    totalMoney = totalMoney.add(financialChangeRecords.get(0).getChangeMoney());
//                }

                OrderStandardDetail detailRes = new OrderStandardDetail();
                detailRes.setOrderDetailId(detail.getId());
                detailRes.setOrderDetailCode(detail.getCode());
                detailRes.setWorkerName(workerName);
                detailRes.setRemark(workerName + "(" + detail.getCode() + ")");
                orderStandardDetails.add(detailRes);
            }

            for (OrderStandardDetail orderStandardDetail : orderStandardDetails) {
                orderStandardDetail.setPayMoney(totalMoney);
            }

            return AjaxResult.success(orderStandardDetails);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

    private boolean checkIsOnlyServer(Long orderMasterId, Long workId) {
        // 找出原单的数量
        List<OrderGoods> orderGoodsList = orderGoodsService.selectByOrderMasterId(orderMasterId);
        // 找出原单关联的细单的商品数量
        List<OrderDetail> orderDetailList = orderDetailService.selectByOrderMasterId(orderMasterId);
        for (OrderDetail detail : orderDetailList) {
            // 非一个师傅接单
            if (!workId.equals(detail.getWorkerId())) {
                return false;
            }
            // 子单数量
            List<OrderGoods> orderDetailGoodsList = orderGoodsService.selectByOrderDetailId(detail.getId());
            // 计算剩余未分配的商品数量
            for (OrderGoods detailGoods : orderDetailGoodsList) {
                for (OrderGoods masterGoods : orderGoodsList) {
                    if (Objects.equals(masterGoods.getGoodsStandardId(), detailGoods.getGoodsStandardId())) {
                        masterGoods.setGoodsNum(masterGoods.getGoodsNum() - detailGoods.getGoodsNum());
                    }
                }
            }
        }
        // 有单派完.
        for (OrderGoods orderGoods : orderGoodsList) {
            if (orderGoods.getGoodsNum() > 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 拒绝订单
     * 后台管理系统使用，可控制权限
     */
    @PostMapping("/reject")
    @ResponseBody
    public AjaxResult reject(OrderMaster orderMaster) {
        int i = orderMasterService.reject(orderMaster);
        return AjaxResult.success(i);
    }

    @GetMapping("/differentStatus/count")
    @ResponseBody
    public AjaxResult differentStatusOrderCount(OrderMaster orderMaster) {
        SysUser user = this.getSysUser();
        if(user != null && user.getRoles().get(0).getRoleId() == 101L ){
            orderMaster.setCreateBy(this.getSysUser().getUserId().toString());
        }
        return AjaxResult.success(orderMasterService.differentStatusOrderCount(orderMaster));
    }

    @GetMapping("/count")
    @ResponseBody
    public AjaxResult OrderMasterCount(OrderMaster orderMaster) {
        if(this.getSysUser() != null && this.getSysUser().getRoles().get(0).getRoleId() == 101L){
            orderMaster.setCreateBy(this.getSysUser().getUserId().toString());
        }
        return AjaxResult.success(orderMasterService.countOrderMasterList(orderMaster));
    }
}
