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.enums.ImgType;
import com.ghy.common.enums.OrderStatus;
import com.ghy.common.enums.PayStatus;
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.GoodsImgs;
import com.ghy.goods.domain.GoodsStandard;
import com.ghy.goods.service.GoodsImgsService;
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.request.OrderProcessRequest;
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.service.FinancialDetailService;
import com.ghy.system.domain.SysArea;
import com.ghy.system.service.ISysAreaService;
import com.ghy.web.pojo.vo.OrderListResponse;
import com.ghy.web.pojo.vo.OrderStandard;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.service.WorkerService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
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.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 详细订单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 ISysAreaService sysAreaService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsImgsService goodsImgsService;
    @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());
            SysArea sysArea = sysAreaService.selectById(customerAddress.getCountryId());
            String completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();

            // 完工图片
            List<String> finishImgList = null;
            if (detail.getOrderStatus() > 3) {
                GoodsImgs qryImgsObj = new GoodsImgs();
                qryImgsObj.setRemark(request.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());
            }

            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(completeAddress);
            orderListResponse.setServerTime(detail.getRevTime());
            orderListResponse.setExpectTimeStart(detail.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(detail.getExpectTimeEnd());
            orderListResponse.setCreateTime(detail.getCreateTime());
            orderListResponse.setWorkBeginTime(detail.getWorkBeginTime());
            orderListResponse.setWorkFinishTime(detail.getWorkFinishTime());
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(orderMaster.getRemark());
            orderListResponse.setFinishImgList(finishImgList);
            orderListResponse.setWorkerRemark(detail.getRemark());

            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());
            SysArea sysArea = sysAreaService.selectById(customerAddress.getCountryId());
            String completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();

            for (OrderGoods orderGoods : orderStandardList) {
                OrderStandard orderStandard = new OrderStandard();
                orderStandard.setStandardName(orderGoods.getGoodsName());
                orderStandard.setStandardNum(orderGoods.getGoodsNum());
                orderStandard.setServerNum(orderGoods.getServerGoodsNum());
                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(completeAddress);
            orderListResponse.setServerTime(detail.getRevTime());
            orderListResponse.setExpectTimeStart(detail.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(detail.getExpectTimeEnd());
            orderListResponse.setWorkBeginTime(detail.getWorkBeginTime());
            orderListResponse.setWorkFinishTime(detail.getWorkFinishTime());
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(orderMaster.getRemark());
            orderListResponse.setOrderType(detail.getOrderType());
            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);
    }

    /**
     * 消费者确认完成子订单
     *
     * @param orderDetailId 子订单ID
     */
    @PostMapping("/finish")
    @ResponseBody
    public AjaxResult finish(Long orderDetailId) {
        try {
            orderDetailService.finish(orderDetailId);
        } catch (BaseAdaPayException e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("操作失败，请稍后重试");
        }
        return AjaxResult.success();
    }

    /**
     * 消费者申请取消子订单
     *
     * @param orderDetailId 子订单ID
     */
    @PostMapping("/cancel")
    @ResponseBody
    public AjaxResult cancel(Long orderDetailId) {
        orderDetailService.cancel(orderDetailId);
        return AjaxResult.success();
    }

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

    /**
     * 师傅发起完单
     *
     * @param request 完单发起请求对象
     */
    @PostMapping("/app/applyFinishOrder")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult applyFinishOrder(@RequestBody OrderProcessRequest request) throws Exception {
        // 判断工单状态是否为服务中以及是否已支付
        OrderDetail orderDetail = orderDetailService.selectById(request.getOrderDetailId());
        OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
        if (orderDetail.getOrderStatus() != OrderStatus.SERVER.code()
            || orderMaster.getPayStatus() != PayStatus.PAID.getCode()) {
            return AjaxResult.error("未支付订单或非服务中订单，发起完单失败");
        }

        // 存储完单图
        List<GoodsImgs> finishImgObjList = new ArrayList<GoodsImgs>();
        for (String imgUrl: request.getFinishImgList()) {
            GoodsImgs finishImgObj = new GoodsImgs();
            finishImgObj.setGoodsId(0l);
            finishImgObj.setImgType(ImgType.FINISH_IMG.getId());
            finishImgObj.setImgUrl(imgUrl);
            finishImgObj.setRemark(String.valueOf(request.getOrderDetailId()));
            finishImgObjList.add(finishImgObj);
        }
        int insertedRows = goodsImgsService.batchInsert(finishImgObjList);
        Assert.isTrue(insertedRows > 0, "完单图入库失败，request=" + request);

        // 修改子单状态为完单待确认状态，更新完单时间
        OrderDetail updateOrderDetail = new OrderDetail();
        updateOrderDetail.setId(request.getOrderDetailId());
        updateOrderDetail.setWorkFinishTime(new Date());
        updateOrderDetail.setOrderStatus(OrderStatus.FINISH_CHECK.code());
        updateOrderDetail.setRemark(request.getRemark());
        int affectedRow = orderDetailService.updateOrderDetail(updateOrderDetail);
        Assert.isTrue(affectedRow == 1, "子订单修改失败，orderDetail=" + orderDetail);

        return AjaxResult.success("发起成功");
    }
}
