package cn.iocoder.yudao.module.inspection.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.core.text.Convert;
import cn.iocoder.yudao.module.core.text.ServletUtils;
import cn.iocoder.yudao.module.label.vo.LabelRespVO;
import cn.iocoder.yudao.module.partner.entity.PartnerCustomerInfo;
import cn.iocoder.yudao.module.partner.service.IPartnerCustomerInfoService;
import cn.iocoder.yudao.module.partner.service.IPartnerWorkerService;
import cn.iocoder.yudao.module.payment.service.OrderInfoService;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import cn.iocoder.yudao.module.core.controller.BaseController;
import cn.iocoder.yudao.util.StringUtils;
import cn.iocoder.yudao.module.inspection.entity.InspectionInfo;
import cn.iocoder.yudao.module.partner.entity.PartnerWorker;
import cn.iocoder.yudao.module.payment.entity.OrderInfo;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import cn.iocoder.yudao.module.shop.service.IShopMallPartnersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/admin-api/system/inspectionMallPartners")
public class InspectionMallPartnersController extends BaseController {
    @Autowired
    private IShopMallPartnersService shopMallPartnersService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private IPartnerWorkerService partnerWorkerService;
    @Autowired
    private DictDataService dictDataService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private IPartnerCustomerInfoService partnerCustomerInfoService;

    /**
     * 查询合作商管理列表
     */
    @GetMapping("/list")
    public CommonResult list(ShopMallPartners shopMallPartners,
                             @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                             @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize)
    {
        shopMallPartners.setType("jc");
        Page<ShopMallPartners> page = new Page<>(pageNum, pageSize);
        IPage<ShopMallPartners> list = shopMallPartnersService.selectShopMallPartnersList(page,shopMallPartners);
        return success(list);
    }


    /**
     * 查询合作商管理列表
     */
    @GetMapping("/listComment")
    public CommonResult listComment(Long partnerId,
                                    @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                                    @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize)
    {
        Page<OrderInfo> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<OrderInfo> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.select(OrderInfo::getGoodsTitle,OrderInfo::getCommentDesc,OrderInfo::getCommentTime,OrderInfo::getCommentStar,OrderInfo::getRealName,OrderInfo::getId).eq(OrderInfo::getPartnerId,partnerId).orderByDesc(OrderInfo::getCommentTime).isNotNull(OrderInfo::getCommentTime);

        IPage<OrderInfo> list = orderInfoService.page(page,queryWrapper);
        return success(list);
    }

    /**
     * 删除评论
     */
    @PostMapping("/delCommentByOrderId")
    public CommonResult delCommentByOrderId(Long orderId)
    {
        LambdaUpdateWrapper<OrderInfo> queryWrapper =new LambdaUpdateWrapper<>();
        queryWrapper.eq(OrderInfo::getId,orderId).set(OrderInfo::getCommentTime,null).set(OrderInfo::getCommentDesc,"").set(OrderInfo::getCommentStar,null);
        orderInfoService.update(queryWrapper);
        return success();
    }

    /**
     * 工单管理
     */
    @GetMapping("/workOrder")
    public CommonResult<IPage<?>> workOrder(String carNum,String goodsTitle,String customerSource,String payType,String startTime,Long roleId,String endTime,Integer pageSize,Integer pageNum)
    {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        List<String> roles = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());
        ShopMallPartners partner  = new ShopMallPartners();
        if (roles.contains("jcshop")){
            LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(ShopMallPartners::getUserId,user.getId()).eq(ShopMallPartners::getType,"jc").eq(ShopMallPartners::getIsBanned,"0");
            partner = shopMallPartnersService.getOne(queryWrapper);
            if (ObjectUtil.isEmpty(partner)){
                return error();
            }
        }else if (roles.contains("jcworker")){
            LambdaQueryWrapper<PartnerWorker> queryWrapperWork =new LambdaQueryWrapper<>();
            queryWrapperWork.eq(PartnerWorker::getUserId,user.getId());
            PartnerWorker worker = partnerWorkerService.getOne(queryWrapperWork);
            if (ObjectUtil.isEmpty(worker)){
                return error();
            }
            partner.setPartnerId(worker.getPartnerId());
        }
        Page<InspectionInfo> page = new Page<>(pageNum, pageSize);
        IPage<InspectionInfo> list = orderInfoService.pageWorkOrder(partner.getPartnerId(),carNum,goodsTitle, customerSource, payType,startTime,roleId,endTime,page);
        return CommonResult.success(list);
    }



    @GetMapping("/delWorkOrder")
    public CommonResult<IPage<?>> delWorkOrder(String carNum,String goodsTitle,String customerSource,String payType,String startTime,Long roleId,String endTime,Integer pageSize,Integer pageNum)
    {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);

        List<String> roles = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());

        ShopMallPartners partner  = new ShopMallPartners();
        if (roles.contains("jcshop")){
            LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(ShopMallPartners::getUserId,user.getId()).eq(ShopMallPartners::getType,"jc").eq(ShopMallPartners::getIsBanned,"0");
            partner = shopMallPartnersService.getOne(queryWrapper);
            if (ObjectUtil.isEmpty(partner)){
                return error();
            }
        }else if (roles.contains("jcworker")){
            LambdaQueryWrapper<PartnerWorker> queryWrapperWork =new LambdaQueryWrapper<>();
            queryWrapperWork.eq(PartnerWorker::getUserId,user.getId());
            PartnerWorker worker = partnerWorkerService.getOne(queryWrapperWork);
            if (ObjectUtil.isEmpty(worker)){
                return error();
            }
            partner.setPartnerId(worker.getPartnerId());
        }
//        Page<InspectionInfo> page = new Page<>(pageNum,pageSize);
        Page<InspectionInfo> page = new Page<>(pageNum, pageSize);

//        List<InspectionInfo> list = orderInfoService.delworkOrder(partner.getPartnerId(),carNum,goodsTitle, customerSource, payType,startTime,roleId,endTime);
        IPage<InspectionInfo> list = orderInfoService.pageWorkOrder(partner.getPartnerId(),carNum,goodsTitle, customerSource, payType,startTime,roleId,endTime,page);

        return CommonResult.success(list);
    }

    @PostMapping("/exportWorkOrder")
    public void exportWorkOrder(String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime, HttpServletResponse response) throws IOException {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);

        List<String> roles = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());
        ShopMallPartners partner  = new ShopMallPartners();
        if (roles.contains("jcshop")){
            LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(ShopMallPartners::getUserId,user.getId()).eq(ShopMallPartners::getType,"jc").eq(ShopMallPartners::getIsBanned,"0");
            partner = shopMallPartnersService.getOne(queryWrapper);
            if (ObjectUtil.isEmpty(partner)){
                return;
            }
        }else if (roles.contains("jcworker")){
            LambdaQueryWrapper<PartnerWorker> queryWrapperWork =new LambdaQueryWrapper<>();
            queryWrapperWork.eq(PartnerWorker::getUserId,user.getId());
            PartnerWorker worker = partnerWorkerService.getOne(queryWrapperWork);
            if (ObjectUtil.isEmpty(worker)){
                return;
            }
            partner.setPartnerId(worker.getPartnerId());
        }
        int pageNum = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        int pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        Page<InspectionInfo> page = new Page<>(pageNum,pageSize);
        List<InspectionInfo> list = orderInfoService.workOrder(partner.getPartnerId(),carNum,goodsTitle, customerSource, payType,startTime,roleId,endTime);
        List<List<String>> rows =new ArrayList<>();
        Map<String, Object> stringObjectMap = orderInfoService.workOrderData(partner.getPartnerId(), carNum, goodsTitle, customerSource, payType, startTime, roleId, endTime);

        rows.add(CollUtil.newArrayList("公示价格汇总:","",String.valueOf(Double.parseDouble(stringObjectMap.get("goodsPriceSum").toString())/100d)+"元","实付金额汇总:","",String.valueOf(Double.parseDouble(stringObjectMap.get("payMoneySum").toString())/100d)+"元"));
        rows.add(CollUtil.newArrayList("车牌号", "检测类型", "检测项目", "公示价格","实收金额","付款时间","客户手机号","接待员手机号","客户来源","支付方式","开始时间","结束时间","检测结果","备注"));


        List<DictDataDO> sysDictData = dictDataService.getDictDataListByDictType("pay_type");
        Map<String,String> payMap =new HashMap<>();
        for (DictDataDO it : sysDictData) {
            payMap.put(it.getValue(),it.getLabel());
        }
        for (InspectionInfo item : list) {
            String isPassStr ="";
            if (StringUtils.isEmpty(item.getIsPass())){
                isPassStr = "进行中";
            }else{
                if (item.getIsPass().equals("0")){
                    isPassStr = "不合格";
                }else {
                    isPassStr = "合格";
                }

            }
            String payTypeStr ="";
            if (StringUtils.isEmpty(item.getPayType())){
                payTypeStr = "";
            }else{
                payTypeStr = payMap.get(item.getPayType());

            }

            rows.add(CollUtil.newArrayList(Optional.ofNullable(item.getCarNum()).orElse(""), Optional.ofNullable(item.getGoodsTitle()).orElse("") ,Optional.ofNullable(item.getSkuName()).orElse("") ,ObjectUtil.isEmpty(item.getGoodsPrice())?"":String.valueOf(item.getGoodsPrice()/100),ObjectUtil.isEmpty(item.getRealPayMoney())?"":String.valueOf(item.getRealPayMoney()/100), ObjectUtil.isEmpty(item.getPayTime())?"":DateUtil.format(item.getPayTime(),"yyyy-MM-dd hh:mm"),
                    Optional.ofNullable(item.getBuyPhone()).orElse(""), Optional.ofNullable(item.getWorkerPhone()).orElse("") , Optional.ofNullable(item.getCustomerSource()).orElse("") , payTypeStr,  ObjectUtil.isEmpty(item.getStartTime())?"":DateUtil.format(item.getStartTime(),"yyyy-MM-dd hh:mm"), ObjectUtil.isEmpty(item.getEndTime())?"":DateUtil.format(item.getEndTime(),"yyyy-MM-dd hh:mm"), isPassStr,
                    Optional.ofNullable(item.getRemark()).orElse("")));
        }

        ExcelWriter writer = ExcelUtil.getWriter();
        //跳过当前行，既第一行，非必须，在此演示用
        //合并单元格后的标题行，使用默认标题样式
        //一次性写出内容，强制输出标题
        writer.write(rows, true);
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename=test.xls");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }



    @GetMapping("/workOrderData")
    public CommonResult workOrderData(String carNum,String goodsTitle,String customerSource,String payType,String startTime,Long roleId,String endTime,Integer pageSize,Integer pageNum)
    {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);

        List<String> roles = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());
        ShopMallPartners partner  = new ShopMallPartners();
        if (roles.contains("jcshop")){
            LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(ShopMallPartners::getUserId,user.getId()).eq(ShopMallPartners::getType,"jc").eq(ShopMallPartners::getIsBanned,"0");
            partner = shopMallPartnersService.getOne(queryWrapper);
            if (ObjectUtil.isEmpty(partner)){
                return CommonResult.error(-1,"信息有误");
            }
        }else if (roles.contains("jcworker")){
            LambdaQueryWrapper<PartnerWorker> queryWrapperWork =new LambdaQueryWrapper<>();
            queryWrapperWork.eq(PartnerWorker::getUserId,user.getId());
            PartnerWorker worker = partnerWorkerService.getOne(queryWrapperWork);
            if (ObjectUtil.isEmpty(worker)){
                return CommonResult.error(-1,"信息有误");
            }
            partner.setPartnerId(worker.getPartnerId());
        }
        return success(orderInfoService.workOrderData(partner.getPartnerId(),carNum,goodsTitle, customerSource, payType,startTime,roleId,endTime));
    }
    /**
     * 修改数据
     * @return 修改结果
     */
    @PostMapping("/add")
    public CommonResult add(@RequestBody ShopMallPartners shopMallPartners) {
        shopMallPartners.setType("jc");
        this.shopMallPartnersService.insertShopMallPartners(shopMallPartners);
        return success();
    }
    /**
     * 修改数据
     * @return 修改结果
     */
    @PostMapping("/edit")
    public CommonResult update(@RequestBody ShopMallPartners shopMallPartners) {
        this.shopMallPartnersService.updateShopMallPartners(shopMallPartners);
        return success();
    }

    /**
     * 设置店主
     * @return 修改结果
     */
    @PostMapping("/setShopAdmin")
    public CommonResult setShopAdmin(@RequestBody ShopMallPartners shopMallPartners) {
        this.shopMallPartnersService.setShopAdmin(shopMallPartners);
        return success();
    }
    /**
     * 封禁 解禁
     * @return 修改结果
     */
    @PostMapping("/banned")
    public CommonResult banned(@RequestBody ShopMallPartners shopMallPartner) {
        ShopMallPartners shopMallPartners = this.shopMallPartnersService.selectShopMallPartnersByPartnerId(shopMallPartner.getPartnerId());
        shopMallPartners.setIsBanned(shopMallPartner.getIsBanned());
        shopMallPartnersService.updateShopMallPartners(shopMallPartners);
        return success();
    }
    /**
     * 删除合作商管理
     */
    @PostMapping("/del")
    public CommonResult remove(@RequestParam("idList") Long[] idList)
    {
        return toAjax(shopMallPartnersService.deleteShopMallPartnersByPartnerIds(idList));
    }
}
