package com.cpxt.web.controller.biz;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cpxt.biz.domain.*;
import com.cpxt.biz.domain.vo.BizCustomerRouteVo;
import com.cpxt.biz.domain.vo.BizOrderSubVo;
import com.cpxt.biz.domain.vo.BizOrderVo;
import com.cpxt.biz.domain.vo.BizOrderVoCustomer;
import com.cpxt.biz.mapper.*;
import com.cpxt.common.constant.HttpStatus;
import com.cpxt.common.core.domain.entity.SysUser;
import com.cpxt.common.utils.SecurityUtils;
import com.cpxt.system.mapper.SysDictDataMapper;
import com.cpxt.system.service.ISysUserService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cpxt.common.annotation.Log;
import com.cpxt.common.core.controller.BaseController;
import com.cpxt.common.core.domain.AjaxResult;
import com.cpxt.common.enums.BusinessType;
import com.cpxt.biz.service.IBizOrderService;
import com.cpxt.common.utils.poi.ExcelUtil;
import com.cpxt.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 订单Controller
 *
 * @author YIN
 * @date 2024-12-16
 */
@RestController
@RequestMapping("/biz/order")
public class BizOrderController extends BaseController {
    @Autowired
    private IBizOrderService bizOrderService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private BizCustomerMapper bizCustomerMapper;

    @Autowired
    private BizCustomerRouteMapper bizCustomerRouteMapper;

    @Autowired
    private BizCustomerWarehouseMapper bizCustomerWarehouseMapper;

    @Autowired
    private BizCustomerShopMapper bizCustomerShopMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private BizOrderMapper bizOrderMapper;

    @Autowired
    private BizOrderSubMapper bizOrderSubMapper;

    /**
     * 查询订单列表（分页）
     */
//    @PreAuthorize("@ss.hasPermi('biz:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizOrder bizOrder,
                              @RequestParam(defaultValue = "1") int pageNum,
                              @RequestParam(defaultValue = "10") int pageSize) {
        Page<BizOrder> recordPage = bizOrderService.selectBizOrderPage(bizOrder, pageNum, pageSize);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(recordPage.getRecords());
        rspData.setTotal(recordPage.getTotal());
        return rspData;
    }

    /**
     * 查询订单列表
     */
//    @PreAuthorize("@ss.hasPermi('biz:order:list')")
    @GetMapping("/list2")
    public AjaxResult list(BizOrder bizOrder) {
        return AjaxResult.success(bizOrderService.selectBizOrderList(bizOrder));
    }

    /**
     * 查询订单列表（主驾司机或者副驾司机是当前用户 - 分页）
     */
    @GetMapping("/listByDriver")
    public TableDataInfo list(String orderStatus,
                              @RequestParam(defaultValue = "1") int pageNum,
                              @RequestParam(defaultValue = "10") int pageSize) {
        Page<BizOrder> recordPage = bizOrderService.selectBizOrderPageByDriver(orderStatus, pageNum, pageSize);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(recordPage.getRecords());
        rspData.setTotal(recordPage.getTotal());
        return rspData;
    }

    /**
     * 订单导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        SysUser user = sysUserService.selectUserById(SecurityUtils.getLoginUser().getUserId());
        if ("0".equals(user.getUserType())) {
            ExcelUtil<BizOrderVo> util = new ExcelUtil<BizOrderVo>(BizOrderVo.class);
            util.importTemplateExcel(response, "订单数据");
        } else {
            Workbook workbook = new XSSFWorkbook();
            // 创建订单数据Sheet
            Sheet sheet1 = workbook.createSheet("订单数据");
            setSheet1(sheet1);
            // 创建路线数据Sheet
            Sheet sheet2 = workbook.createSheet("路线数据");
            setSheet2(sheet2);
            // 创建仓库数据Sheet
            Sheet sheet3 = workbook.createSheet("仓库数据");
            setSheet3(sheet3);
            // 创建仓库数据Sheet
            Sheet sheet4 = workbook.createSheet("店铺数据");
            setSheet4(sheet4);
            // 创建物品类型Sheet
            Sheet sheet5 = workbook.createSheet("物品类型");
            setSheet5(sheet5);
            // 设置响应头，指定下载的文件名和内容类型
            response.setHeader("Content-Disposition", "attachment; filename=orders.xlsx");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            // 将工作簿写入响应输出流
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                workbook.write(outputStream);
            } finally {
                workbook.close();
            }
//            ExcelUtil<BizOrderVoCustomer> util = new ExcelUtil<BizOrderVoCustomer>(BizOrderVoCustomer.class);
//            util.importTemplateExcel(response, "订单数据");
        }
    }

    private void setSheet1(Sheet sheet1) {
        Row row0 = sheet1.createRow(0);
        Cell cell0 = row0.createCell(0);
        cell0.setCellValue("路线名称");
        Cell cell1 = row0.createCell(1);
        cell1.setCellValue("仓库名称");
        Cell cell2 = row0.createCell(2);
        cell2.setCellValue("店铺名称");
        Cell cell3 = row0.createCell(3);
        cell3.setCellValue("物品类型");
        Cell cell4 = row0.createCell(4);
        cell4.setCellValue("物品名称");
        Cell cell5 = row0.createCell(5);
        cell5.setCellValue("重量");
        Cell cell6 = row0.createCell(6);
        cell6.setCellValue("长");
        Cell cell7 = row0.createCell(7);
        cell7.setCellValue("宽");
        Cell cell8 = row0.createCell(8);
        cell8.setCellValue("高");
        Cell cell9 = row0.createCell(9);
        cell9.setCellValue("备注");
    }

    private void setSheet2(Sheet sheet2) {
        BizCustomer bizCustomer = bizCustomerMapper.selectByLinkPhone(SecurityUtils.getUsername());
        List<String> nameList = bizCustomerRouteMapper.selectNameByCustomerId(bizCustomer.getId());
        Row row0 = sheet2.createRow(0);
        Cell cell0 = row0.createCell(0);
        cell0.setCellValue("路线名称");
        for (int i = 0; i < nameList.size(); i++) {
            Row row = sheet2.createRow(i + 1);
            Cell cell = row.createCell(0);
            cell.setCellValue(nameList.get(i));
        }
    }

    private void setSheet3(Sheet sheet3) {
        BizCustomer bizCustomer = bizCustomerMapper.selectByLinkPhone(SecurityUtils.getUsername());
        List<BizCustomerWarehouse> warehouseList = bizCustomerWarehouseMapper.selectByCustomerId(bizCustomer.getId());
        Row row0 = sheet3.createRow(0);
        Cell cell0 = row0.createCell(0);
        cell0.setCellValue("仓库名称");
        Cell cell1 = row0.createCell(1);
        cell1.setCellValue("联系人");
        Cell cell2 = row0.createCell(2);
        cell2.setCellValue("联系电话");
        Cell cell3 = row0.createCell(3);
        cell3.setCellValue("仓库地址");
        for (int i = 0; i < warehouseList.size(); i++) {
            Row row = sheet3.createRow(i + 1);
            Cell cell = row.createCell(0);
            cell.setCellValue(warehouseList.get(i).getName());
            Cell cell11 = row.createCell(1);
            cell11.setCellValue(warehouseList.get(i).getLinkman());
            Cell cell22 = row.createCell(2);
            cell22.setCellValue(warehouseList.get(i).getLinkphone());
            Cell cell33 = row.createCell(3);
            cell33.setCellValue(warehouseList.get(i).getAddress());
        }
    }

    private void setSheet4(Sheet sheet4) {
        BizCustomer bizCustomer = bizCustomerMapper.selectByLinkPhone(SecurityUtils.getUsername());
        List<BizCustomerShop> shopList = bizCustomerShopMapper.selectByCustomerId(bizCustomer.getId());
        Row row0 = sheet4.createRow(0);
        Cell cell0 = row0.createCell(0);
        cell0.setCellValue("店铺名称");
        Cell cell1 = row0.createCell(1);
        cell1.setCellValue("联系人");
        Cell cell2 = row0.createCell(2);
        cell2.setCellValue("联系电话");
        Cell cell3 = row0.createCell(3);
        cell3.setCellValue("店铺地址");
        for (int i = 0; i < shopList.size(); i++) {
            Row row = sheet4.createRow(i + 1);
            Cell cell = row.createCell(0);
            cell.setCellValue(shopList.get(i).getName());
            Cell cell11 = row.createCell(1);
            cell11.setCellValue(shopList.get(i).getLinkman());
            Cell cell22 = row.createCell(2);
            cell22.setCellValue(shopList.get(i).getLinkphone());
            Cell cell33 = row.createCell(3);
            cell33.setCellValue(shopList.get(i).getAddress());
        }
    }

    private void setSheet5(Sheet sheet5) {
        List<String> nameList = sysDictDataMapper.selectLabelByType("sys_goods_type");
        Row row0 = sheet5.createRow(0);
        Cell cell0 = row0.createCell(0);
        cell0.setCellValue("物品类型");
        for (int i = 0; i < nameList.size(); i++) {
            Row row = sheet5.createRow(i + 1);
            Cell cell = row.createCell(0);
            cell.setCellValue(nameList.get(i));
        }
    }

    @Log(title = "订单管理", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        SysUser user = sysUserService.selectUserById(SecurityUtils.getLoginUser().getUserId());
        String message;
        if ("0".equals(user.getUserType())) {
            ExcelUtil<BizOrderVo> util = new ExcelUtil<BizOrderVo>(BizOrderVo.class);
            List<BizOrderVo> orderList = util.importExcel(file.getInputStream());
            message = bizOrderService.importOrder(orderList, updateSupport);
        } else {
            ExcelUtil<BizOrderVoCustomer> util = new ExcelUtil<BizOrderVoCustomer>(BizOrderVoCustomer.class);
            List<BizOrderVoCustomer> orderList = util.importExcel(file.getInputStream());
            message = bizOrderService.importOrderCustomer(orderList, updateSupport);
        }
        return success(message);
    }

    /**
     * 导出订单列表
     */
//    @PreAuthorize("@ss.hasPermi('biz:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizOrder bizOrder) {
        List<Long> importIdList = bizOrder.getImportIdList();
        if (bizOrder.getImportType().equals("1")){
            // 导出订单
            if (importIdList != null && importIdList.size() != 0){
                // 导出选中订单
                LambdaQueryWrapper<BizOrder> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(BizOrder::getId,importIdList);
                List<BizOrder> list = bizOrderMapper.selectList(queryWrapper);
                ExcelUtil<BizOrder> util = new ExcelUtil<BizOrder>(BizOrder.class);
                util.exportExcel(response, list, "订单数据");
            }else {
                // 导出当前条件订单
                List<BizOrder> list = bizOrderService.selectBizOrderList(bizOrder);
                ExcelUtil<BizOrder> util = new ExcelUtil<BizOrder>(BizOrder.class);
                util.exportExcel(response, list, "订单数据");
            }
        }else {
            // 导出该订单下的运单
            if (importIdList != null && importIdList.size() != 0){
                // 导出选中订单下的运单
                LambdaQueryWrapper<BizOrder> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(BizOrder::getId,importIdList);
                List<BizOrder> list = bizOrderMapper.selectList(queryWrapper);
                List<String> orderSnList = list.stream().map(BizOrder::getOrderSn).collect(Collectors.toList());
                LambdaQueryWrapper<BizOrderSub> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.in(BizOrderSub::getOrderSn,orderSnList);
                List<BizOrderSub> bizOrderSubList = bizOrderSubMapper.selectList(queryWrapper1);
                List<BizOrderSubVo> bizOrderSubVoList = new ArrayList<>();
                for (BizOrderSub bizOrderSub : bizOrderSubList) {
                    BizOrder bizOrder1 = bizOrderMapper.selectByOrderSn(bizOrderSub.getOrderSn());
                    BizOrderSubVo bizOrderSubVo = new BizOrderSubVo();
                    BeanUtils.copyProperties(bizOrder1,bizOrderSubVo);
                    bizOrderSubVo.setSubOrderSn(bizOrderSub.getSubOrderSn());
                    bizOrderSubVo.setSubWeight(bizOrderSub.getWeight());
                    bizOrderSubVo.setSubVolume(bizOrderSub.getVolume());
                    bizOrderSubVo.setSubLength(bizOrderSub.getLength());
                    bizOrderSubVo.setSubWidth(bizOrderSub.getWidth());
                    bizOrderSubVo.setSubHeight(bizOrderSub.getHeight());
                    bizOrderSubVo.setSubGoodsType(bizOrderSub.getGoodsType());
                    bizOrderSubVo.setSubGoodsName(bizOrderSub.getGoodsName());
                    bizOrderSubVo.setSubOrderFee(bizOrderSub.getOrderFee());
                    bizOrderSubVo.setSubRemark(bizOrderSub.getRemark());
                    bizOrderSubVoList.add(bizOrderSubVo);
                }
                ExcelUtil<BizOrderSubVo> util = new ExcelUtil<BizOrderSubVo>(BizOrderSubVo.class);
                util.exportExcel(response, bizOrderSubVoList, "订单及运单数据");
            }else {
                // 导出当前条件下订单的运单
                List<BizOrder> list = bizOrderService.selectBizOrderList(bizOrder);
                List<String> orderSnList = list.stream().map(BizOrder::getOrderSn).collect(Collectors.toList());
                LambdaQueryWrapper<BizOrderSub> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.in(BizOrderSub::getOrderSn,orderSnList);
                List<BizOrderSub> bizOrderSubList = bizOrderSubMapper.selectList(queryWrapper1);
                List<BizOrderSubVo> bizOrderSubVoList = new ArrayList<>();
                for (BizOrderSub bizOrderSub : bizOrderSubList) {
                    BizOrder bizOrder1 = bizOrderMapper.selectByOrderSn(bizOrderSub.getOrderSn());
                    BizOrderSubVo bizOrderSubVo = new BizOrderSubVo();
                    BeanUtils.copyProperties(bizOrder1,bizOrderSubVo);
                    bizOrderSubVo.setSubOrderSn(bizOrderSub.getSubOrderSn());
                    bizOrderSubVo.setSubWeight(bizOrderSub.getWeight());
                    bizOrderSubVo.setSubVolume(bizOrderSub.getVolume());
                    bizOrderSubVo.setSubLength(bizOrderSub.getLength());
                    bizOrderSubVo.setSubWidth(bizOrderSub.getWidth());
                    bizOrderSubVo.setSubHeight(bizOrderSub.getHeight());
                    bizOrderSubVo.setSubGoodsType(bizOrderSub.getGoodsType());
                    bizOrderSubVo.setSubGoodsName(bizOrderSub.getGoodsName());
                    bizOrderSubVo.setSubOrderFee(bizOrderSub.getOrderFee());
                    bizOrderSubVo.setSubRemark(bizOrderSub.getRemark());
                    bizOrderSubVoList.add(bizOrderSubVo);
                }
                ExcelUtil<BizOrderSubVo> util = new ExcelUtil<BizOrderSubVo>(BizOrderSubVo.class);
                util.exportExcel(response, bizOrderSubVoList, "订单及运单数据");
            }
        }

    }

    /**
     * 获取订单详细信息
     */
//    @PreAuthorize("@ss.hasPermi('biz:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizOrderService.selectBizOrderById(id));
    }

    /**
     * 新增订单
     */
//    @PreAuthorize("@ss.hasPermi('biz:order:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizOrder bizOrder) {
        return toAjax(bizOrderService.insertBizOrder(bizOrder));
    }

    /**
     * 新增订单子单
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/sub/add")
    public AjaxResult add(@RequestBody Map map) {
        bizOrderService.insertBizOrderSub(map);
        return AjaxResult.success();
    }

    /**
     * 修改订单
     */
//    @PreAuthorize("@ss.hasPermi('biz:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizOrder bizOrder) {
        return toAjax(bizOrderService.updateBizOrder(bizOrder));
    }

    /**
     * 删除订单
     */
//    @PreAuthorize("@ss.hasPermi('biz:order:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bizOrderService.deleteBizOrderByIds(ids));
    }


    /**
     * 去配送
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/goDelivery")
    public AjaxResult goDelivery(@RequestBody Map map) {

        return toAjax(bizOrderService.goDelivery(map));
    }

    /**
     * 已到达
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/arrived")
    public AjaxResult arrived(@RequestBody Map map) {
        return toAjax(bizOrderService.arrived(map));
    }

    /**
     * app当前司机订单统计
     */
    @GetMapping("/statics")
    public AjaxResult statics() {
        return AjaxResult.success(bizOrderService.getOrderStaticsByDriver());
    }
}
