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.TableDataInfo;
import com.ghy.common.enums.BusinessType;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.ObjectUtils;
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.Goods;
import com.ghy.goods.domain.GoodsStandard;
import com.ghy.goods.service.GoodsService;
import com.ghy.goods.service.GoodsStandardService;
import com.ghy.order.domain.OrderDetail;
import com.ghy.order.domain.OrderGoods;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.service.OrderDetailService;
import com.ghy.order.service.OrderGoodsService;
import com.ghy.order.service.OrderMasterService;
import com.ghy.payment.domain.FinancialDetail;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.service.FinancialDetailService;
import com.ghy.payment.service.FinancialMasterService;
import com.ghy.web.pojo.vo.OrderDetailsResponseVo;
import com.ghy.web.pojo.vo.OrderListResponse;
import com.ghy.web.pojo.vo.OrderStandard;
import com.ghy.web.pojo.vo.OrderStandardDetail;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.service.WorkerService;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    private final String prefix = "order/master";

    @Autowired
    private OrderMasterService orderMasterService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private WorkerService workerService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private CustomerAddressService addressService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CustomerAddressService customerAddressService;
    @Autowired
    private FinancialDetailService financialDetailService;
    @Autowired
    private FinancialMasterService financialMasterService;
    @Autowired
    private GoodsStandardService goodsStandardService;

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

    @PostMapping("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestBody OrderMaster orderMaster) {
        startPage();
        List<OrderListResponse> orderListResponses = new ArrayList<>();
        List<OrderMaster> list = orderMasterService.selectOrderMasterList(orderMaster);
        list.forEach(master -> {
            // 初始化属性
            OrderListResponse orderListResponse = new OrderListResponse();
            List<OrderStandard> standardList = new ArrayList<>();

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

            // 消费者信息
            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());

            // 地址信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(master.getAddressId());

            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(financialMaster.getPayMoney());
            orderListResponse.setWorkerName(worker.getName());
            orderListResponse.setWorkerPhone(worker.getPhone());
            orderListResponse.setCustomerName(customer.getName());
            orderListResponse.setCustomerPhone(customer.getPhone());
            orderListResponse.setServerTime(master.getRevTime());
            orderListResponse.setOrderStatus(master.getOrderStatus());
            orderListResponse.setPayStatus(master.getPayStatus());
            orderListResponse.setPayType(master.getPayType());
            orderListResponse.setOrderMasterCode(master.getCode());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(customerAddress.getAddress());
            orderListResponses.add(orderListResponse);

        });
        return voDataTable(orderListResponses, list);
    }

    @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<>();
            orderDetailList.forEach(orderDetail -> {
                List<OrderStandard> standardList = new ArrayList<>();
                // 子单施工师傅信息
                Worker detailWorker = workerService.selectById(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);
                }

                OrderStandardDetail orderStandardDetail = new OrderStandardDetail();
                orderStandardDetail.setOrderDetailId(orderDetail.getId());
                orderStandardDetail.setOrderDetailCode(orderDetail.getCode());
                orderStandardDetail.setWorkBeginTime(orderDetail.getWorkBeginTime());
                orderStandardDetail.setWorkFinishTime(orderDetail.getWorkFinishTime());
                orderStandardDetail.setWorkerName(detailWorker.getName());
                orderStandardDetail.setWorkerPhone(detailWorker.getPhone());
                orderStandardDetail.setRevTime(orderDetail.getRevTime());
                orderStandardDetail.setOrderStandardList(standardList);

                orderStandardDetails.add(orderStandardDetail);
            });

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

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

            // 消费者信息
            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());

            // 财务信息
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(orderMaster.getId());

            // 地址信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(orderMaster.getAddressId());

            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);
            }

            // 编辑返回属性
            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(financialMaster.getPayMoney());
            orderListResponse.setWorkerName(worker.getName());
            orderListResponse.setWorkerPhone(worker.getPhone());
            orderListResponse.setCustomerName(customer.getName());
            orderListResponse.setCustomerPhone(customer.getPhone());
            orderListResponse.setOrderStatus(orderMaster.getOrderStatus());
            orderListResponse.setPayStatus(orderMaster.getPayStatus());
            orderListResponse.setPayType(orderMaster.getPayType());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(customerAddress.getAddress());
            orderListResponse.setServerTime(orderMaster.getRevTime());
            orderListResponse.setCreateTime(orderMaster.getCreateTime());
            orderListResponse.setOrderStandardDetailList(orderStandardDetails);

            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) {
        startPage();
        List<OrderMaster> orderMasterList = orderMasterService.selectOrderMasterList(orderMaster);
        // 数据处理。待返回的数据信息。
        List<OrderDetailsResponseVo> orderDetailsResponseVoList = new ArrayList<>();
        // 存在数据在进行数据查询处理。
        if (orderMasterList != null && orderMasterList.size() > 0) {
            // 第一次循环 进行拿到对应用户数据集合信息与实体集合数据信息，
            // 消费者相关集合
            List<Long> customIdList = new ArrayList<>();
            // 师傅相关集合
            List<Long> workerIdList = new ArrayList<>();
            // 订单编号数据信息。
            List<Long> orderIdList = new ArrayList<>();
            for (OrderMaster orderMasterByListData : orderMasterList) {
                // 订单Id
                if (ObjectUtils.isNotNull(orderMasterByListData.getId())) {
                    orderIdList.add(orderMasterByListData.getId());
                }
                // 消费者id
                if (ObjectUtils.isNotNull(orderMasterByListData.getCustomerId())) {
                    customIdList.add(orderMasterByListData.getCustomerId());
                }
                // 师傅id
                if (ObjectUtils.isNotNull(orderMasterByListData.getWorkerId())) {
                    workerIdList.add(orderMasterByListData.getWorkerId());
                }
            }
            // 消费者
            Map<Long, Customer> longCustomerMap = customerService.byCustomerUseridInMap(customIdList);
            // 师傅
            Map<Long, Worker> longWorkerMap = workerService.byWorkUserIdInMap(workerIdList);
            // 订单数据
            Map<Long, List<OrderDetail>> longOrderDetailMap = orderDetailService.byOrderIdInMap(orderIdList);
            Map<Long, List<OrderGoods>> longOrderGoodsMap = orderGoodsService.byOrderIdInMap(orderIdList);
            // 消费者的上级邀请人信息。
            List<Long> customByPlaceIdList = new ArrayList<>();
            // 循环数据赋值。
            for (OrderMaster orderMasterByListData : orderMasterList) {
                OrderDetailsResponseVo orderDetailsResponseVo = new OrderDetailsResponseVo();
                // 订单基本信息。
                orderDetailsResponseVo.setOrderId(orderMasterByListData.getId());
                orderDetailsResponseVo.setCode(orderMasterByListData.getCode());
                // 基本信息。
                List<OrderGoods> orderGoodsList = longOrderGoodsMap.get(orderMasterByListData.getId());
                if (orderGoodsList != null && orderGoodsList.size() > 0) {
                    List<OrderDetailsResponseVo.OrderDetails> orderDetailsList = new ArrayList<>();
                    // 用于订单附表数据查询。
                    List<Long> orderDetailsIdList = new ArrayList<>();
                    for (OrderGoods orderGoods : orderGoodsList) {
                        orderDetailsIdList.add(orderGoods.getOrderId());
                    }
                    // 财务数据信息。
                    Map<Long, FinancialDetail> longFinancialDetailMap = financialDetailService.byOrderIdInMap(orderDetailsIdList);
                    for (OrderGoods orderGoods : orderGoodsList) {
                        OrderDetailsResponseVo.OrderDetails orderDetails = OrderDetailsResponseVo.OrderDetails.modelDataSupplement(orderGoods);
                        FinancialDetail financialDetail = longFinancialDetailMap.get(orderGoods.getOrderGoodsId());
                        if (ObjectUtils.isNotNull(financialDetail)) {
                            orderDetails.setDiscountMoney(financialDetail.getDiscountMoney());
                            orderDetails.setPayMoney(financialDetail.getPayMoney());
                            orderDetails.setTotalMoney(financialDetail.getTotalMoney());
                        }
                        orderDetailsList.add(orderDetails);
                    }
                    orderDetailsResponseVo.setDetailsList(orderDetailsList);
                }
                // 订单接单信息。 现在都取接单人。
                Worker workerByReceivingUser = longWorkerMap.get(orderMasterByListData.getWorkerId());
                Worker workerByOperationUser = longWorkerMap.get(orderMasterByListData.getWorkerId());
                orderDetailsResponseVo.setReceiving(OrderDetailsResponseVo.OrderReceiving.modelDataSupplement(workerByReceivingUser, workerByOperationUser));
                // 订单状态。
                orderDetailsResponseVo.setState(OrderDetailsResponseVo.OrderState.modelDataSupplement(orderMasterByListData));
                // 消费者相关。
                Customer customer = longCustomerMap.get(orderMasterByListData.getCustomerId());
                if (ObjectUtils.isNotNull(customer)) {
                    // 地址信息 这里默认取第一条数据既可以了
                    List<CustomerAddress> customerAddressList = customerAddressService.selectByCustomerId(customer.getCustomerId());
                    if (customerAddressList != null && customerAddressList.size() > 0) {
                        orderDetailsResponseVo.setCustomDetails(OrderDetailsResponseVo.OrderCustomDetails.modelDataSupplement(customerAddressList.get(0)));
                    }
                    customByPlaceIdList.add(customer.getCustomerPlace());
                }
                //  数据添加处理。
                orderDetailsResponseVoList.add(orderDetailsResponseVo);
            }
            // 第三次数据循环处理 用于邀请人相关补充，
            Map<Long, Customer> longCustomerByPlaceMap = customerService.byCustomerUseridInMap(customByPlaceIdList);
            for (OrderDetailsResponseVo vo : orderDetailsResponseVoList) {
                if (ObjectUtils.isNotNull(vo.getCustomDetails())) {
                    Customer customer = longCustomerByPlaceMap.get(vo.getCustomDetails().getCustomerId());
                    if (ObjectUtils.isNotNull(customer)) {
                        vo.setInvitee(OrderDetailsResponseVo.OrderInvitee.modelDataSupplement(customer));
                    }
                }
            }
        }
        return voDataTable(orderDetailsResponseVoList, 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) {
        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) {
        return toAjax(orderMasterService.updateOrderMaster(orderMaster));
    }

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