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

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.bean.workorder.OrderFlagLogic;
import com.gree.mall.miniapp.enums.IsYesNoEnum;
import com.gree.mall.miniapp.enums.NoticeEnum;
import com.gree.mall.miniapp.enums.workorder.OrderBaseStatusEnum;
import com.gree.mall.miniapp.enums.workorder.OrderFlagEnum;
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.plus.entity.*;
import com.gree.mall.miniapp.plus.service.*;
import com.gree.mall.miniapp.utils.StringUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequiredArgsConstructor
@Service
public class OrderLogLogic {

    private final CommonLogic commonLogic;
    private final OrderFlagLogic orderFlagLogic;
    private final PgOrderOperatorLogService pgOrderOperatorLogService;
    private final PgOrderBaseService pgOrderBaseService;
    private final NoticeRecordService noticeRecordService;
    private final PgOrderWorkerService pgOrderWorkerService;
    private final PgOrderProductService pgOrderProductService;

    /**
     * 工单操作明细
     * @param orderBaseId
     * @return
     */
    public List<PgOrderOperatorLog> operatorLogList(String orderBaseId){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        List<PgOrderOperatorLog> list = pgOrderOperatorLogService.lambdaQuery()
                .eq(PgOrderOperatorLog::getOrderBaseId, orderBaseId)
                .eq(StringUtils.isNotBlank(currentCompanyWechat.getCompanyWechatId()),
                        PgOrderOperatorLog::getCompanyWechatId,
                        currentCompanyWechat.getCompanyWechatId())
                .orderByDesc(PgOrderOperatorLog::getId)
                .list();
        return list;
    }


    /**
     * 过程反馈-添加操作明细
     */
    @Transactional
    public void addLog(PgOrderOperatorLog pgOrderOperatorLog){
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(pgOrderOperatorLog.getOrderBaseId());

        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.YUYUE.getRemark())
            ||pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.GAIYUE.getRemark())) {
            //预约和改约需要记录操作明细，并变更工单预约时间
            pgOrderBaseService.lambdaUpdate()
                    .set(PgOrderBase::getAppointmentTime, pgOrderOperatorLog.getAppointmentTime())
                    .set(PgOrderBase::getAppointmentEndTime, pgOrderOperatorLog.getAppointmentEndTime())
                    .set(PgOrderBase::getLastOperatorAppointmentTime, new Date())
                    .eq(PgOrderBase::getId, pgOrderOperatorLog.getOrderBaseId())
                    .update();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH");
        SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm");

        //预约
        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.YUYUE.getRemark())){
            if(pgOrderBase.getAppointmentTime() != null){
                throw new RemoteServiceException("已预约工单请操作改约");
            }
            if(pgOrderOperatorLog.getAppointmentTime().getTime() < new Date().getTime()){
                throw new RemoteServiceException("预约时间不可小于当前时间");
            }

            int hour = Integer.parseInt(sdf2.format(pgOrderOperatorLog.getAppointmentTime()));
            String s = hour >= 12 ? "下午" : "上午";
            String text = StringUtil.isEmpty(pgOrderOperatorLog.getContent())?"":(pgOrderOperatorLog.getContent()+"，");

            String format = sdf3.format(pgOrderBase.getAppointmentTime());
            String format1 = sdf3.format(pgOrderBase.getAppointmentEndTime());

            pgOrderOperatorLog.setContent(text+"预约时间:"+sdf.format(pgOrderOperatorLog.getAppointmentTime())+" "+format+"-"+format1);

        }
        //改约
        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.GAIYUE.getRemark())){
            if(pgOrderBase.getOrderStatus().equals(OrderBaseStatusEnum.YWG.getRemark()) || pgOrderBase.getOrderStatus().equals(OrderBaseStatusEnum.YJS.getRemark())){
                throw new RemoteServiceException("已完工工单请勿操作改约");
            }
            if(pgOrderOperatorLog.getAppointmentTime().getTime() < DateUtil.beginOfDay(new Date()).getTime()){
                throw new RemoteServiceException("改约时间不可小于当前时间");
            }
            int hour = Integer.parseInt(sdf2.format(pgOrderOperatorLog.getAppointmentTime()));
            String s = hour >= 12 ? "下午" : "上午";

            String text = StringUtil.isEmpty(pgOrderOperatorLog.getContent())?"":(pgOrderOperatorLog.getContent()+"，");

            String format = sdf3.format(pgOrderBase.getAppointmentTime());
            String format1 = sdf3.format(pgOrderBase.getAppointmentEndTime());


            pgOrderOperatorLog.setContent(text+"预约时间:"+sdf.format(pgOrderOperatorLog.getAppointmentTime())+" "+format+"-"+format1);
        }
        //异常
        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.YCFK.getRemark())){
            orderFlagLogic.saveOrderFlag(Lists.newArrayList(pgOrderBase.getId()), OrderFlagEnum.YI_CHANGE);
        }
        pgOrderOperatorLog.setCreateWebsit(pgOrderBase.getWebsitName());
        this.addLog(pgOrderOperatorLog.getOrderBaseId(),pgOrderOperatorLog.getType(),pgOrderOperatorLog.getContent(),pgOrderOperatorLog.getCreateWebsit(),pgOrderOperatorLog.getImgSrc());
    }


    private void insertNotice(String orderBaseId) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        List<PgOrderProduct> pgOrderProductList = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, orderBaseId).list();
        List<PgOrderWorker> list = pgOrderWorkerService.lambdaQuery().eq(PgOrderWorker::getOrderBaseId, orderBaseId).list();
        List<NoticeRecord> noticeRecords = new ArrayList<>();

        String text = "";

        for (PgOrderProduct pgOrderProduct : pgOrderProductList) {
            text = pgOrderProduct.getMainName()+pgOrderBase.getOrderSmallTypeText()+"*"+pgOrderProduct.getNum()+",";
        }

        text = text.substring(0,text.length() -1);

        for (PgOrderWorker pgOrderWorker : list) {
            NoticeRecord noticeRecord = new NoticeRecord();
            noticeRecord.setNoticeId(pgOrderWorker.getOrderBaseId());
            noticeRecord.setTitle("服务单派工");
            noticeRecord.setContent("服务单号："+pgOrderWorker.getOrderBaseId()+",网点名称："+pgOrderBase.getWebsitName()
                    +"，预约时间："+(pgOrderBase.getAppointmentTime() != null?DateUtil.format(pgOrderBase.getAppointmentTime(),"yyyy-MM-dd"):"")+",服务项目："+text+",客户信息："+pgOrderBase.getUserName()+
                    ",客户电话："+pgOrderBase.getUserMobile()+",服务地址："+pgOrderBase.getAddress());
            noticeRecord.setType(NoticeEnum.B.getKey());
            noticeRecord.setIsNotice(IsYesNoEnum.YES.getKey());
            noticeRecord.setReadFlag(IsYesNoEnum.NO.getKey());
            noticeRecord.setAdminUserId(pgOrderWorker.getWorkerId());
            noticeRecord.setAdminNickName(pgOrderWorker.getWorkerName());
            noticeRecord.setIsWorker("YES");
            noticeRecord.setIssueTime(new Date());
            noticeRecord.setAdminCompanyId(pgOrderBase.getCompanyWechatId());
            noticeRecord.setAdminCompanyName(pgOrderBase.getCompanyWechatName());
            noticeRecord.setNoticeType("SYSTEM");
            noticeRecords.add(noticeRecord);
        }

        noticeRecordService.saveBatch(noticeRecords);

    }


    @Transactional
    public void addLog(String orderBaseId,String type,String content,String websitName){
        this.addLog(orderBaseId,type,content,websitName,"");
    }

    /**
     * 创建工单内部-添加操作明细
     */
    @Transactional
    public void addLog(String orderBaseId,String type,String content,String websitName,String imgSrc){
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        PgOrderOperatorLog pgOrderOperatorLog = new PgOrderOperatorLog();
        pgOrderOperatorLog.setContent(content);
        pgOrderOperatorLog.setType(type);
        pgOrderOperatorLog.setOrderBaseId(orderBaseId);
        pgOrderOperatorLog.setCreateWebsit(websitName);
        pgOrderOperatorLog.setCompanyWechatId(pgOrderBase.getCompanyWechatId());
        pgOrderOperatorLog.setCompanyWechatName(pgOrderBase.getCompanyWechatName());
        pgOrderOperatorLog.setCreateTime(new Date());
        pgOrderOperatorLog.setImgSrc(imgSrc);
        pgOrderOperatorLog.insert();

        PgOrderBase pgOrderBaseUp = new PgOrderBase();
        pgOrderBaseUp.setId(pgOrderBase.getId());
        pgOrderBaseUp.setLastOperator(content);
        pgOrderBaseUp.setLastOperatorWebsit(websitName);
        pgOrderBaseUp.setLastOperatorTime(new Date());
        pgOrderBaseUp.updateById();
        //派单
        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.WORKER.getRemark()) || pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.GP.getRemark())){
            this.insertNotice(pgOrderOperatorLog.getOrderBaseId());
        }
    }

}
