package com.storlead.sales.service.impl.customer;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CodeGenerateInterface;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.DateUtil;
import com.storlead.framework.common.util.generate.CodeGenerate;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.enums.QueryRangeTypeEnum;
import com.storlead.sales.pojo.dto.customer.WorkOrderAddDTO;
import com.storlead.sales.pojo.dto.customer.WorkOrderChageUserDTO;
import com.storlead.sales.pojo.dto.customer.WorkOrderSearchDTO;
import com.storlead.sales.pojo.entity.customer.*;
import com.storlead.sales.pojo.vo.customer.WorkOrderDetailVO;
import com.storlead.sales.pojo.vo.customer.WorkOrderListVO;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.mapper.customer.WorkOrderMapper;
import com.storlead.sales.service.customer.CustomerService;
import com.storlead.sales.service.customer.DynamicLogService;
import com.storlead.sales.service.customer.SysResourceService;
import com.storlead.sales.service.customer.WorkOrderService;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 工单表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-04-29
 */
@Service
public class WorkOrderServiceImpl extends MyBaseServiceImpl<WorkOrderMapper, WorkOrderEntity> implements WorkOrderService {

    @Resource
    private DynamicLogService dynamicLogService;
    @Resource
    private CustomerService customerService;
    @Resource
    private IUserService userService;
    @Resource
    private IDepartService departService;
    @Resource
    private SysResourceService sysResourceService;
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> addWorkOrder(WorkOrderAddDTO workOrderAddDTO) {
        WorkOrderEntity workOrderEntity = new WorkOrderEntity();
        WorkOrderEntity workOrderOld = new WorkOrderEntity();
        BeanUtils.copyProperties(workOrderAddDTO, workOrderEntity);
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        UserEntity createUser = userService.getById(loginUser.getId());
        UserEntity ownerUser = userService.getById(workOrderEntity.getOwnerBy());
        DeptEntity createDept = departService.getById(createUser.getDeptId());
        DeptEntity ownerDept = departService.getById(ownerUser.getDeptId());
        workOrderEntity.setCreateDepartmentId(createDept.getId());
        workOrderEntity.setCreateDepartmentName(createDept.getName());
        workOrderEntity.setOwnerDepartmentId(ownerDept.getId());
        workOrderEntity.setOwnerDepartmentName(ownerDept.getName());
//        workOrderEntity.setCurrentUserId(loginUser.getId());
//        workOrderEntity.setCurrentUserName(loginUser.getRealName());
        if (ObjectUtils.isEmpty(workOrderEntity.getId())){
            workOrderEntity.setCommitTime(new Date());
            workOrderEntity.setDataCode(CodeGenerate.generate10Code(CodeGenerateInterface.WORK_ORDER_CODE));
        }else {
            workOrderOld = getById(workOrderEntity.getId());
        }


        boolean success = saveOrUpdate(workOrderEntity);
        if (success) {
            DynamicLogEntity workOrderDynamicLog = new DynamicLogEntity();
            workOrderDynamicLog.setId(workOrderEntity.getId());
            workOrderDynamicLog.setTitle(workOrderEntity.getTitle());
            workOrderDynamicLog.setAssignUserId(workOrderEntity.getOwnerBy());
            workOrderDynamicLog.setNewUserId(workOrderEntity.getCurrentUserId());
            workOrderDynamicLog.setNewUserName(workOrderEntity.getCurrentUserName());
            workOrderDynamicLog.setOrderStatus(workOrderEntity.getOrderStatus());
            workOrderDynamicLog.setCreateTime(new Date());
            workOrderDynamicLog.setCompanyName(createDept.getName());
            if (!ObjectUtils.isEmpty(workOrderAddDTO.getId())){
                workOrderDynamicLog.setOldUserId(workOrderOld.getOwnerBy());
                UserEntity oldUser = userService.getById(workOrderOld.getOwnerBy());
                workOrderDynamicLog.setOldUserName(oldUser.getUserName());
            }
            dynamicLogService.save(workOrderDynamicLog);

            //添加附件
            if (!CollectionUtils.isEmpty(workOrderAddDTO.getResourceIdList())){
                sysResourceService.updateResourceById(workOrderEntity.getCustomerId(),ResourceTypeEnum.WORK_ORDER.code,workOrderEntity.getId(),workOrderAddDTO.getResourceIdList());
            }
            return Result.ok();
        }
        return Result.error("操作失败！");
    }

    @Override
    public Result<IPage<WorkOrderListVO>> selectListVO(WorkOrderSearchDTO workOrderSearchDTO) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        IPage<WorkOrderListVO> pageVO = new Page<>(workOrderSearchDTO.getPageIndex(), workOrderSearchDTO.getPageSize());
        IPage<WorkOrderEntity> page = new Page<>(workOrderSearchDTO.getPageIndex(), workOrderSearchDTO.getPageSize());
        LambdaQueryWrapper<WorkOrderEntity> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(workOrderSearchDTO.getBlurry())) {
            wrapper.and(w ->w.like(WorkOrderEntity::getTitle,workOrderSearchDTO.getBlurry()).or().like(WorkOrderEntity::getOrderStatus,workOrderSearchDTO.getBlurry()));
        }
        wrapper.eq(!ObjectUtils.isEmpty(workOrderSearchDTO.getCustomerId()),WorkOrderEntity::getCustomerId, workOrderSearchDTO.getCustomerId());
        wrapper.eq(WorkOrderEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.eq(!ObjectUtils.isEmpty(workOrderSearchDTO.getOrderStatus()),WorkOrderEntity::getOrderStatus, workOrderSearchDTO.getOrderStatus());
        wrapper.eq(!ObjectUtils.isEmpty(workOrderSearchDTO.getWorkOrderCategoryId()),WorkOrderEntity::getWorkOrderCategoryId, workOrderSearchDTO.getWorkOrderCategoryId());
        wrapper.eq(!ObjectUtils.isEmpty(workOrderSearchDTO.getUrgentStatus()),WorkOrderEntity::getUrgentStatus, workOrderSearchDTO.getUrgentStatus());
        wrapper.in(!CollectionUtils.isEmpty(workOrderSearchDTO.getOwnerByIds()), WorkOrderEntity::getOwnerBy, workOrderSearchDTO.getOwnerByIds());
        if (Objects.nonNull(workOrderSearchDTO.getQueryRangeType())) {
            String queryRangeSql = QueryRangeTypeEnum.getQueryRangeSql(workOrderSearchDTO.getQueryRangeType(),LoginUserUtil.getCurrentUserId());
            if (StrUtil.isNotBlank(queryRangeSql)) {
                wrapper.apply(queryRangeSql);
            }
        }
        page = pageWithScope(page, wrapper);
        if (CollectionUtils.isEmpty(page.getRecords())){
            return Result.result(pageVO);
        }
//        List<CustomerListVO> customerListVO = new ArrayList<>();
        //复制list给VO类
        pageVO = SysBaseField.page(page, WorkOrderListVO.class);
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());
        return Result.result(pageVO);
    }

    @Override
    public WorkOrderDetailVO getWorkOrderVOById(Long id) {
        WorkOrderDetailVO workOrderDetailVO = new WorkOrderDetailVO();
        WorkOrderEntity workOrderEntity = getById(id);
        BeanUtils.copyProperties(workOrderEntity, workOrderDetailVO);
        SysBaseField.orgFileds(workOrderDetailVO);

        CustomerEntity customerEntity = customerService.getById(workOrderEntity.getCustomerId());
        workOrderDetailVO.setCustomerName(customerEntity.getCustomerName());

        workOrderDetailVO.dictFiled();
        SysBaseField.orgFileds(workOrderDetailVO);

        //4、展示工单动态的信息
//        List<WorkOrderDynamicLogVO> dynamicList = workOrderDynamicLogService.getListByOderId(workOrderId);

        String waitTime = "";

        long commit_time = workOrderDetailVO.getCreateTime().getTime();//发起时间
        long now = new Date().getTime();//当前时间
//        long expect_time = workOrderDetailVO.getExpectTime().getTime();//期望完成时间

        if(workOrderDetailVO.getOrderStatus()==4 || workOrderDetailVO.getOrderStatus()==5){//工单已完成/确认，计算完成用时
            //actual_time-commit_time
            long actual_time = workOrderDetailVO.getActualTime().getTime();//实际完成时间
            int fzs = DateUtil.getOffsetMinutes(actual_time,commit_time);
            if(fzs>60){
                waitTime = (fzs/60+"小时"+fzs%60+"分钟");
            }else {
                waitTime = (fzs+"分钟");
            }
            workOrderDetailVO.setWaitTimeStr(waitTime);
        }else if(workOrderDetailVO.getOrderStatus()==2 || workOrderDetailVO.getOrderStatus()==3){//工单已撤销/退回
            //revoke_time-commit_time
            long revoke_time = workOrderDetailVO.getRevokeTime().getTime();//撤销、拒绝时间
            int fzs = DateUtil.getOffsetMinutes(revoke_time,commit_time);
            if(fzs>60){
                waitTime = (fzs/60+"小时"+fzs%60+"分钟");
            }else {
                waitTime = (fzs+"分钟");
            }
            workOrderDetailVO.setWaitTimeStr(waitTime);
//            workOrderDetailVO.setShowTime(dynamicList.get(0).getCreatedTime());
        }else{//工单正常进行，计算已创建时间
            //now()-commit_time
            int fzs = DateUtil.getOffsetMinutes(now,commit_time);
            if(fzs>60){
                waitTime = (fzs/60+"小时"+fzs%60+"分钟");
            }else {
                waitTime = (fzs+"分钟");
            }
            workOrderDetailVO.setWaitTimeStr(waitTime);
        }

        //添加下一个id
        WorkOrderEntity next = getNextById(id, new LambdaQueryWrapper<WorkOrderEntity>().eq(WorkOrderEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
        if (!ObjectUtils.isEmpty(next)){
            workOrderDetailVO.setNextId(next.getId());
        }
        //添加上一个id
        WorkOrderEntity previous = getPreviousById(id, new LambdaQueryWrapper<WorkOrderEntity>().eq(WorkOrderEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
        if (!ObjectUtils.isEmpty(previous)){
            workOrderDetailVO.setPreviousId(previous.getId());
        }

        return workOrderDetailVO;
    }

    @Override
    public Result distribution(WorkOrderChageUserDTO workOrderChageUserDTO) {
        SysBaseField.orgFileds(workOrderChageUserDTO);
//        Long sysUserId = workOrderChageUserDTO.getCreateBy();
        LoginUser loginUser = LoginUserUtil.getLoginUser();
//        Department department = getDepartmentId(sysUserId);
        String workOrderIds = workOrderChageUserDTO.getWorkOrderIds();
        String[] split = workOrderIds.split(",");
        for (int i = 0; i < split.length; i++) {
            Long workOrderId = Long.parseLong(split[i]);
            try {
                WorkOrderEntity workOrderEntity = baseMapper.selectById(workOrderId);

                WorkOrderDetailVO existInfo =new WorkOrderDetailVO();
                 BeanUtils.copyProperties(workOrderEntity, existInfo);
                if(ObjectUtils.isEmpty(existInfo)){
                    continue;
                }

                //1、更新工单
                WorkOrderEntity workOrder = new WorkOrderEntity();
                workOrder.setId(workOrderId);
                workOrder.setCurrentUserId(workOrderChageUserDTO.getOwnerBy());
                workOrder.setCurrentUserName(workOrderChageUserDTO.getOwnerByName());
                workOrder.setOwnerBy(workOrderChageUserDTO.getOwnerBy());
//                workOrderEntity.setCurrentUserId(loginUser.getId());
//                workOrderEntity.setCurrentUserName(loginUser.getRealName());
                baseMapper.updateById(workOrder);
                //2、增加动态记录
                if(workOrder.getCurrentUserId() != null && !existInfo.getCurrentUserId().equals(workOrder.getCurrentUserId())) {
                    DynamicLogEntity workOrderDynamicLog = new DynamicLogEntity();
//                    workOrderDynamicLog.setCompanyName(department.getName());
                    workOrderDynamicLog.setResourceType(ResourceTypeEnum.WORK_ORDER.code);
                    workOrderDynamicLog.setRecordId(workOrderId);
                    workOrderDynamicLog.setTitle(existInfo.getTitle());
                    workOrderDynamicLog.setAssignUserId(loginUser.getId());
                    workOrderDynamicLog.setOldUserName(existInfo.getCurrentUserName());
                    workOrderDynamicLog.setOldUserId(existInfo.getCurrentUserId());
                    workOrderDynamicLog.setNewUserName(workOrderChageUserDTO.getOwnerByName());
                    workOrderDynamicLog.setNewUserId(workOrderChageUserDTO.getOwnerBy());
                    workOrderDynamicLog.setOrderStatus(existInfo.getOrderStatus());
                    workOrderDynamicLog.setRemark(workOrderChageUserDTO.getRemark());
                    workOrderDynamicLog.setCreateTime(new Date());

                    dynamicLogService.save(workOrderDynamicLog);
                    //3、发送处理人消息
//                    sendNeedHandleMessage(workOrder.getCurrentUserId(),workOrderChageUserDTO.getCreateUser(),existInfo.getTitle());
                }
            } catch (Exception e) {
                log.error("分配出错，workOrderId="+workOrderId);
            }
        }
        return Result.ok();
    }

    @Override
    public Result status(WorkOrderChageUserDTO workOrderChageUserDTO, Long id) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        Long sysUserId = loginUser.getId();
        Long workOrderId = workOrderChageUserDTO.getId();
        DateTime date = new DateTime();
        WorkOrderEntity workOrderEntity = baseMapper.selectById(workOrderId);

        WorkOrderChageUserDTO exit =new WorkOrderChageUserDTO();
        BeanUtils.copyProperties(workOrderEntity, exit);
        //工单状态：1待处理，2已撤销，3被退回，4已完成，5已确认
        WorkOrderEntity workOrder = new WorkOrderEntity();
        DynamicLogEntity workOrderDynamicLog = new DynamicLogEntity();
        // orderType 工单情景 1：撤销工单，2：退回工单，3：完成工单，4：确认不通过工单，5：确认通过工单， 6再次发起工单
        if(workOrderChageUserDTO.getOrderType() == 1){
            if(exit.getOrderStatus() != 1 && exit.getOrderStatus() != 6){
                return Result.error("抱歉，您无法操作！");
            }
            if(!exit.getCreateBy().equals(loginUser.getId())){
                return Result.error( "抱歉，您无法操作！");
            }
            workOrderDynamicLog.setWaitTimeStr("共间隔：" + getDistanceTime(exit.getCreateTime(), date));
            workOrder.setOrderStatus(2);
            workOrder.setRevokeTime(date);
            workOrderDynamicLog.setOrderStatus(workOrder.getOrderStatus());
            //短信通知
//            sendRevokeHandleMessage(exit.getCurrentUserId(),workOrderChageUserDTO.getCreateUser(),exit.getTitle(),"GD" + exit.getWorkOrderId(),workOrderChageUserDTO.getRemark(),SmsTemplateConstants.SMS_WO_REVOKE_HANDLE_TASK_TEMPLATE);
        } else if(workOrderChageUserDTO.getOrderType() == 2){
            if(!exit.getCurrentUserId().equals(sysUserId)){
                return Result.error("抱歉，您无法操作！");
            }
            if(exit.getOrderStatus() != 1 && exit.getOrderStatus() != 6){
                return Result.error("抱歉，您无法操作！");
            }
            workOrder.setOrderStatus(3);
            workOrder.setRevokeTime(date);
            workOrder.setRemark(workOrderChageUserDTO.getRemark());
            workOrderDynamicLog.setWaitTimeStr("共间隔：" + getDistanceTime(exit.getCommitTime(), date));
            workOrderDynamicLog.setOrderStatus(workOrder.getOrderStatus());
            //短信通知
//            sendRevokeHandleMessage(exit.getCreatedBy(),workOrderChageUserDTO.getCreateUser(),exit.getTitle(),"GD" + exit.getWorkOrderId(),workOrderChageUserDTO.getRemark(),SmsTemplateConstants.SMS_WO_BACK_HANDLE_TASK_TEMPLATE);
        } else if(workOrderChageUserDTO.getOrderType() == 3){
            //需要创建者确认
            if(!exit.getCurrentUserId().equals(sysUserId)){
                return Result.error("抱歉，您无法操作！");
            }
            if(exit.getOrderStatus() != 1 && exit.getOrderStatus() != 6){
                return Result.error("抱歉，您无法操作！");
            }
            workOrder.setOrderStatus(4);
            workOrder.setActualTime(date);
            workOrderDynamicLog.setWaitTimeStr("共耗时：" + getDistanceTime(exit.getCommitTime(), date));
            workOrderDynamicLog.setOrderStatus(workOrder.getOrderStatus());
            //短信通知
//            sendConfirmMessage(exit.getCreatedBy(),workOrderChageUserDTO.getCreateUser(),exit.getTitle(),"GD" + exit.getWorkOrderId());
        } else if(workOrderChageUserDTO.getOrderType() == 4){
            //需要创建者确认
            if (!exit.getCreateBy().equals(sysUserId)) {
                return Result.error("抱歉，您无法操作！");
            }
            if(exit.getOrderStatus() != 4){
                return Result.error("抱歉，您无法操作！");
            }
            workOrder.setOrderStatus(1);
            workOrderDynamicLog.setWaitTimeStr("共耗时：" + getDistanceTime(exit.getCommitTime(), date));
            workOrderDynamicLog.setOrderStatus(5);
            //短信通知
//            sendRevokeHandleMessage(exit.getCurrentUserId(),workOrderChageUserDTO.getCreateUser(),exit.getTitle(),"GD" + exit.getWorkOrderId(),"不通过",SmsTemplateConstants.SMS_WO_CONFIRM_HANDLE_TASK_TEMPLATE);
        } else if(workOrderChageUserDTO.getOrderType() == 5){
            //需要创建者确认
            if (!exit.getCreateBy().equals(sysUserId)) {
                return Result.error("无权操作");
            }
            if(exit.getOrderStatus() != 4){
                return Result.error("无法操作");
            }
            workOrder.setOrderStatus(5);
            workOrderDynamicLog.setWaitTimeStr("共耗时：" + getDistanceTime(exit.getCommitTime(), date));
            workOrderDynamicLog.setOrderStatus(workOrder.getOrderStatus());
            //短信通知
//            sendRevokeHandleMessage(exit.getCurrentUserId(),workOrderChageUserDTO.getCreateUser(),exit.getTitle(),"GD" + exit.getWorkOrderId(),"已通过",SmsTemplateConstants.SMS_WO_CONFIRM_HANDLE_TASK_TEMPLATE);
        } else if(workOrderChageUserDTO.getOrderType() == 6){
            //再次发起
            //需要创建者确认
            if(!exit.getCreateBy().equals(sysUserId)){
                return Result.error("非工单创建者");
            }
//            workOrderAnnexService.delete(new EntityWrapper<WorkOrderAnnex>().eq("work_order_id",workOrderChageUserDTO.getWorkOrderId()));
            workOrder.setOrderCount(exit.getOrderCount() + 1);
            workOrder.setCommitTime(date);
            workOrder.setOrderStatus(1);
            workOrder.setExpectTime(workOrderChageUserDTO.getExpectTime());
            workOrderDynamicLog.setNewUserId(exit.getCurrentUserId());
            workOrderDynamicLog.setNewUserName(exit.getCurrentUserName());
            workOrderDynamicLog.setOrderStatus(workOrder.getOrderStatus());
            //通知处理人
//            sendNeedHandleMessage(exit.getCurrentUserId(),workOrderChageUserDTO.getCreateUser(),exit.getTitle());
        }  else {
            return Result.error( "参数错误");
        }
        workOrder.setId(workOrderId);
        workOrder.setUpdateTime(date);
        baseMapper.updateById(workOrder);
        //2、保存动态信息
//        Department department = getDepartmentId(sysUserId);
        workOrderDynamicLog.setResourceType(ResourceTypeEnum.WORK_ORDER.code);
        workOrderDynamicLog.setRecordId(workOrderId);
        workOrderDynamicLog.setCreateTime(date);
        workOrderDynamicLog.setAssignUserId(sysUserId);
        workOrderDynamicLog.setTitle(exit.getTitle());
        workOrderDynamicLog.setRemark(workOrderChageUserDTO.getRemark());
//        workOrderDynamicLog.setCompanyName(department.getName());
        dynamicLogService.save(workOrderDynamicLog);
        //3、保存评论信息
//        if(StringUtils.isNotBlank(workOrderChageUserDTO.getContent())){
//            WorkOrderComment workOrderComment = new WorkOrderComment();
//            workOrderComment.setWorkOrderId(workOrderId);
//            workOrderComment.setTopCommentId(0);
//            workOrderComment.setSysUserId(sysUserId);
//            workOrderComment.setCommentType(1);
//            workOrderComment.setContent(workOrderChageUserDTO.getContent());
//            workOrderComment.setCreatedTime(date);
//            workOrderCommentService.insertInfo(workOrderComment);
//        }
        return Result.ok();
    }

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param starttime 时间参数 1 格式：1990-01-01 12:00:00
     * @param endtime 时间参数 2 格式：2009-01-01 12:00:00
     * @return String 返回值为：xx天xx小时xx分xx秒
     */
    public  String getDistanceTime(Date starttime, Date endtime) {
        long diff = endtime.getTime() - starttime.getTime();
        long day = diff / (24 * 60 * 60 * 1000);
        long hour = (diff / (60 * 60 * 1000) - day * 24);
        long min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        String result = min + "分钟";
        if(hour != 0){
            result = hour + "小时" + result;
        }
        if( day != 0) {
            result = day + "天" + result;
        }
        return result;
    }
}
