package com.ghy.web.controller.order;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.db.sql.Order;
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.json.JSONObject;
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.request.OrderChangePriceReq;
import com.ghy.order.request.SysOrderAssignRequest;
import com.ghy.order.request.SysOrderGoodsStandards;
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.*;
import com.ghy.web.service.InsuranceService;
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 io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
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.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
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;
    @Resource
    private CustomerAddressService customerAddressService;

    @Resource
    private InsuranceService insuranceService;

    @Resource
    private IInsuranceManagerService insuranceManagerService;

    @PostMapping("/orderInsurance")
    @ResponseBody
    public AjaxResult orderInsurance(@RequestParam(value = "orderCode") String orderCode){
        try {
            insuranceService.orderInsurance(orderCode);
            return AjaxResult.success();
        }catch (Exception e){
            return AjaxResult.error("保险未响应，请再次点击操作，或稍等再试【本单联通保险公司系统，操作此按键时开始投保，偶遇未响应，请间隔一两分钟再次点接单即可！】");
        }
    }

    @GetMapping("/changePrice/{orderIds}")
    public String changePrice(@PathVariable("orderIds") String orderIds, ModelMap mmap)
    {
        mmap.put("orderIds", orderIds);
        return "order/batchChangePrice";
    }

    @PostMapping(value = "batchChangePrice")
    @ResponseBody
    public AjaxResult batchChangePrice(@Validated OrderChangePriceReq changePriceReq){
        return orderMasterService.batchChangePrice(changePriceReq);
    }


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

    @GetMapping("/batchChangeInsurance/{orderIds}")
    public String batchChangeInsurance(@PathVariable(value = "orderIds") String orderIds, ModelMap mmap) {
        // 不知道为啥参数可能会带上双引号 这里去掉再转Long
        orderIds = orderIds.replace("\"", "");
        List<InsuranceManager> insuranceManagers = insuranceManagerService.selectInsuranceManagerList(new InsuranceManager());
        mmap.put("orderIds", orderIds);
        mmap.put("insurances", insuranceManagers);
        return "order/batchPcOrderInsurance";
    }

    @GetMapping("/pcOrderInsurance/{orderIds}")
    public String pcOrderInsurance(@PathVariable(value = "orderIds") String orderIds, ModelMap mmap) {
        // 不知道为啥参数可能会带上双引号 这里去掉再转Long
        orderIds = orderIds.replace("\"", "");
        List<InsuranceManager> insuranceManagers = insuranceManagerService.selectInsuranceManagerList(new InsuranceManager());
        mmap.put("orderIds", orderIds);
        mmap.put("insurances", insuranceManagers);
        return "order/pcOrderInsurance";
    }

    @PostMapping("/pcOrderWorker/batchChangeInsurance")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult batchChangeInsurance(OrderMaster orderMaster) {
        String [] orderIdArr = orderMaster.getOrderMasterIds().split(",");
        for (String id : orderIdArr) {
            // 原单
            OrderMaster master = orderMasterService.selectById(Long.valueOf(id));
            if(master==null || master.getInsuranceId() != null){
                return AjaxResult.error(master.getCode() + "订单已经选择过保险了!");
            }
        }
        // 查询保险信息
        InsuranceManager insuranceManager = insuranceManagerService.selectInsuranceManagerById(orderMaster.getInsuranceId());
        if(insuranceManager == null){
            return AjaxResult.error("保险信息有误!");
        }

        for (String id : orderIdArr) {
            // 原单
            OrderMaster master = orderMasterService.selectById(Long.valueOf(id));
            if(master==null || master.getInsuranceId() != null){
                return AjaxResult.error(master.getCode() + "订单已经选择过保险了!");
            }
            // 修改主单金额 财务单总金额增加 平台金额增加
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(master.getId());
            financialMaster.setPayMoney(financialMaster.getPayMoney().add(insuranceManager.getInsuranceAmount()));
            financialMaster.setTotalMoney(financialMaster.getTotalMoney().add(insuranceManager.getInsuranceAmount()));
            financialMasterService.updateFinancialMaster(financialMaster);
            // 修改子单
            List<FinancialDetail> details = financialDetailService.selectByFinancialMasterIdAndType(financialMaster.getId(), FinancialDetailType.PLATFORM_FEE.getCode());
            if(CollectionUtils.isNotEmpty(details)){
                FinancialDetail detail = details.get(0);
                detail.setPayMoney(detail.getPayMoney().add(insuranceManager.getInsuranceAmount()));
                financialDetailService.updateFinancialDetail(detail);
            }
            // 修改主单保险内容
            OrderMaster param = new OrderMaster();
            param.setId(master.getId());
            param.setInsuranceId(orderMaster.getInsuranceId());
            orderMasterService.updateOrderMaster(param);
        }
        return AjaxResult.success();
    }

    @PostMapping("/pcOrderWorker/changeInsurance")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult changeInsurance(OrderMaster orderMaster) {
        // 原单
        OrderMaster master = orderMasterService.selectById(orderMaster.getId());
        if(master==null || master.getInsuranceId() != null){
            return AjaxResult.error("订单已经选择过保险了!");
        }
        // 查询保险信息
        InsuranceManager insuranceManager = insuranceManagerService.selectInsuranceManagerById(orderMaster.getInsuranceId());
        if(insuranceManager == null){
            return AjaxResult.error("保险信息有误!");
        }
        // 修改主单金额 财务单总金额增加 平台金额增加
        FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(master.getId());
        financialMaster.setPayMoney(financialMaster.getPayMoney().add(insuranceManager.getInsuranceAmount()));
        financialMaster.setTotalMoney(financialMaster.getTotalMoney().add(insuranceManager.getInsuranceAmount()));
        financialMasterService.updateFinancialMaster(financialMaster);
        // 修改子单
        List<FinancialDetail> details = financialDetailService.selectByFinancialMasterIdAndType(financialMaster.getId(), FinancialDetailType.PLATFORM_FEE.getCode());
        if(CollectionUtils.isNotEmpty(details)){
            FinancialDetail detail = details.get(0);
            detail.setPayMoney(detail.getPayMoney().add(insuranceManager.getInsuranceAmount()));
            financialDetailService.updateFinancialDetail(detail);
        }
        // 修改主单保险内容
        orderMasterService.updateOrderMaster(orderMaster);
        return AjaxResult.success();
    }

    @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())).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> paramsNew = new HashMap<>();
                // 订单编号
                paramsNew.put("thing21", "您帐号收到1条新订单");
                // 名称
                paramsNew.put("thing31", "请进入【我的订单--新订单】操作处理");
                CustomerAddress address = customerAddressService.selectByCustomerAddressId(master.getAddressId());
                paramsNew.put("thing14", address.getName());
                // 预约时间
                paramsNew.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", master.getExpectTimeStart()));
                // 消息推送
                WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), assignWorker.getWxOpenId(), WxMsgEnum.NORMAL_ORDER, paramsNew);
            } catch (Exception e) {
                // 暂时不做任何操作。
                logger.error(e.getMessage(), e);
            }

        });
        return AjaxResult.success();
    }

    @PostMapping("/importData")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysOrderRequest> util = new ExcelUtil<SysOrderRequest>(SysOrderRequest.class);
        List<SysOrderRequest> jsonObjects = util.importExcel(file.getInputStream());
        boolean flag = false;
        for (SysOrderRequest model : jsonObjects) {
            if("序号".equals(model.getSeq())){
                flag = true;
                continue;
            }
            if(flag){
                sysOrder(format(model));
            }
        }
        return AjaxResult.success(jsonObjects);
    }

    public SysOrderAssignRequest format(SysOrderRequest orderRequest) throws Exception{
        SysOrderAssignRequest request = new SysOrderAssignRequest();
        if(StringUtils.isEmpty(orderRequest.getSeq())){
            throw new Exception("导入表格序号,序号不能为空!");
        }
        if(StringUtils.isEmpty(orderRequest.getName())){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",姓名不能为空!");
        }
        if(StringUtils.isEmpty(orderRequest.getPrice())){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",I列，发布价格填写不能为空！");
        }
        try {
            Integer.parseInt(orderRequest.getPrice());
        }catch (Exception e){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",I列，发布价格不能有小数点！");
        }
        if(StringUtils.isEmpty(orderRequest.getNum())){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",H列，数量填写不能为空！");
        }
        try {
            Integer.parseInt(orderRequest.getNum());
        }catch (Exception e){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",H列，数量不能含小数点。");
        }
        if(StringUtils.isEmpty(orderRequest.getLastCategory())){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",C列，四级类目不能为空！");
        }
        request.setCustomerName(orderRequest.getName());
        if(StringUtils.isEmpty(orderRequest.getPhone())){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",导入手机号不能为空!");
        }
        request.setCustomerPhone(orderRequest.getPhone());
        request.setServDate(orderRequest.getDate());
        request.setServTime(orderRequest.getTime());
        request.setGoodsBrand(orderRequest.getBrand());
        request.setRemark(orderRequest.getRemark());
        if(StringUtils.isEmpty(orderRequest.getMode())){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",G列，下单模式名称有误/或带有其它字符！");
        }else {
            if(orderRequest.getMode().contains("-")){
                String orderModel = orderRequest.getMode().split("-")[0];
                String payType = orderRequest.getMode().split("-")[1];
                if("带价下单".equals(orderModel)){
                    request.setOrderMode("02");
                }else if("一票价".equals(orderModel)){
                    request.setOrderMode("01");
                }else {
                    throw new Exception("导入表格序号" + orderRequest.getSeq() + ",G列，下单模式名称有误/或带有其它字符！");
                }
                if("到付".equals(payType)){
                    request.setPayMode("01");
                }else {
                    request.setPayMode("02");
                }
            }else {
                if("带价下单".equals(orderRequest.getMode())){
                    request.setOrderMode("02");
                    request.setPayMode("02");
                }else if("一票价".equals(orderRequest.getMode())){
                    request.setOrderMode("01");
                    request.setPayMode("02");
                }else {
                    throw new Exception("导入表格序号" + orderRequest.getSeq() + ",G列，下单模式名称有误/或带有其它字符！");
                }
            }

        }

        if(StringUtils.isEmpty(orderRequest.getPrice())){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",I列，发布价格填写不能为空！\n");
        }
        request.setPrice(new BigDecimal(orderRequest.getPrice()));
        request.setVideoUrl(orderRequest.getUrl());
        request.setImageUrl("http://gqz.opsoul.com/default.jpeg");
        List<SysOrderGoodsStandards> goodsStandards = new ArrayList<>();
        String [] categoryNames = orderRequest.getCategory().split("-");
        if(categoryNames.length != 3){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",B列，三级类目名称有误/或格式有误！");
        }else {
            if(StringUtils.isEmpty(categoryNames[0])||StringUtils.isEmpty(categoryNames[1])||StringUtils.isEmpty(categoryNames[2])){
                throw new Exception("导入表格序号" + orderRequest.getSeq() + ",B列，三级类目名称有误/或格式有误！");
            }
            try {
                // 第一层
                GoodsCategory param1 = new GoodsCategory();
                param1.setGoodsCategoryName(categoryNames[0]);
                GoodsCategory category1 = goodsCategoryService.selectGoodsCategoryList(param1).get(0);
                // 第二层
                GoodsCategory param2 = new GoodsCategory();
                param2.setParentCategoryId(category1.getGoodsCategoryId());
                param2.setGoodsCategoryName(categoryNames[1]);
                GoodsCategory category2 = goodsCategoryService.selectGoodsCategoryList(param2).get(0);
                // 第三层
                GoodsCategory param3 = new GoodsCategory();
                param3.setParentCategoryId(category2.getGoodsCategoryId());
                param3.setGoodsCategoryName(categoryNames[2]);
                GoodsCategory category3 = goodsCategoryService.selectGoodsCategoryList(param3).get(0);

                DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.selectOneByGoodsCategoryId(category3.getGoodsCategoryId());
                request.setCategoryId3(deptGoodsCategory.getDeptGoodsCategoryId());

                // 第四层
                GoodsCategory param4 = new GoodsCategory();
                param4.setParentCategoryId(category3.getGoodsCategoryId());
                param4.setGoodsCategoryName(orderRequest.getLastCategory());
                List<GoodsCategory> categories =  goodsCategoryService.selectGoodsCategoryList(param4);
                if(CollectionUtils.isEmpty(categories)){
                    param4.setGoodsCategoryName(null);
                    categories = goodsCategoryService.selectGoodsCategoryList(param4);
                }
                GoodsCategory category4 = categories.get(0);

                SysOrderGoodsStandards standards = new SysOrderGoodsStandards();
                DeptGoodsCategory deptGoodsCategory2 = deptGoodsCategoryService.selectOneByGoodsCategoryId(category4.getGoodsCategoryId());
                standards.setDeptCategoryId(deptGoodsCategory2.getDeptGoodsCategoryId());
                standards.setGoodsStandardNum(Integer.parseInt(orderRequest.getNum()));
                standards.setGoodsStandardName(orderRequest.getLastCategory());
                goodsStandards.add(standards);
            }catch (Exception e){
                throw new Exception("导入表格序号" + orderRequest.getSeq() + ",B列，三级类目名称有误/或格式有误！");
            }

        }
        request.setOrderGoodsStandards(goodsStandards);
        String [] addressName = orderRequest.getAddress().split("-");
        if(addressName.length == 1){
            addressName = orderRequest.getAddress().split("，");
            if(addressName.length == 1){
                addressName = orderRequest.getAddress().split(" ");
            }if(addressName.length == 1){
                addressName = orderRequest.getAddress().split("/");
            }
        }
        if(addressName.length < 4){
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",L列，服务地址不能为空或分隔符不能少于3个！");
        }else {
            // 省
            SysArea param1 = new SysArea();
            param1.setAreaName(addressName[0]);
            SysArea area1 = sysAreaService.selectSysAreaList(param1).get(0);
            request.setProvinceId(area1.getAreaId());

            // 市
            SysArea param2 = new SysArea();
            param2.setAreaName(addressName[1]);
            param2.setParentCode(area1.getAreaCode());
            SysArea area2 = sysAreaService.selectSysAreaList(param2).get(0);
            request.setCityId(area2.getAreaId());

            // 区
            SysArea param3 = new SysArea();
            param3.setAreaName(addressName[2]);
            param3.setParentCode(area2.getAreaCode());
            SysArea area3 = sysAreaService.selectSysAreaList(param3).get(0);
            request.setDistrictId(area3.getAreaId());

            // 详细地址
            if(addressName.length == 5){
                request.setFullAddress(addressName[3]+addressName[4]);
            }else {
                request.setFullAddress(addressName[3]);
            }

        }
        return request;
    }

    public synchronized void sysOrder(@RequestBody SysOrderAssignRequest request) throws Exception {

        // 判断传递价格是否有小数
        if (new BigDecimal(request.getPrice().intValue()).compareTo(request.getPrice())!=0){
            throw new Exception("后台发单金额不能含有小数!");
        }

        // 判断是否有客户
        SysUser sysUser = getSysUser();
        Long deptId = sysUser.getDept().getDeptId();
        String loginName = sysUser.getLoginName();
        Customer customer = customerService.selectByAccount("sys_" + loginName);
        if (customer == null) {
            customer = new Customer();
            customer.setAccount("sys_" + loginName);
            customer.setName("平台用户_" + loginName);
            customerService.insertCustomer(customer);
        }

        // 判断是否有客户地址
        if (request.getProvinceId() == null || request.getCityId() == null || request.getDistrictId() == null || org.apache.commons.lang3.StringUtils.isBlank(request.getFullAddress())) {
            throw new Exception("请填写地址");
        }

        CustomerAddress customerAddress = new CustomerAddress();
        customerAddress.setCustomerId(customer.getCustomerId());
        customerAddress.setProvinceId(request.getProvinceId());
        customerAddress.setCityId(request.getCityId());
        customerAddress.setCountryId(request.getDistrictId());
        customerAddress.setAddress(request.getFullAddress());
        customerAddress.setIsDefault(0);
        customerAddress.setPhone(request.getCustomerPhone());
        customerAddress.setName(request.getCustomerName());
        customerAddressService.insertCustomerAddress(customerAddress);

        // 订单总价 不能小于0
        BigDecimal orderPrice = request.getPrice().max(BigDecimal.ZERO);
        Integer totalNum = 0;
        for (SysOrderGoodsStandards model : request.getOrderGoodsStandards()) {
            totalNum = totalNum + model.getGoodsStandardNum();
        }
        // 商品单价
        BigDecimal goodsPrice = orderPrice.divide(BigDecimal.valueOf(totalNum), RoundingMode.HALF_UP);

        // 增加商品
        Goods goods = new Goods();
        goods.setDeptId(deptId);
        // 后续改成 三级类目+品牌
        goods.setGoodsName(request.getGoodsBrand());
        goods.setGoodsImgUrl(request.getImageUrl());
        goods.setGoodsVideoUrl(request.getVideoUrl());
        goods.setDeptGoodsCategoryId(request.getCategoryId3());
        goods.setStatus(1);
        goods.setRemark(request.getRemark());
        goodsService.insertGoods(goods);

        List<GoodsStandard> goodsStandards = new ArrayList<>();
        // TODO 生成规格 -- orderGoods完成后未会写规格id
        request.getOrderGoodsStandards().forEach(list -> {
            DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(list.getDeptCategoryId());
            GoodsStandard standard = new GoodsStandard();
            standard.setGoodsStandardName(list.getGoodsStandardName());
            standard.setDeptGoodsCategoryId(deptGoodsCategory.getDeptGoodsCategoryId());
            standard.setGoodsCategoryName(deptGoodsCategory.getGoodsCategoryName());
            standard.setGoodsPrice(goodsPrice);
            standard.setGoodsId(goods.getGoodsId());
            standard.setExtMoney(BigDecimal.ZERO);
            standard.setGoodsNum(list.getGoodsStandardNum());
            standard.setSaleNum(0);
            goodsStandardService.insertGoodsStandard(standard);
            goodsStandards.add(standard);
        });

        // 生成主单
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setDeptId(deptId);
        orderMaster.setCode(orderMasterService.createOrderCode());
        orderMaster.setOrderType(0);
        orderMaster.setOrderStatus(OrderStatus.RECEIVE.code());
        orderMaster.setAddressId(customerAddress.getCustomerAddressId());
        orderMaster.setPayStatus(PayStatus.WAIT_PAY.getCode());
        orderMaster.setCreateTime(new Date());
        orderMaster.setCustomerId(customer.getCustomerId());
        orderMaster.setGoodsId(goods.getGoodsId());
        orderMaster.setPayType(0);
        orderMaster.setOrderMode(request.getOrderMode());
        orderMaster.setPayMode(request.getPayMode());
        orderMaster.setGoodsBrand(request.getGoodsBrand());
        orderMaster.setGoodsSpecification(request.getGoodsSpecification());
        // 存在登陆用户的情况下
        if(getSysUser() != null){
            orderMaster.setCreateBy(getSysUser().getUserId().toString());
        }
        if(StringUtils.isEmpty(request.getServDate())){
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 1);
            String dateStr = DateUtil.format(calendar.getTime(), "yyyy-MM-dd");
            orderMaster.setExpectTimeStart(DateUtil.parse(dateStr+" 08:00", "yyyy-MM-dd HH:mm"));
            orderMaster.setExpectTimeEnd(DateUtil.parse(dateStr+" 10:00", "yyyy-MM-dd HH:mm"));
        }else {
            // 服务时间
            String[] split = request.getServTime().split("-");
            try {
                orderMaster.setExpectTimeStart(org.apache.commons.lang3.time.DateUtils.parseDate(request.getServDate() + " " + split[0], "yyyy-MM-dd hh:mm"));
                orderMaster.setExpectTimeEnd(org.apache.commons.lang3.time.DateUtils.parseDate(request.getServDate() + " " + split[1], "yyyy-MM-dd hh:mm"));
            } catch (Exception e) {

            }
        }
        orderMasterService.insertOrderMaster(orderMaster);
        Assert.notNull(orderMaster.getId(), "OrderMaster.id is null!");

        // 生成财务主单
        FinancialMaster financialMaster = new FinancialMaster(financialMasterService.createCode(), deptId,
                orderMaster.getId(), orderMaster.getCode(), request.getPrice(), BigDecimal.ZERO, request.getPrice());
        financialMaster.setServerMoney(financialMaster.getTotalMoney());
        financialMasterService.insertFinancialMaster(financialMaster);
        Assert.notNull(financialMaster.getId(), "FinancialMaster.id is null!");

        // 生成提成类子财务单
        createDeptFinancialDetail(goodsStandards.get(0), deptId, financialMaster);

        // 生成商品订单
        goodsStandards.forEach(goodsStandard -> {
            OrderGoods orderGoods = new OrderGoods(orderMaster.getId(), goodsStandard.getGoodsStandardId(),
                    goodsStandard.getGoodsStandardName(), goodsStandard.getGoodsNum(), 0);
            orderGoodsService.insertOrderGoods(orderGoods);
        });

        // 推送公众号通知数据。
        try {
            Worker assignWorker = workerService.selectById(orderMaster.getWorkerId());
            // 消息组装。
            Map<String, Object> params = new HashMap<>();
            // 订单编号
            params.put("character_string6", orderMaster.getCode());
            // 名称
            params.put("thing14", customer.getName());
            // 预约时间
            params.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", orderMaster.getExpectTimeStart()));
            // 消息推送
            WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), assignWorker.getWxOpenId(), WxMsgEnum.TEXT, params);
        } catch (Exception e) {
            // 暂时不做任何操作。
            logger.error(e.getMessage(), e);
        }
        logger.info("下单成成");
    }

    private void createDeptFinancialDetail(GoodsStandard goodsStandard, Long deptId, FinancialMaster financialMaster) {
        // 平台
        BigDecimal deptMoney = BigDecimal.ZERO;
        // 截流扣点
        BigDecimal specialMoney = BigDecimal.ZERO;
        // 服务金额
        BigDecimal serverMoney = financialMaster.getServerMoney();
        // 扣点设置类目
        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goodsStandard.getDeptGoodsCategoryId());
        // 平台扣点 = 平台金额 + 商品单价 * 扣点比例
        deptMoney = deptMoney.add(deptGoodsCategory.getPcDeptMoney())
                .add(financialMaster.getPayMoney().multiply(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getPcDeptRate()))));
        // 截流扣点 = 截流金额 + 商品单价 * 扣点比例
        specialMoney = specialMoney.add(deptGoodsCategory.getPcRetainMoney())
                .add(financialMaster.getPayMoney().multiply(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getPcRetainRate()))));
        // 平台扣点记录
        FinancialDetail deptDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                financialMaster.getId(), financialMaster.getCode(), deptMoney, FinancialDetailType.PLATFORM_FEE.getCode(), null);
        financialDetailService.insertFinancialDetail(deptDetail);
        // 剩余服务金额
        serverMoney = serverMoney.subtract(deptMoney);

        // 截流扣点记录
        FinancialDetail retainDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                financialMaster.getId(), financialMaster.getCode(), specialMoney, FinancialDetailType.PLATFORM_FEE.getCode(), null);
        financialDetailService.insertFinancialDetail(retainDetail);
        // 剩余服务金额
        serverMoney = serverMoney.subtract(specialMoney);

        FinancialMaster fmUpdate = new FinancialMaster();
        fmUpdate.setId(financialMaster.getId());
        fmUpdate.setServerMoney(serverMoney);
        financialMasterService.updateFinancialMaster(fmUpdate);
    }

    @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());
            // 填充商品三级类目
            if(goods.getDeptGoodsCategoryId() != null){
                Long categoryId = null;
                // 前端发单和后台派单
                if(com.ghy.common.utils.StringUtils.isEmpty(master.getOrderMode())){
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.selectOneByGoodsCategoryId(goods.getDeptGoodsCategoryId());
                    if(deptGoodsCategory != null){
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    }
                }else {
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goods.getDeptGoodsCategoryId());
                    if(deptGoodsCategory != null){
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    }
                }
                if(categoryId != null){
                    GoodsCategory one = goodsCategoryService.selectById(categoryId);
                    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){
                                master.setConsoleGoodsName(three.getGoodsCategoryName()
                                        + "-" + two.getGoodsCategoryName()
                                        + "-" + one.getGoodsCategoryName());
                            }
                        }
                    }
                }
            }

            // 财务信息
            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;
            if(customerAddress.getStreetId()!=null){
                sysArea = sysAreaService.selectById(customerAddress.getStreetId());
            }else {
                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.setGoodsBrand(master.getGoodsBrand());
            orderListResponse.setGoodsSpecification(master.getGoodsSpecification());
            orderListResponse.setOrderMasterId(master.getId());
            orderListResponse.setGoodsName(master.getConsoleGoodsName());
            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;
            if(customerAddress.getStreetId()!=null){
                sysArea = sysAreaService.selectById(customerAddress.getStreetId());
            }else {
                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.getSurname()+ 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());

                orderStandardDetail.setAfterTimeout(orderDetail.getAfterTimeout());

                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.getSurname()+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());
            if (goods != null) {
                // 填充商品三级类目
                if(goods.getDeptGoodsCategoryId() != null){
                    Long categoryId = null;
                    // 前端发单和后台派单
                    if(com.ghy.common.utils.StringUtils.isEmpty(orderMaster.getOrderMode())){
                        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.selectOneByGoodsCategoryId(goods.getDeptGoodsCategoryId());
                        if(deptGoodsCategory != null){
                            categoryId = deptGoodsCategory.getGoodsCategoryId();
                        }
                    }else {
                        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goods.getDeptGoodsCategoryId());
                        if(deptGoodsCategory != null){
                            categoryId = deptGoodsCategory.getGoodsCategoryId();
                        }
                    }
                    if(categoryId != null){
                        GoodsCategory one = goodsCategoryService.selectById(categoryId);
                        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){
                                    orderListResponse.setTotalName(three.getGoodsCategoryName()
                                            + "-" + two.getGoodsCategoryName()
                                            + "-" + one.getGoodsCategoryName());
                                }
                            }
                        }
                    }
                }
            }
            // 补全商品服务区域
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(goods.getGoodsId());
            goods.setGoodsAreaList(goodsAreas);

            // 地址信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(orderMaster.getAddressId());
            SysArea sysArea;
            if(customerAddress.getStreetId()!=null){
                sysArea = sysAreaService.selectById(customerAddress.getStreetId());
            }else {
                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.setWorkerId(worker == null ? null : worker.getWorkerId());
            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()) {
            List<?> rows = this.afterList(orderMaster).getRows();
            StringBuilder masterIds = new StringBuilder();
            if(CollectionUtils.isNotEmpty(rows)){
                rows.forEach(model->{
                    OrderListResponse response = (OrderListResponse)model;
                    masterIds.append(response.getOrderMasterId()).append(",");
                });
            }
            String ids = masterIds.toString();
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(ids)) {
                orderMaster.setOrderMasterIds(ids.substring(0, ids.length() - 1));
            }
        }

        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());
            }
            if(StringUtils.isNotEmpty(orderMaster.getOrderStatusName())){
                master.setOrderStatusName(orderMaster.getOrderStatusName());
            }
            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()) + " 拨号次数x" + orderCallRecords.size());
            }
            Goods good = goodsMap.get(master.getGoodsId());
            if (good != null) {
                master.setGoods(good);
                // 填充商品三级类目
                if(good.getDeptGoodsCategoryId() != null){
                    Long categoryId = null;
                    // 前端发单和后台派单
                    if(com.ghy.common.utils.StringUtils.isEmpty(master.getOrderMode())){
                        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.selectOneByGoodsCategoryId(good.getDeptGoodsCategoryId());
                        if(deptGoodsCategory != null){
                            categoryId = deptGoodsCategory.getGoodsCategoryId();
                        }
                    }else {
                        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(good.getDeptGoodsCategoryId());
                        if(deptGoodsCategory != null){
                            categoryId = deptGoodsCategory.getGoodsCategoryId();
                        }
                    }
                    if(categoryId != null){
                        GoodsCategory one = goodsCategoryService.selectById(categoryId);
                        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;
                if(customerAddress.getStreetId() != null){
                    sysArea = sysAreaService.selectById(customerAddress.getStreetId());
                }else {
                    sysArea = sysAreaService.selectById(customerAddress.getCountryId());
                }

                String completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();
                master.setAddressName(customerAddress.getName());
                master.setAddressPhone(customerAddress.getPhone());
                master.setAddress(completeAddress);
            }
            if(master.getExpectTimeStart() != null && master.getExpectTimeEnd() != null){
                master.setMixExpectTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",master.getExpectTimeStart()) +"-"+ DateUtils.parseDateToStr("HH:mm",master.getExpectTimeEnd()));
            }
            if("01".equals(master.getConsultMode())){
                master.setOrderMode("05");
            } else if (StringUtils.isEmpty(master.getOrderMode())) {
                master.setOrderMode("01");
            }
            List<OrderDetail> details = orderDetailService.selectByOrderMasterId(master.getId());
            StringBuilder stringBuilder = new StringBuilder();
            details.forEach(model->{
                GoodsImgs param = new GoodsImgs();
                param.setRemark(String.valueOf(model.getId()));
                param.setImgType(ImgType.FINISH_IMG.getId());
                List<GoodsImgs> imgsList = goodsImgsService.qryGoodsImgs(param);
                imgsList.forEach(imgs->{
                    stringBuilder.append("<a target='_blank' href='").append(imgs.getImgUrl()).append("' >查看图片<a/>");
                });
            });
            master.setOrderImgs(stringBuilder.toString());
        }
        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 {
        try {
            if (UserConstants.ORDER_CODE_NOT_UNIQUE.equals(orderMasterService.checkOrderMasterCodeUnique(orderMaster))) {
                return error("修改主订单'" + orderMaster.getCode() + "'失败，主订单编码已存在");
            }
            orderMaster.setUpdateBy(getLoginName());
            return toAjax(orderMasterService.updateOrderMaster(orderMaster));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("修改订单信息失败:" + e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 修改保存主订单信息
     */
    @PostMapping("/editOrderMaster")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editOrderMaster(@RequestBody OrderMaster orderMaster) {
        try {
            int result = orderMasterService.updateOrderMaster(orderMaster);
            // 下单
            if(orderMaster.getOrderStatus() != null && OrderStatus.PLAIN.code() == orderMaster.getOrderStatus()){
                OrderMaster model = orderMasterService.selectById(orderMaster.getId());
//                try {
//                    if(model.getInsuranceId()!=null){
//                        insuranceService.orderInsurance(model.getCode());
//                    }
//                }catch (Exception e){
//                    logger.error("下单报错:" + ExceptionUtils.getMessage(e));
//                    return AjaxResult.error("保险正生成中，可能需几秒或几分钟，请稍等即可！若超半小时可联系发单方或平台!");
//                }
                // 判断是否是在线支付订单--如果是在线支付,且未付款,则需要提示支付后接单
                if(PayTypeEnum.WX_LITE.getCode().equals(model.getPayType())){
                    // 查询财务信息
                    FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(model.getId());
                    if(!PayStatus.PAID.getCode().equals(financialMaster.getPayStatus())){
                        return AjaxResult.error("客户支付中，请稍后！待支付完成可接单!");
                    }
                }
            }
            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();
            logger.error("派单失败:" + ExceptionUtils.getMessage(e));
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/editServingInfo")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editServingInfo(@RequestBody OrderMaster request) {
        try {
            // 更新期望时间
            orderMasterService.updateOrderMaster(request);
            // 更新客户联系方式和地址
            OrderMaster order = orderMasterService.selectById(request.getId());
            CustomerAddress address2Update = new CustomerAddress();
            address2Update.setAddress(request.getAddress());
            address2Update.setPhone(request.getAddressPhone());
            address2Update.setCustomerAddressId(order.getAddressId());
            customerAddressService.updateCustomerAddress(address2Update);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改服务时间失败:" + ExceptionUtils.getStackTrace(e));
            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.getSurname()+ 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));
    }

    @ResponseBody
    @Operation(summary = "获取当天订单统计数据", method = "GET")
    @GetMapping(path = "/statistics/now", produces = MediaType.APPLICATION_JSON_VALUE)
    public AjaxResult statisticsNow() {
        return AjaxResult.success(orderMasterService.orderStatisticsReturnByNow());
    }

    @ResponseBody
    @Operation(summary = "获取全部订单统计数据", method = "GET")
    @GetMapping(path = "/statistics", produces = MediaType.APPLICATION_JSON_VALUE)
    public AjaxResult statistics() {
        return AjaxResult.success(orderMasterService.orderStatisticsReturn());
    }
}
