package com.ghy.web.controller.order;

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.page.PageDomain;
import com.ghy.common.core.page.TableDataInfo;
import com.ghy.common.core.page.TableSupport;
import com.ghy.common.enums.BusinessType;
import com.ghy.common.enums.ImgType;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.StringUtils;
import com.ghy.common.utils.poi.ExcelUtil;
import com.ghy.customer.domain.CustomerAddress;
import com.ghy.customer.service.CustomerAddressService;
import com.ghy.goods.domain.Goods;
import com.ghy.goods.domain.GoodsArea;
import com.ghy.goods.domain.GoodsImgs;
import com.ghy.goods.domain.GoodsStandard;
import com.ghy.goods.service.GoodsAreaService;
import com.ghy.goods.service.GoodsImgsService;
import com.ghy.goods.service.GoodsService;
import com.ghy.goods.service.GoodsStandardService;
import com.ghy.order.domain.AfterServiceRecord;
import com.ghy.order.domain.OrderDetail;
import com.ghy.order.domain.OrderGoods;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.service.IAfterServiceRecordService;
import com.ghy.order.service.OrderDetailService;
import com.ghy.order.service.OrderGoodsService;
import com.ghy.order.service.OrderMasterService;
import com.ghy.payment.domain.FinancialChangeRecord;
import com.ghy.payment.domain.FinancialDetail;
import com.ghy.payment.domain.FinancialMaster;
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.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
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.util.ArrayList;
import java.util.List;
import java.util.Objects;
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 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("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestBody OrderMaster orderMaster) {
//        TableDataInfo rspData = new TableDataInfo();
        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 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);
            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.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());

            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) {
        TableDataInfo rspData = new TableDataInfo();
        startPage();
        List<OrderMasterResponseVo> orderMasterResponseVos = new ArrayList<>();
        List<OrderMaster> orderMasterList = orderMasterService.selectOrderMasterList(orderMaster);
        for (OrderMaster master : orderMasterList) {
            OrderMasterResponseVo orderMasterResponseVo = new OrderMasterResponseVo();
            // 将公共属性复制过去
            BeanUtils.copyProperties(master, orderMasterResponseVo);
            // 师傅信息
            if (StringUtils.isNotNull(master.getWorkerId())) {
                Worker worker = workerService.selectById(master.getWorkerId());
                orderMasterResponseVo.setWorkerName(worker.getName());
            }
            // 消费者信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(master.getAddressId());
            orderMasterResponseVo.setCustomerName(customerAddress.getName());

            orderMasterResponseVos.add(orderMasterResponseVo);
        }
        // 存在数据在进行数据查询处理。
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (null == pageDomain.getPageNum() || null == pageDomain.getPageSize()) {
            rspData.setRows(orderMasterResponseVos);
            rspData.setTotal(orderMasterResponseVos.size());
            return rspData;
        }
        int pageNum = (pageDomain.getPageNum() - 1) * 10;
        int pageSize = pageDomain.getPageNum() * 10;
        if (pageSize > orderMasterResponseVos.size()) {
            pageSize = orderMasterResponseVos.size();
        }
        rspData.setRows(orderMasterResponseVos.subList(pageNum, pageSize));
        rspData.setTotal(orderMasterResponseVos.size());
        return rspData;
    }

    @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("/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();
    }

    /**
     * 师傅审核取消主订单申请
     *
     * @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);
    }
}
