package com.gree.mall.miniapp.logic.engin;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.miniapp.bean.order.MaterialOrderBuy;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.bean.workorder.RpMaterialOrderCount;
import com.gree.mall.miniapp.bean.workorder.RpMaterialOrderVO;
import com.gree.mall.miniapp.enums.*;
import com.gree.mall.miniapp.enums.workorder.OrderOperatorLogTypeEnum;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.common.WxPubNoticeLogic;
import com.gree.mall.miniapp.logic.common.outside.WechatLogic;
import com.gree.mall.miniapp.logic.order.PayOrderLogic;
import com.gree.mall.miniapp.logic.workorder.OrderLogLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.*;
import com.gree.mall.miniapp.utils.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class RpMaterialLogic {


    @Autowired
    RpMaterialOrderService rpMaterialOrderService;

    @Autowired
    RpMaterialOrderItemService rpMaterialOrderItemService;

    @Autowired
    RpProjectRepairByService rpProjectRepairByService;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    PgOrderWorkerService pgOrderWorkerService;

    @Autowired
    PgOrderBaseService pgOrderBaseService;

    @Autowired
    PgOrderProductService pgOrderProductService;

    @Autowired
    WebsitGoodsService websitGoodsService;


    @Autowired
    WebsitNormChargeService websitNormChargeService;

    @Autowired
    WechatLogic wechatLogic;

    @Autowired
    RpProjectRepairService rpProjectRepairService;

    @Autowired
    WxPubNoticeLogic wxPubNoticeLogic;

    @Autowired
    WorkerSettlementService workerSettlementService;

    @Autowired
    UserService userService;

    @Autowired
    NoticeRecordService noticeRecordService;

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    AdminUserWebsitRelaService adminUserWebsitRelaService;

    @Autowired
    OrderLogLogic orderLogLogic;

    @Autowired
    RpProjectRepairItemService rpProjectRepairItemService;

    @Autowired
    PayOrderLogic payOrderLogic;


    public IPage<RpMaterialOrder> page(String examineStatus, Integer pageNum, Integer pageSize) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();

        List<String> collect = rpProjectRepairByService.lambdaQuery().eq(RpProjectRepairBy::getMobile, currentCompanyWechat.getUser().getMobile())
                .select(RpProjectRepairBy::getProjectRepairId).list().stream().map(RpProjectRepairBy::getProjectRepairId).collect(Collectors.toList());


        Page<RpMaterialOrder> page = rpMaterialOrderService.lambdaQuery()
                .and(item -> item.eq(RpMaterialOrder::getWorkerMobile, currentCompanyWechat.getUser().getMobile()).or()
                        .in(!CollectionUtils.isEmpty(collect), RpMaterialOrder::getRpProjectRepairId, collect))
                .eq(!StringUtil.isEmpty(examineStatus), RpMaterialOrder::getExamineStatus, examineStatus)
                .orderByDesc(RpMaterialOrder::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
        return page;
    }

    public RpMaterialOrderCount pageCount() {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();

        List<String> collect = rpProjectRepairByService.lambdaQuery().eq(RpProjectRepairBy::getMobile, currentCompanyWechat.getUser().getMobile())
                .select(RpProjectRepairBy::getProjectRepairId).list().stream().map(RpProjectRepairBy::getProjectRepairId).collect(Collectors.toList());

        Integer qb = rpMaterialOrderService.lambdaQuery()
                .and(item -> item.eq(RpMaterialOrder::getWorkerMobile, currentCompanyWechat.getUser().getMobile()).or()
                        .in(!CollectionUtils.isEmpty(collect), RpMaterialOrder::getRpProjectRepairId, collect))
                .count();
        Integer dsp = rpMaterialOrderService.lambdaQuery()
                .and(item -> item.eq(RpMaterialOrder::getWorkerMobile, currentCompanyWechat.getUser().getMobile()).or()
                        .in(!CollectionUtils.isEmpty(collect), RpMaterialOrder::getRpProjectRepairId, collect))
                .eq(RpMaterialOrder::getExamineStatus, ExamineStatusEnum.WAIT.getKey())
                .count();

        Integer shtg = rpMaterialOrderService.lambdaQuery()
                .and(item -> item.eq(RpMaterialOrder::getWorkerMobile, currentCompanyWechat.getUser().getMobile()).or()
                        .in(!CollectionUtils.isEmpty(collect), RpMaterialOrder::getRpProjectRepairId, collect))
                .eq(RpMaterialOrder::getExamineStatus, ExamineStatusEnum.OK.getKey())

                .count();

        Integer spbh = rpMaterialOrderService.lambdaQuery()
                .and(item -> item.eq(RpMaterialOrder::getWorkerMobile, currentCompanyWechat.getUser().getMobile()).or()
                        .in(!CollectionUtils.isEmpty(collect), RpMaterialOrder::getRpProjectRepairId, collect))
                .eq(RpMaterialOrder::getExamineStatus, ExamineStatusEnum.FAIL.getKey())

                .count();

        Integer yxczf = rpMaterialOrderService.lambdaQuery()
                .and(item -> item.eq(RpMaterialOrder::getWorkerMobile, currentCompanyWechat.getUser().getMobile()).or()
                        .in(!CollectionUtils.isEmpty(collect), RpMaterialOrder::getRpProjectRepairId, collect))
                .eq(RpMaterialOrder::getExamineStatus, PayStatusEnum.PAID.getKey())

                .count();

        Integer yqx = rpMaterialOrderService.lambdaQuery()
                .and(item -> item.eq(RpMaterialOrder::getWorkerMobile, currentCompanyWechat.getUser().getMobile()).or()
                        .in(!CollectionUtils.isEmpty(collect), RpMaterialOrder::getRpProjectRepairId, collect))
                .eq(RpMaterialOrder::getExamineStatus, MaterialExamineStatusEnum.NO.getKey())

                .count();

        RpMaterialOrderCount rpMaterialOrderCount = new RpMaterialOrderCount();
        rpMaterialOrderCount.setQb(qb);
        rpMaterialOrderCount.setDsp(dsp);
        rpMaterialOrderCount.setSptg(shtg);
        rpMaterialOrderCount.setSpbh(spbh);
        rpMaterialOrderCount.setYxczf(yxczf);
        rpMaterialOrderCount.setYqx(yqx);

        return rpMaterialOrderCount;

    }

    public RpMaterialOrderVO detail(String id) {
        RpMaterialOrder rpMaterialOrder = rpMaterialOrderService.getById(id);
        RpMaterialOrderVO rpMaterialOrderVO = BeanUtil.toBean(rpMaterialOrder, RpMaterialOrderVO.class);

        List<RpMaterialOrderItem> rpMaterialOrderItemList = rpMaterialOrderItemService.lambdaQuery().eq(RpMaterialOrderItem::getOrderId, rpMaterialOrder.getOrderId()).list();

        rpMaterialOrderVO.setRpMaterialOrderItems(rpMaterialOrderItemList);

        PgOrderBase pgOrderBase = pgOrderBaseService.getById(rpMaterialOrderVO.getWorkerOrderId());

        List<PgOrderWorker> list = pgOrderWorkerService.lambdaQuery().eq(PgOrderWorker::getOrderBaseId, pgOrderBase.getId()).list();

        rpMaterialOrderVO.setPgOrderBase(pgOrderBase);
        rpMaterialOrderVO.setPgOrderWorkers(list);

        List<PgOrderProduct> pgOrderProducts = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, pgOrderBase.getId()).list();

        rpMaterialOrderVO.setPgOrderProducts(pgOrderProducts);

        return rpMaterialOrderVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public String buy(MaterialOrderBuy workerOrderBuy, String ip, HttpServletRequest request) {

        PgOrderBase pgOrderBase = pgOrderBaseService.getById(workerOrderBuy.getWorkerOrderId());
        RpProjectRepair rpProjectRepair = rpProjectRepairService.getById(pgOrderBase.getRpProjectRepairId());

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        workerOrderBuy.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
        workerOrderBuy.setCompanyWechatName(currentCompanyWechat.getCompanyName());
        workerOrderBuy.setWorkerId(currentCompanyWechat.getUser().getUserId());
        workerOrderBuy.setWorkerName(currentCompanyWechat.getUser().getNickName());
        workerOrderBuy.setWorkerMobile(currentCompanyWechat.getUser().getMobile());
        workerOrderBuy.setUserName(pgOrderBase.getUserName());
        workerOrderBuy.setOrderSmallType(pgOrderBase.getOrderType());
        workerOrderBuy.setOrderSmallTypeText(pgOrderBase.getOrderTypeText());

        workerOrderBuy.setCreateBy(currentCompanyWechat.getUser().getNickName());
        workerOrderBuy.setCreateTime(new Date());
        workerOrderBuy.setIdentity(currentCompanyWechat.getUser().getIdCard());
        workerOrderBuy.setUserId(currentCompanyWechat.getUser().getUserId());

        workerOrderBuy.setExamineStatus(MaterialExamineStatusEnum.NO_PAID.getKey());
        workerOrderBuy.setFeePayMethod(rpProjectRepair.getFeePayMethod());
        workerOrderBuy.setIsAllFee(rpProjectRepair.getIsAllFee());
        workerOrderBuy.setRpProjectRepairId(rpProjectRepair.getId());
        workerOrderBuy.setRpProjectRepairName(rpProjectRepair.getProjectName());
        workerOrderBuy.setPayType(PayTypeEnum.WECHAT.getKey());

        if (StringUtil.isEmpty(workerOrderBuy.getCategoryId()))
            workerOrderBuy.setGoodsType("M");
        else
            workerOrderBuy.setGoodsType("P");
        workerOrderBuy.insert();

        BigDecimal totalAmount = new BigDecimal("0");


        BigDecimal num = new BigDecimal("0");

        for (RpMaterialOrderItem rpMaterialOrderItem : workerOrderBuy.getRpMaterialOrderItemList()) {

            rpMaterialOrderItem.setOrderId(workerOrderBuy.getOrderId());

            if (StringUtil.isEmpty(workerOrderBuy.getCategoryId())) {
                this.addFuCai(rpMaterialOrderItem,pgOrderBase.getRpProjectRepairId());


            }else {
                this.addPeiJian(rpMaterialOrderItem,pgOrderBase.getRpProjectRepairId());

            }


            totalAmount = totalAmount.add(rpMaterialOrderItem.getTotalAmount());

            num = num.add(rpMaterialOrderItem.getNum());
        }

        workerOrderBuy.setTotalAmount(totalAmount);

        workerOrderBuy.setNum(num);
        workerOrderBuy.updateById();

        rpMaterialOrderItemService.saveBatch(workerOrderBuy.getRpMaterialOrderItemList());

        return workerOrderBuy.getOrderId();
    }


    private void addPeiJian(RpMaterialOrderItem workerOrderItem,String rpId) {
        WebsitGoods websitGoods = websitGoodsService.getById(workerOrderItem.getGoodsId());


        workerOrderItem.setGoodsAmount(websitGoods.getNormAmount());
        workerOrderItem.setGoodsCode(websitGoods.getGoodsCode());


        if (websitGoods.getNormType().equals("S"))
            workerOrderItem.setNormAmount(workerOrderItem.getNormAmount());
        else
            workerOrderItem.setNormAmount(websitGoods.getNormAmount());

        BigDecimal bigDecimal = payOrderLogic.normPrice(workerOrderItem.getGoodsId(), rpId);
        workerOrderItem.setNormAmount(bigDecimal == null?workerOrderItem.getNormAmount():bigDecimal);

        workerOrderItem.setTotalAmount(workerOrderItem.getNormAmount().multiply(Convert.toBigDecimal(workerOrderItem.getNum())));

        workerOrderItem.setUnit(websitGoods.getGoodsSalesUnit());

        if (websitGoods.getNormType().equals("M")) {
            workerOrderItem.setChargeType("ACC");

        } else {
            workerOrderItem.setChargeType("SERV");
        }


    }

    private void addFuCai(RpMaterialOrderItem workerOrderItem,String rpId) {
        WebsitNormCharge websitNormCharge = websitNormChargeService.getById(workerOrderItem.getGoodsId());

        BigDecimal bigDecimal = payOrderLogic.normPrice(workerOrderItem.getGoodsId(), rpId);
        websitNormCharge.setNormAmount(bigDecimal == null?websitNormCharge.getNormAmount():bigDecimal);

        workerOrderItem.setTotalAmount(websitNormCharge.getNormAmount().multiply(Convert.toBigDecimal(workerOrderItem.getNum())));
        workerOrderItem.setGoodsAmount(websitNormCharge.getNormAmount());
        workerOrderItem.setGoodsCode(websitNormCharge.getNormCode());
        workerOrderItem.setNormAmount(websitNormCharge.getNormAmount());
        workerOrderItem.setUnit(websitNormCharge.getUnit());
        if (websitNormCharge.getNormType().equals("M")) {
            workerOrderItem.setChargeType("MCC");
        } else {
            workerOrderItem.setChargeType("SERV");
        }

    }


    public void cancel(String orderId) {

        if (rpMaterialOrderService.lambdaQuery().eq(RpMaterialOrder::getOrderId, orderId)
                .eq(RpMaterialOrder::getPayStatus, "WAIT").count() < 1) {
            throw new RemoteServiceException("订单不属于未支付不可取消");
        }

        rpMaterialOrderService.lambdaUpdate().eq(RpMaterialOrder::getOrderId, orderId)
                .set(RpMaterialOrder::getPayStatus, PayStatusEnum.CANCEL.getKey())
                .set(RpMaterialOrder::getExamineStatus, "NO")
                .update();
    }

    @Transactional(rollbackFor = Exception.class)
    public String apply(MaterialOrderBuy workerOrderBuy) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        workerOrderBuy.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
        workerOrderBuy.setCompanyWechatName(currentCompanyWechat.getCompanyName());
        workerOrderBuy.setWorkerId(currentCompanyWechat.getUser().getUserId());
        workerOrderBuy.setWorkerName(currentCompanyWechat.getUser().getNickName());
        workerOrderBuy.setWorkerMobile(currentCompanyWechat.getUser().getMobile());
        workerOrderBuy.setCreateBy(currentCompanyWechat.getUser().getNickName());

        workerOrderBuy.setCreateTime(new Date());
        workerOrderBuy.setIdentity(currentCompanyWechat.getUser().getIdCard());
        workerOrderBuy.setUserId(currentCompanyWechat.getUser().getUserId());
        workerOrderBuy.setFeePayMethod("EXAMINE");

        PgOrderBase pgOrderBase = pgOrderBaseService.getById(workerOrderBuy.getWorkerOrderId());
        RpProjectRepair rpProjectRepair = rpProjectRepairService.getById(pgOrderBase.getRpProjectRepairId());
        workerOrderBuy.setUserName(pgOrderBase.getUserName());
        workerOrderBuy.setOrderSmallType(pgOrderBase.getOrderType());
        workerOrderBuy.setOrderSmallTypeText(pgOrderBase.getOrderTypeText());

        workerOrderBuy.setFeePayMethod(rpProjectRepair.getFeePayMethod());
        workerOrderBuy.setIsAllFee(rpProjectRepair.getIsAllFee());
        workerOrderBuy.setRpProjectRepairId(rpProjectRepair.getId());
        workerOrderBuy.setRpProjectRepairName(rpProjectRepair.getProjectName());

        if (workerOrderBuy.getIsAllFee().equals("YES")) {
            workerOrderBuy.setExamineStatus(ExamineStatusEnum.OK.getKey());
            workerOrderBuy.setPayStatus(null);
        }

        if (StringUtil.isEmpty(workerOrderBuy.getCategoryId()))
            workerOrderBuy.setGoodsType("M");
        else
            workerOrderBuy.setGoodsType("P");
        workerOrderBuy.insert();

        BigDecimal totalAmount = new BigDecimal("0");


        BigDecimal num = new BigDecimal("0");

        for (RpMaterialOrderItem rpMaterialOrderItem : workerOrderBuy.getRpMaterialOrderItemList()) {

            rpMaterialOrderItem.setOrderId(workerOrderBuy.getOrderId());

            if (StringUtil.isEmpty(workerOrderBuy.getCategoryId())) {
                this.addFuCai(rpMaterialOrderItem, pgOrderBase.getRpProjectRepairId());

            }else {
                this.addPeiJian(rpMaterialOrderItem, pgOrderBase.getRpProjectRepairId());

            }


            totalAmount = totalAmount.add(rpMaterialOrderItem.getTotalAmount());

            num = num.add(rpMaterialOrderItem.getNum());
        }

        workerOrderBuy.setTotalAmount(totalAmount);

        workerOrderBuy.setNum(num);
        workerOrderBuy.updateById();

        rpMaterialOrderItemService.saveBatch(workerOrderBuy.getRpMaterialOrderItemList());

        if (workerOrderBuy.getIsAllFee().equals("NO") && workerOrderBuy.getFeePayMethod().equals(FeePayMethodEnum.EXAMINE.getKey())) {
            this.sendMaterialOrder(workerOrderBuy);

            this.addLog(workerOrderBuy);

        }

        return workerOrderBuy.getOrderId();
    }

    private void addLog(MaterialOrderBuy workerOrderBuy) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(workerOrderBuy.getWorkerOrderId());

        PgOrderOperatorLog pgOrderOperatorLog = new PgOrderOperatorLog();
        pgOrderOperatorLog.setOrderBaseId(workerOrderBuy.getWorkerOrderId());
        pgOrderOperatorLog.setType(OrderOperatorLogTypeEnum.FEIYONG.getRemark());
        pgOrderOperatorLog.setTypeText(OrderOperatorLogTypeEnum.FEIYONG.getRemark());
        pgOrderOperatorLog.setContent("费用申请，申请人" + workerOrderBuy.getWorkerName());
        orderLogLogic.addLog(pgOrderOperatorLog);
    }

    private void sendMaterialOrder(MaterialOrderBuy workerOrderBuy) {

        String text = "";
        for (RpMaterialOrderItem rpMaterialOrderItem : workerOrderBuy.getRpMaterialOrderItemList()) {
            text = text + rpMaterialOrderItem.getGoodsName() + "*" + rpMaterialOrderItem.getNum() + ",";
        }

        List<NoticeRecord> noticeRecords = new ArrayList<>();
        List<RpProjectRepairBy> list = rpProjectRepairByService.lambdaQuery().eq(RpProjectRepairBy::getProjectRepairId, workerOrderBuy.getRpProjectRepairId()).list();
        for (RpProjectRepairBy rpProjectRepairBy : list) {
            wxPubNoticeLogic.addWbAmountApply(rpProjectRepairBy.getMobile(), workerOrderBuy.getCompanyWechatId(), workerOrderBuy.getWorkerName() + workerOrderBuy.getWorkerMobile()
                    , workerOrderBuy.getCreateTime(), "待审批" + workerOrderBuy.getRpProjectRepairName(), text + workerOrderBuy.getTotalAmount(), workerOrderBuy.getOrderId(), workerOrderBuy.getOrderId());

            User user = userService.lambdaQuery().eq(User::getMobile, rpProjectRepairBy.getMobile()).last("limit 1").one();
            if (user != null) {
                NoticeRecord noticeRecord = new NoticeRecord();
                noticeRecord.setNoticeId(workerOrderBuy.getOrderId());

                noticeRecord.setTitle("费用申请单待审批");
                noticeRecord.setContent(workerOrderBuy.getOrderId());
                noticeRecord.setType(NoticeEnum.B.getKey());
                noticeRecord.setIsNotice(IsYesNoEnum.YES.getKey());
                noticeRecord.setReadFlag(IsYesNoEnum.NO.getKey());
                noticeRecord.setAdminUserId(user.getUserId());
                noticeRecord.setAdminNickName(user.getNickName());
                noticeRecord.setIsWorker("YES");
                noticeRecord.setIssueTime(new Date());
                noticeRecord.setAdminCompanyId(user.getUserId());
                noticeRecord.setAdminCompanyName(user.getCompanyName());
                noticeRecord.setNoticeType("WB");
                noticeRecord.setOrderId(workerOrderBuy.getOrderId());
                noticeRecord.insert();
            }
        }

        List<AdminUserWebsitRela> adminUserWebsitRelas = adminUserWebsitRelaService.lambdaQuery()
                .eq(AdminUserWebsitRela::getAdminWebsitId, workerOrderBuy.getWebsitId()).list();

        for (AdminUserWebsitRela adminUserWebsitRela : adminUserWebsitRelas) {
            AdminUser one = adminUserService.getById(adminUserWebsitRela.getAdminUserId());
            NoticeRecord noticeRecord = new NoticeRecord();
            noticeRecord.setNoticeId(workerOrderBuy.getOrderId());
            noticeRecord.setTitle("费用申请单待审批");
            String format = DateUtil.format(new Date(), "yyyy-MM-dd");
            noticeRecord.setContent(workerOrderBuy.getRpProjectRepairName() + "，创建时间" + format + ",请及时审批");
            noticeRecord.setType(NoticeEnum.B.getKey());
            noticeRecord.setNoticeType(NoticeTypeEnum.SYSTEM.getKey());
            noticeRecord.setIsNotice(IsYesNoEnum.YES.getKey());
            noticeRecord.setReadFlag(IsYesNoEnum.NO.getKey());
            noticeRecord.setAdminUserId(adminUserWebsitRela.getAdminUserId());
            noticeRecord.setAdminNickName(one.getNickName());
            noticeRecord.setIssueTime(new Date());
            noticeRecord.setAdminCompanyId(workerOrderBuy.getCompanyWechatId());
            noticeRecord.setAdminCompanyName(workerOrderBuy.getCompanyWechatName());
            noticeRecord.setAdminNoticeType(AdminNoticTypeEnum.WBI.getKey());
            noticeRecord.setOrderId(workerOrderBuy.getOrderId());
            noticeRecord.insert();
        }


        AdminUser one = adminUserService.lambdaQuery().eq(AdminUser::getCompanyWechatId, workerOrderBuy.getCompanyWechatId())
                .eq(AdminUser::getType, 1).last("limit 1").one();

        NoticeRecord noticeRecordCom = new NoticeRecord();
        noticeRecordCom.setNoticeId(workerOrderBuy.getOrderId());
        noticeRecordCom.setTitle("费用申请单待审批");
        String format = DateUtil.format(new Date(), "yyyy-MM-dd");
        noticeRecordCom.setContent(workerOrderBuy.getRpProjectRepairName() + "，创建时间" + format + ",请及时审批");
        noticeRecordCom.setType(NoticeEnum.B.getKey());
        noticeRecordCom.setNoticeType(NoticeTypeEnum.SYSTEM.getKey());
        noticeRecordCom.setIsNotice(IsYesNoEnum.YES.getKey());
        noticeRecordCom.setReadFlag(IsYesNoEnum.NO.getKey());
        noticeRecordCom.setAdminUserId(one.getAdminUserId());
        noticeRecordCom.setAdminNickName(one.getNickName());
        noticeRecordCom.setIssueTime(new Date());
        noticeRecordCom.setAdminCompanyId(one.getCompanyWechatId());
        noticeRecordCom.setAdminCompanyName(one.getCompanyName());
        noticeRecordCom.setAdminNoticeType(AdminNoticTypeEnum.WBI.getKey());
        noticeRecordCom.setOrderId(workerOrderBuy.getOrderId());
        noticeRecordCom.insert();

 /*       wxPubNoticeLogic.addWbAmountApply(workerOrderBuy.getWorkerMobile(),workerOrderBuy.getCompanyWechatId(),workerOrderBuy.getWorkerName()+workerOrderBuy.getWorkerMobile()
                ,workerOrderBuy.getCreateTime(),workerOrderBuy."待审批"+getRpProjectRepairName(),text+workerOrderBuy.getTotalAmount(),workerOrderBuy.getOrderId(),workerOrderBuy.getOrderId());

        NoticeRecord noticeRecord = new NoticeRecord();
        noticeRecord.setNoticeId(workerOrderBuy.getOrderId());
        noticeRecord.setTitle("费用申请单待审批");
        noticeRecord.setContent(workerOrderBuy.getOrderId());
        noticeRecord.setType(NoticeEnum.B.getKey());
        noticeRecord.setIsNotice(IsYesNoEnum.YES.getKey());
        noticeRecord.setReadFlag(IsYesNoEnum.NO.getKey());
        noticeRecord.setAdminUserId(workerOrderBuy.getWorkerId());
        noticeRecord.setAdminNickName(workerOrderBuy.getWorkerName());
        noticeRecord.setIsWorker("YES");
        noticeRecord.setIssueTime(new Date());
        noticeRecord.setAdminCompanyId(workerOrderBuy.getWorkerId());
        noticeRecord.setAdminCompanyName(workerOrderBuy.getCompanyWechatName());
        noticeRecord.setNoticeType("WB");
        noticeRecord.setOrderId(workerOrderBuy.getOrderId());
        noticeRecords.add(noticeRecord);*/


        // noticeRecordService.saveBatch(noticeRecords);
    }

    public Boolean paid(String orderId, String authCode, String ip, String payType) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        RpMaterialOrder rpMaterialOrder = rpMaterialOrderService.getById(orderId);
        if (!rpMaterialOrder.getPayStatus().equals("WAIT")) {
            throw new RemoteServiceException("订单已取消支付");
        }

        rpMaterialOrder.setSource(commonLogic.getSource().equals(OrderInfoSourceEnum.A) ?
                OrderInfoSourceEnum.A.getRemark() : OrderInfoSourceEnum.B.getRemark());


        if (payType.equals(PayTypeEnum.WECHAT.getKey())) {
            String transcationId = wechatLogic.paymentFkm(rpMaterialOrder.getOrderId(), rpMaterialOrder.getTotalAmount(), authCode, "N",
                    ip, currentCompanyWechat.getCompanyWechatId(), rpMaterialOrder.getSource());
            rpMaterialOrder.setWechatOrder(transcationId);
        }
        rpMaterialOrder.setPayTime(new Date());
        rpMaterialOrder.setPayStatus(PayStatusEnum.PAID.getKey());
        rpMaterialOrder.setPayType(payType);

        rpMaterialOrder.setExamineStatus(PayStatusEnum.PAID.getKey());
        rpMaterialOrder.updateById();

        List<RpMaterialOrderItem> list = rpMaterialOrderItemService.lambdaQuery().eq(RpMaterialOrderItem::getOrderId, orderId).list();

        this.addSettlementWorker(rpMaterialOrder, list);
        return true;
    }

    private void addSettlementWorker(RpMaterialOrder workerOrder, List<RpMaterialOrderItem> workerOrderItems) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        WorkerSettlement one = workerSettlementService.lambdaQuery().eq(WorkerSettlement::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId())
                .eq(WorkerSettlement::getWebsitId, workerOrder.getWebsitId())
                .eq(WorkerSettlement::getType, "PROJECT")
                .eq(WorkerSettlement::getPayType, workerOrder.getPayType())
                .eq(WorkerSettlement::getWorkerId, workerOrder.getWorkerId()).last("limit 1").one();
        if (one != null) {

            one.setTotalAmount(workerOrder.getTotalAmount().add(one.getTotalAmount()));
            one.setTotalNum(one.getTotalNum().add(Convert.toBigDecimal("1")));
            one.updateById();
        } else {
            WorkerSettlement workerSettlement = new WorkerSettlement();
            workerSettlement.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
            workerSettlement.setCompanyWechatName(currentCompanyWechat.getCompanyName());
            workerSettlement.setWebsitId(workerOrder.getWebsitId());
            workerSettlement.setWebsitName(workerOrder.getWebsitName());
            workerSettlement.setWorkerId(workerOrder.getWorkerId());
            workerSettlement.setWorkerName(workerOrder.getWorkerName());
            workerSettlement.setWorkerMobile(workerOrder.getWorkerMobile());
            workerSettlement.setIdentity(workerOrder.getIdentity());
            workerSettlement.setTotalAmount(workerOrder.getTotalAmount());
            workerSettlement.setTotalNum(Convert.toBigDecimal("1"));
            workerSettlement.setPayType(workerOrder.getPayType());
            workerSettlement.setType("PROJECT");
            workerSettlement.insert();
        }

    }

    public List<RpMaterialOrderVO> detailWorker(String workerOrderId) {

        List<RpMaterialOrder> rpMaterialOrders = rpMaterialOrderService.lambdaQuery().eq(RpMaterialOrder::getWorkerOrderId, workerOrderId).list();

        List<RpMaterialOrderVO> rpMaterialOrderVOS = BeanUtil.copyToList(rpMaterialOrders, RpMaterialOrderVO.class);

        for (RpMaterialOrderVO rpMaterialOrderVO : rpMaterialOrderVOS) {
            List<RpMaterialOrderItem> rpMaterialOrderItemList = rpMaterialOrderItemService.lambdaQuery().eq(RpMaterialOrderItem::getOrderId, rpMaterialOrderVO.getOrderId()).list();
            rpMaterialOrderVO.setRpMaterialOrderItems(rpMaterialOrderItemList);

            PgOrderBase pgOrderBase = pgOrderBaseService.getById(rpMaterialOrderVO.getWorkerOrderId());

            List<PgOrderWorker> list = pgOrderWorkerService.lambdaQuery().eq(PgOrderWorker::getOrderBaseId, pgOrderBase.getId()).list();

            rpMaterialOrderVO.setPgOrderBase(pgOrderBase);
            rpMaterialOrderVO.setPgOrderWorkers(list);

            List<PgOrderProduct> pgOrderProducts = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, pgOrderBase.getId()).list();

            rpMaterialOrderVO.setPgOrderProducts(pgOrderProducts);
        }

        return rpMaterialOrderVOS;

    }

    public Boolean isBy(String orderBaserId) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();

        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaserId);


        if (rpProjectRepairByService.lambdaQuery().eq(RpProjectRepairBy::getProjectRepairId, pgOrderBase.getRpProjectRepairId())
                .eq(RpProjectRepairBy::getMobile, currentCompanyWechat.getUser().getMobile())
                .eq(RpProjectRepairBy::getFeeExamine, "YES")
                .count() < 1) {
            return false;
        }

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public void examine(String id, String examineRemark, String examineStatus) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        RpMaterialOrder rpMaterialOrder = rpMaterialOrderService.getById(id);

        if (rpProjectRepairByService.lambdaQuery().eq(RpProjectRepairBy::getProjectRepairId, rpMaterialOrder.getRpProjectRepairId())
                .eq(RpProjectRepairBy::getMobile, currentCompanyWechat.getUser().getMobile()).count() < 1) {
            throw new RemoteServiceException("非项目负责人，不可审批");
        }


        if (!rpMaterialOrder.getExamineStatus().equals(MaterialExamineStatusEnum.WAIT.getKey()))
            throw new RemoteServiceException("订单不属于待审批");

        RpMaterialOrder rpMaterialOrderIn = new RpMaterialOrder();
        rpMaterialOrderIn.setOrderId(rpMaterialOrder.getOrderId());
        rpMaterialOrderIn.setExamineName(currentCompanyWechat.getUser().getNickName());
        rpMaterialOrderIn.setExamineRemark(examineRemark);
        rpMaterialOrderIn.setExamineTime(new Date());
        rpMaterialOrderIn.setExamineStatus(examineStatus);
        if (examineStatus.equals(MaterialExamineStatusEnum.FAIL.getKey())) {
            rpMaterialOrderIn.setPayStatus(PayStatusEnum.CANCEL.getKey());
        } else {
            rpMaterialOrderIn.setPayStatus(PayStatusEnum.PAID.getKey());
            rpMaterialOrderIn.setPayTime(new Date());
        }
        rpMaterialOrderIn.updateById();

        if (rpMaterialOrder.getIsAllFee().equals("NO") && rpMaterialOrder.getFeePayMethod().equals(FeePayMethodEnum.EXAMINE.getKey())) {
            RpMaterialOrder rpMaterialOrderUp = rpMaterialOrderService.getById(id);
            this.sendMaterialExamine(rpMaterialOrderUp);
            this.addExLog(rpMaterialOrderUp);
        }
    }

    private void addExLog(RpMaterialOrder rpMaterialOrderIn) {

        String status = "";
        if (rpMaterialOrderIn.getExamineStatus().equals(ExamineStatusEnum.FAIL.getKey()))
            status = "审批驳回";
        else if (rpMaterialOrderIn.getExamineStatus().equals(MaterialExamineStatusEnum.NO.getKey()))
            status = "取消";
        else
            status = "审批通过";
        PgOrderOperatorLog pgOrderOperatorLog = new PgOrderOperatorLog();
        pgOrderOperatorLog.setOrderBaseId(rpMaterialOrderIn.getWorkerOrderId());
        pgOrderOperatorLog.setType(OrderOperatorLogTypeEnum.FEIYONGEX.getRemark());
        pgOrderOperatorLog.setTypeText(OrderOperatorLogTypeEnum.FEIYONGEX.getRemark());
        pgOrderOperatorLog.setContent("费用申请" + status + "，审核人" + rpMaterialOrderIn.getExamineName());
        orderLogLogic.addLog(pgOrderOperatorLog);
    }


    private void sendMaterialExamine(RpMaterialOrder rpMaterialOrder) {
        List<RpMaterialOrderItem> rpMaterialOrderItems = rpMaterialOrderItemService.lambdaQuery().eq(RpMaterialOrderItem::getOrderId, rpMaterialOrder.getOrderId()).list();
        String text = "";
        for (RpMaterialOrderItem rpMaterialOrderItem : rpMaterialOrderItems) {
            text = text + rpMaterialOrderItem.getGoodsName() + "*" + rpMaterialOrderItem.getNum() + ",";
        }
        String status = "";
        if (rpMaterialOrder.getExamineStatus().equals(ExamineStatusEnum.FAIL.getKey()))
            status = "审批驳回";
        else if (rpMaterialOrder.getExamineStatus().equals(MaterialExamineStatusEnum.NO.getKey()))
            status = "取消";
        else
            status = "审批通过";

        List<NoticeRecord> noticeRecords = new ArrayList<>();
        List<RpProjectRepairBy> list = rpProjectRepairByService.lambdaQuery().eq(RpProjectRepairBy::getProjectRepairId, rpMaterialOrder.getRpProjectRepairId()).list();
        for (RpProjectRepairBy rpProjectRepairBy : list) {
            wxPubNoticeLogic.addWbAmountApply(rpProjectRepairBy.getMobile(), rpMaterialOrder.getCompanyWechatId(), rpMaterialOrder.getWorkerName() + rpMaterialOrder.getWorkerMobile()
                    , rpMaterialOrder.getCreateTime(), status + rpMaterialOrder.getRpProjectRepairName(), text + rpMaterialOrder.getTotalAmount(), rpMaterialOrder.getOrderId(), rpMaterialOrder.getOrderId());

            User user = userService.lambdaQuery().eq(User::getMobile, rpProjectRepairBy.getMobile()).last("limit 1").one();
            if (user != null) {
                NoticeRecord noticeRecord = new NoticeRecord();
                noticeRecord.setNoticeId(rpMaterialOrder.getOrderId());
                noticeRecord.setTitle("费用申请单" + status);
                String format = DateUtil.format(new Date(), "yyyy-MM-dd");
                noticeRecord.setContent(rpMaterialOrder.getRpProjectRepairName() + "，创建时间" + format + "," + status + ",已审批完成");

                noticeRecord.setType(NoticeEnum.B.getKey());
                noticeRecord.setIsNotice(IsYesNoEnum.YES.getKey());
                noticeRecord.setReadFlag(IsYesNoEnum.NO.getKey());
                noticeRecord.setAdminUserId(user.getUserId());
                noticeRecord.setAdminNickName(user.getNickName());
                noticeRecord.setIssueTime(new Date());
                noticeRecord.setAdminCompanyId(user.getUserId());
                noticeRecord.setAdminCompanyName(user.getCompanyName());
                noticeRecord.setNoticeType("WB");
                noticeRecord.setOrderId(rpMaterialOrder.getOrderId());
                noticeRecord.insert();
            }
        }

        List<AdminUserWebsitRela> adminUserWebsitRelas = adminUserWebsitRelaService.lambdaQuery()
                .eq(AdminUserWebsitRela::getAdminWebsitId, rpMaterialOrder.getWebsitId()).list();

        for (AdminUserWebsitRela adminUserWebsitRela : adminUserWebsitRelas) {
            AdminUser one = adminUserService.getById(adminUserWebsitRela.getAdminUserId());
            NoticeRecord noticeRecord = new NoticeRecord();
            noticeRecord.setNoticeId(rpMaterialOrder.getOrderId());
            noticeRecord.setTitle("费用申请单" + status);
            String format = DateUtil.format(new Date(), "yyyy-MM-dd");
            noticeRecord.setContent(rpMaterialOrder.getRpProjectRepairName() + "，创建时间" + format + "," + status + ",已审批完成");
            noticeRecord.setType(NoticeEnum.B.getKey());
            noticeRecord.setNoticeType(NoticeTypeEnum.SYSTEM.getKey());
            noticeRecord.setIsNotice(IsYesNoEnum.YES.getKey());
            noticeRecord.setReadFlag(IsYesNoEnum.NO.getKey());
            noticeRecord.setAdminUserId(adminUserWebsitRela.getAdminUserId());
            noticeRecord.setAdminNickName(one.getNickName());
            noticeRecord.setIssueTime(new Date());
            noticeRecord.setAdminCompanyId(rpMaterialOrder.getCompanyWechatId());
            noticeRecord.setAdminCompanyName(rpMaterialOrder.getCompanyWechatName());
            noticeRecord.setAdminNoticeType(AdminNoticTypeEnum.WBK.getKey());
            noticeRecord.setOrderId(rpMaterialOrder.getOrderId());
            noticeRecord.insert();
        }

        AdminUser one = adminUserService.lambdaQuery().eq(AdminUser::getCompanyWechatId, rpMaterialOrder.getCompanyWechatId())
                .eq(AdminUser::getType, 1).last("limit 1").one();

        NoticeRecord noticeRecordCom = new NoticeRecord();
        noticeRecordCom.setNoticeId(rpMaterialOrder.getOrderId());
        noticeRecordCom.setTitle("费用申请单" + status);
        noticeRecordCom.setContent("费用申请单" + status);
        noticeRecordCom.setType(NoticeEnum.B.getKey());
        noticeRecordCom.setNoticeType(NoticeTypeEnum.SYSTEM.getKey());
        noticeRecordCom.setIsNotice(IsYesNoEnum.YES.getKey());
        noticeRecordCom.setReadFlag(IsYesNoEnum.NO.getKey());
        noticeRecordCom.setAdminUserId(one.getAdminUserId());
        noticeRecordCom.setAdminNickName(one.getNickName());
        noticeRecordCom.setIsWorker("YES");
        noticeRecordCom.setIssueTime(new Date());
        noticeRecordCom.setAdminCompanyId(rpMaterialOrder.getCompanyWechatId());
        noticeRecordCom.setAdminCompanyName(rpMaterialOrder.getCompanyWechatName());
        noticeRecordCom.setAdminNoticeType(AdminNoticTypeEnum.WBK.getKey());
        noticeRecordCom.setOrderId(rpMaterialOrder.getOrderId());
        noticeRecordCom.insert();

      /*  wxPubNoticeLogic.addWbAmountApply(rpMaterialOrder.getWorkerMobile(),rpMaterialOrder.getCompanyWechatId(),rpMaterialOrder.getWorkerName()+rpMaterialOrder.getWorkerMobile()
                ,rpMaterialOrder.getCreateTime(),status+rpMaterialOrder.getRpProjectRepairName(),text+rpMaterialOrder.getTotalAmount(),status+rpMaterialOrder.getOrderId(),rpMaterialOrder.getOrderId());
        NoticeRecord noticeRecord = new NoticeRecord();
        noticeRecord.setNoticeId(rpMaterialOrder.getOrderId());
        noticeRecord.setTitle("费用申请单"+status);
        noticeRecord.setContent(rpMaterialOrder.getOrderId());
        noticeRecord.setType(NoticeEnum.B.getKey());
        noticeRecord.setIsNotice(IsYesNoEnum.YES.getKey());
        noticeRecord.setReadFlag(IsYesNoEnum.NO.getKey());
        noticeRecord.setAdminUserId(rpMaterialOrder.getWorkerId());
        noticeRecord.setAdminNickName(rpMaterialOrder.getWorkerName());
        noticeRecord.setIsWorker("YES");
        noticeRecord.setIssueTime(new Date());
        noticeRecord.setAdminCompanyId(rpMaterialOrder.getWorkerId());
        noticeRecord.setAdminCompanyName(rpMaterialOrder.getCompanyWechatName());
        noticeRecord.setNoticeType("WB");
        noticeRecord.setOrderId(rpMaterialOrder.getOrderId());
        noticeRecords.add(noticeRecord);*/


        // noticeRecordService.saveBatch(noticeRecords);
    }

    public void cancelOrder(String id) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        RpMaterialOrder rpMaterialOrder = rpMaterialOrderService.getById(id);

      /*  if (rpProjectRepairByService.lambdaQuery().eq(RpProjectRepairBy::getProjectRepairId,rpMaterialOrder.getRpProjectRepairId())
                .eq(RpProjectRepairBy::getMobile,currentCompanyWechat.getUser().getMobile())
                .eq(RpProjectRepairBy::getFeeExamine,"YES").count() < 1 ||
            !rpMaterialOrder.getWorkerMobile().equals(currentCompanyWechat.getLinkPhone())
        ) {
            throw new RemoteServiceException("非项目负责人，不可取消");
        }*/


        RpMaterialOrder rpMaterialOrderIn = new RpMaterialOrder();
        rpMaterialOrderIn.setOrderId(rpMaterialOrder.getOrderId());
        rpMaterialOrderIn.setExamineStatus(MaterialExamineStatusEnum.NO.getKey());
        rpMaterialOrderIn.setCancelName(currentCompanyWechat.getUser().getNickName());
        rpMaterialOrderIn.setCancelTime(new Date());
        rpMaterialOrderIn.updateById();

        if (rpMaterialOrder.getIsAllFee().equals("NO") && rpMaterialOrder.getFeePayMethod().equals(FeePayMethodEnum.EXAMINE.getKey())) {
            RpMaterialOrder rpMaterialOrderUp = rpMaterialOrderService.getById(id);
            this.sendMaterialExamine(rpMaterialOrderUp);
        }
    }
}
