package com.ghy.web.controller.order;

import com.ghy.common.annotation.Log;
import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.page.PageDomain;
import com.ghy.common.core.page.TableDataInfo;
import com.ghy.common.core.page.TableSupport;
import com.ghy.common.enums.BusinessType;
import com.ghy.common.enums.ImgType;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.StringUtils;
import com.ghy.common.utils.poi.ExcelUtil;
import com.ghy.customer.domain.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.service.OrderDetailService;
import com.ghy.order.service.OrderGoodsService;
import com.ghy.order.service.OrderMasterService;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.service.FinancialMasterService;
import com.ghy.web.pojo.vo.OrderListResponse;
import com.ghy.web.pojo.vo.OrderMasterResponseVo;
import com.ghy.web.pojo.vo.OrderStandard;
import com.ghy.web.pojo.vo.OrderStandardDetail;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.domain.WorkerCertification;
import com.ghy.worker.service.IWorkerCertificationService;
import com.ghy.worker.service.WorkerService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.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 java.util.ArrayList;
import java.util.List;
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";

    @Autowired
    private OrderMasterService orderMasterService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private WorkerService workerService;
    @Autowired
    private IWorkerCertificationService workerCertificationService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private CustomerAddressService addressService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsImgsService goodsImgsService;
    @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) {
//        TableDataInfo rspData = new TableDataInfo();
        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 = 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());

            // 地址信息
            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 == null ? "" : worker.getName());
            orderListResponse.setWorkerPhone(worker == null ? "" : worker.getPhone());
            orderListResponse.setCustomerName(customer.getName());
            orderListResponse.setCustomerPhone(customer.getPhone());
            orderListResponse.setServerTime(master.getRevTime());
            orderListResponse.setExpectTimeStart(master.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(master.getExpectTimeEnd());
            orderListResponse.setOrderStatus(master.getOrderStatus());
            orderListResponse.setPayStatus(master.getPayStatus());
            orderListResponse.setPayType(master.getPayType());
            orderListResponse.setOrderMasterCode(master.getCode());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(customerAddress.getAddress());
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(master.getRemark());
            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/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());
                // 师傅实名信息
                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());
                }

                OrderStandardDetail orderStandardDetail = new OrderStandardDetail();
                orderStandardDetail.setOrderDetailId(orderDetail.getId());
                orderStandardDetail.setOrderDetailCode(orderDetail.getCode());
                orderStandardDetail.setWorkBeginTime(orderDetail.getWorkBeginTime());
                orderStandardDetail.setWorkFinishTime(orderDetail.getWorkFinishTime());
                orderStandardDetail.setWorkerName(detailWorkerRealInfo.getName());
                orderStandardDetail.setWorkerPhone(detailWorker.getPhone());
                orderStandardDetail.setRevTime(orderDetail.getRevTime());
                orderStandardDetail.setExpectTimeStart(orderDetail.getExpectTimeStart());
                orderStandardDetail.setExpectTimeEnd(orderDetail.getExpectTimeEnd());
                orderStandardDetail.setOrderStandardList(standardList);
                orderStandardDetail.setFinishImgList(finishImgList);
                orderStandardDetail.setRemark(orderDetail.getRemark());

                orderStandardDetails.add(orderStandardDetail);
            });

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

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

            // 师傅实名信息
            WorkerCertification workerRealInfo = workerCertificationService.selectByWorkerId(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(workerRealInfo == null ? "" : workerRealInfo.getName());
            orderListResponse.setWorkerPhone(worker == null ? "" : 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.setExpectTimeStart(orderMaster.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(orderMaster.getExpectTimeEnd());
            orderListResponse.setCreateTime(orderMaster.getCreateTime());
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(orderMaster.getRemark());
            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) {
        TableDataInfo rspData = new TableDataInfo();
        startPage();
        List<OrderMasterResponseVo> orderMasterResponseVos = new ArrayList<>();
        List<OrderMaster> orderMasterList = orderMasterService.selectOrderMasterList(orderMaster);
        for (OrderMaster master : orderMasterList) {
            OrderMasterResponseVo orderMasterResponseVo = new OrderMasterResponseVo();
            // 将公共属性复制过去
            BeanUtils.copyProperties(master, orderMasterResponseVo);
            // 师傅信息
            if (StringUtils.isNotNull(master.getWorkerId())) {
                Worker worker = workerService.selectById(master.getWorkerId());
                orderMasterResponseVo.setWorkerName(worker.getName());
            }
            // 消费者信息
            Customer customer = customerService.selectByCustomerId(master.getCustomerId());
            orderMasterResponseVo.setCustomerName(customer.getName());

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

    @Log(title = "主订单管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("order:master:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(OrderMaster orderMaster) {
        List<OrderMaster> list = orderMasterService.selectOrderMasterList(orderMaster);
        ExcelUtil<OrderMaster> util = new ExcelUtil<>(OrderMaster.class);
        return util.exportExcel(list, "主订单数据");
    }

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

    /**
     * 修改主订单
     */
    @RequiresPermissions("order:master:edit")
    @GetMapping("/edit/{orderMasterId}")
    public String edit(@PathVariable("orderMasterId") Long orderMasterId, ModelMap mmap) {
        mmap.put("orderMaster", orderMasterService.selectById(orderMasterId));
        return prefix + "/edit";
    }

    /**
     * 修改保存主订单
     */
    @RequiresPermissions("order:master:edit")
    @Log(title = "主订单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated OrderMaster orderMaster) throws BaseAdaPayException {
        if (UserConstants.ORDER_CODE_NOT_UNIQUE.equals(orderMasterService.checkOrderMasterCodeUnique(orderMaster))) {
            return error("修改主订单'" + orderMaster.getCode() + "'失败，主订单编码已存在");
        }
        orderMaster.setUpdateBy(getLoginName());
        return toAjax(orderMasterService.updateOrderMaster(orderMaster));
    }

    /**
     * 修改保存主订单信息
     */
    @PostMapping("/editOrderMaster")
    @ResponseBody
    public AjaxResult editOrderMaster(@RequestBody OrderMaster orderMaster) {
        try {
            int result = orderMasterService.updateOrderMaster(orderMaster);
            if (result > 0) {
                List<OrderDetail> orderDetails = orderDetailService.selectByOrderMasterId(orderMaster.getId());
                orderDetails.forEach(orderDetail -> {
                    orderDetail.setOrderStatus(orderMaster.getOrderStatus());
                    orderDetailService.updateOrderDetail(orderDetail);
                });
            }
            return AjaxResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("");
        }
    }

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

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

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