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.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.web.pojo.vo.OrderListResponse;
import com.ghy.web.pojo.vo.OrderStandard;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.service.WorkerService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.List;

/**
 * 详细订单API
 *
 * @author HH 2022/4/25
 */
@Controller
@RequestMapping("/order/detail")
public class OrderDetailController extends BaseController {

    private final String prefix = "order/detail";

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

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

//    @RequiresPermissions("order:detail:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(OrderDetail orderDetail) {
        startPage();
        List<OrderDetail> orderDetailList = orderDetailService.selectOrderDetailList(orderDetail);
        return getDataTable(orderDetailList);
    }

    @PostMapping("/app/detail")
    @ResponseBody
    public AjaxResult appDetail(@RequestBody OrderDetail request){
        try {
            // 子单信息
            OrderDetail detail = orderDetailService.selectById(request.getId());
            // 主单信息
            OrderMaster orderMaster = orderMasterService.selectById(detail.getOrderMasterId());
            // 初始化属性
            OrderListResponse orderListResponse = new OrderListResponse();
            List<OrderStandard> standardList = new ArrayList<>();

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

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

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

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

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

            // 财务信息
            FinancialDetail financialDetail = financialDetailService.selectByOrderDetailId(detail.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.setOrderDetailId(detail.getId());
            orderListResponse.setOrderDetailCode(detail.getCode());
            orderListResponse.setOrderMasterId(detail.getOrderMasterId());
            orderListResponse.setOrderMasterCode(detail.getOrderMasterCode());
            orderListResponse.setGoodsName(goods.getGoodsName());
            orderListResponse.setGoodsLogoUrl(goods.getGoodsImgUrl());
            orderListResponse.setDiscountMoney(financialDetail.getDiscountMoney());
            orderListResponse.setTotalMoney(financialDetail.getTotalMoney());
            orderListResponse.setPayMoney(financialDetail.getPayMoney());
            orderListResponse.setWorkerName(worker.getName());
            orderListResponse.setWorkerPhone(worker.getPhone());
            orderListResponse.setCustomerName(customer.getName());
            orderListResponse.setCustomerPhone(customer.getPhone());
            orderListResponse.setOrderStatus(detail.getOrderStatus());
            orderListResponse.setPayStatus(orderMaster.getPayStatus());
            orderListResponse.setPayType(orderMaster.getPayType());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(customerAddress.getAddress());
            orderListResponse.setServerTime(detail.getRevTime());
            orderListResponse.setCreateTime(detail.getCreateTime());
            orderListResponse.setWorkBeginTime(detail.getWorkBeginTime());
            orderListResponse.setWorkFinishTime(detail.getWorkFinishTime());

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

    @PostMapping("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestBody OrderDetail orderDetail){

        startPage();
        List<OrderListResponse> orderListResponses = new ArrayList<>();
        List<OrderDetail> list = orderDetailService.selectOrderDetailList(orderDetail);
        list.forEach(detail->{

            // 主单信息
            OrderMaster orderMaster = orderMasterService.selectById(detail.getOrderMasterId());
            // 初始化属性
            OrderListResponse orderListResponse = new OrderListResponse();
            List<OrderStandard> standardList = new ArrayList<>();

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

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

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

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

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

            // 财务信息
            FinancialDetail financialDetail = financialDetailService.selectByOrderDetailId(detail.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());
                orderStandard.setFinishTime(orderGoods.getFinishTime());
                orderStandard.setWaitServerNum(orderGoods.getGoodsNum() - orderGoods.getServerGoodsNum());
                standardList.add(orderStandard);
            }

            // 编辑返回属性
            orderListResponse.setOrderDetailId(detail.getId());
            orderListResponse.setOrderDetailCode(detail.getCode());
            orderListResponse.setOrderMasterId(detail.getOrderMasterId());
            orderListResponse.setOrderMasterCode(detail.getOrderMasterCode());
            orderListResponse.setGoodsName(goods.getGoodsName());
            orderListResponse.setGoodsLogoUrl(goods.getGoodsImgUrl());
            orderListResponse.setDiscountMoney(financialDetail.getDiscountMoney());
            orderListResponse.setTotalMoney(financialDetail.getTotalMoney());
            orderListResponse.setPayMoney(financialDetail.getPayMoney());
            orderListResponse.setWorkerName(worker.getName());
            orderListResponse.setWorkerPhone(worker.getPhone());
            orderListResponse.setCustomerName(customer.getName());
            orderListResponse.setCustomerPhone(customer.getPhone());
            orderListResponse.setOrderStatus(detail.getOrderStatus());
            orderListResponse.setPayStatus(orderMaster.getPayStatus());
            orderListResponse.setPayType(orderMaster.getPayType());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(customerAddress.getAddress());
            orderListResponse.setServerTime(detail.getRevTime());
            orderListResponse.setWorkBeginTime(detail.getWorkBeginTime());
            orderListResponse.setWorkFinishTime(detail.getWorkFinishTime());
            orderListResponses.add(orderListResponse);
        });
        return voDataTable(orderListResponses, list);
    }

    @Log(title = "详细订单管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("order:detail:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(OrderDetail orderDetail) {
        List<OrderDetail> list = orderDetailService.selectOrderDetailList(orderDetail);
        ExcelUtil<OrderDetail> util = new ExcelUtil<>(OrderDetail.class);
        return util.exportExcel(list, "详细订单数据");
    }

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

    /**
     * 修改详细订单
     */
    @RequiresPermissions("order:detail:edit")
    @GetMapping("/edit/{orderDetailId}")
    public String edit(@PathVariable("orderDetailId") Long orderDetailId, ModelMap mmap) {
        mmap.put("orderDetail", orderDetailService.selectById(orderDetailId));
        return prefix + "/edit";
    }

    /**
     * 修改保存详细订单
     */
    @RequiresPermissions("order:detail:edit")
    @Log(title = "详细订单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated OrderDetail orderDetail) {
        if (UserConstants.ORDER_CODE_NOT_UNIQUE.equals(orderDetailService.checkOrderDetailCodeUnique(orderDetail))) {
            return error("修改详细订单'" + orderDetail.getCode() + "'失败，详细订单编码已存在");
        }
        orderDetail.setUpdateBy(getLoginName());
        return toAjax(orderDetailService.updateOrderDetail(orderDetail));
    }

    /**
     * 修改保存详细订单
     */
    @PostMapping("/app/edit")
    @ResponseBody
    public AjaxResult appEdit(@RequestBody OrderDetail orderDetail) {
        if (UserConstants.ORDER_CODE_NOT_UNIQUE.equals(orderDetailService.checkOrderDetailCodeUnique(orderDetail))) {
            return error("修改详细订单'" + orderDetail.getCode() + "'失败，详细订单编码已存在");
        }
        return toAjax(orderDetailService.updateOrderDetail(orderDetail));
    }

    /**
     * 校验详细订单编码
     */
    @PostMapping("/checkOrderDetailCodeUnique")
    @ResponseBody
    public String checkOrderDetailCodeUnique(OrderDetail orderDetail) {
        return orderDetailService.checkOrderDetailCodeUnique(orderDetail);
    }
}
