package com.dk.mdm.service.mst;

import com.dk.common.exception.BaseBusinessException;
import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.model.pojo.PageList;
import com.dk.common.model.vo.core.StaffEntity;
import com.dk.common.response.ResponseCodeEnum;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.mdm.infrastructure.convert.mst.CusFollowConvert;
import com.dk.mdm.infrastructure.convert.mst.MeasureReceiptConvert;
import com.dk.mdm.infrastructure.util.AuthUtils;
import com.dk.mdm.mapper.mst.*;
import com.dk.mdm.model.pojo.mst.*;
import com.dk.common.service.BaseService;
import com.dk.common.mapper.BaseMapper;
import com.dk.mdm.model.query.mst.CusFollowQuery;
import com.dk.mdm.model.query.mst.CustomerQuery;
import com.dk.mdm.model.response.mst.CusFollowResponse;
import com.dk.mdm.model.response.mst.CustomerResponse;
import com.dk.common.model.response.mst.StaffResponse;
import com.dk.mdm.model.vo.mst.CusFollowVO;
import com.dk.mdm.model.vo.mst.MeasureReceiptVO;
import com.dk.mdm.service.common.CommonService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Transactional
public class CusFollowService extends BaseService<CusFollow> {

    @Override
    public BaseMapper<CusFollow> getRepository() {
        return cusFollowMapper;
    }

    @Autowired
    private CusFollowMapper cusFollowMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CusFollowStaffMapper cusFollowStaffMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private CusFollowConvert cusFollowConvert;

    @Autowired
    private StaffMapper staffMapper;


    @Autowired
    private AuthUtils authUtils;

    @Autowired
    private MeasureRoomService measureRoomService;

    @Autowired
    private MeasureReceiptService measureReceiptService;
    @Autowired
    private MeasureReceiptMapper measureReceiptMapper;

    @Autowired
    private MeasureRoomMapper measureRoomMapper;


    @Autowired
    private MeasureReceiptConvert measureReceiptConvert;

    /**
     * @desc : 重写主键
     * @author : 于继渤
     * @date : 2024/2/29 20:29
     */
    @Override
    public String getPrimaryKey() {
        return "follow_id";
    }


    /**
     * @desc : 查询
     * @author : 于继渤
     * @date : 2023/1/5 9:39
     */
    @Pagination
    public ResponseResultVO<PageList<CusFollowResponse>> selectByCond(CusFollowQuery cusFollowQuery) {
        return super.mergeListWithCount(cusFollowQuery, cusFollowMapper.selectByCond(cusFollowQuery),
                cusFollowMapper.countByCond(cusFollowQuery));
    }

    public ResponseResultVO<List<CusFollowResponse>> selectByList(CusFollowQuery cusFollowQuery) {
        return ResponseResultUtil.success(cusFollowMapper.selectByList(cusFollowQuery));
    }

    /**
     * @desc : 跟进id查询
     * @author : 于继渤
     * @date : 2023/1/5 9:39
     */
    public ResponseResultVO<CusFollowResponse> selectById(CusFollowQuery cusFollowQuery) {
        CusFollowResponse cusFollowResponse = cusFollowMapper.selectByCond(cusFollowQuery).get(0);

        if (cusFollowResponse.getFollowId() != null && cusFollowResponse.getMeasureStatus()!=null &&cusFollowResponse.getMeasureStatus().equals(Constant.BasicDataConstant.MEASURE_STATUS_1.getValue())) {
            //已量尺
            MeasureReceipt measureReceipts = measureReceiptMapper.selectByFollowId(new MeasureReceipt().setFollowId(cusFollowResponse.getFollowId()));
            cusFollowResponse.setMeasureReceipt(measureReceipts);
            //查询 空间
            List<MeasureRoom> measureRooms = measureRoomMapper.selectByReceiptId(new MeasureRoom().setReceiptId(measureReceipts.getReceiptId()));
            cusFollowResponse.setMeasureRoomList(measureRooms);
        }
        return ResponseResultUtil.success(cusFollowResponse);
    }

    /**
     * @desc : 新建
     * @author : 于继渤
     * @date : 2023/1/5 9:39
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> insert(CusFollowVO cusFollowVO) {
        CusFollow cusFollow = cusFollowConvert.convertToPo(cusFollowVO);
        //设置ID
        Map<String, Object> uniqueNoteCode = commonService.getUniqueNoteCode(Constant.docNameConstant.CUSTOMERFOLLOW.getName(), true);
        cusFollow.setFollowId(uniqueNoteCode.get("outId").toString());
        //跟进时间
        cusFollow.setFollowTime(LocalDateTime.now());
        //跟进人
        cusFollow.setFollowStaff(authUtils.getStaff().getStaffId());
        //跟进部门
//        cusFollow.setFollowOrg(authUtils.getStaff().getOrgId());
        if (cusFollowVO.getCusId() != null) {
            //查询客户
            Customer customer = customerMapper.selectById(cusFollowVO.getCusId());

            // 查询跟进人是否存在
            CusFollowStaff followStaff = cusFollowStaffMapper.selectByCusFollowStaffId(cusFollowVO.getCusId(), authUtils.getStaff().getStaffId());
            //追加跟进人表
            if (followStaff == null) {
                cusFollowStaffMapper.insert(new CusFollowStaff()
                        .setCusId(cusFollowVO.getCusId())
                        .setFollowStaff(authUtils.getStaff().getStaffId())
                        .setLastFollowId(authUtils.getStaff().getStaffId())
                        .setLastFollowTime(LocalDateTime.now())
                        .setCpId(authUtils.getStaff().getCpId())
                        .setLastFollowStatus(cusFollowVO.getFollowStatus())
                        .setFollowCount(1)
                );
            }
            //追加跟进人
            List<Long> users = new ArrayList<>();
            Object o = customerMapper.selectFollowStaffs(cusFollowVO.getCusId());
            if (o != null && o instanceof Long[]) {
                users = Arrays.asList((Long[]) o);
            }

            if (users == null || users.size() == 0 || (users != null && users.stream().allMatch(Objects::isNull))) {
                users = new ArrayList<>();
            }


            //公海客户跟进后 变成潜客状态
            if (Constant.saleCustomerStatusConstant.SALE_STATUS_INTE.getName().equals(customer.getSaleStatus())) {
                customer.setSaleStatus(Constant.saleCustomerStatusConstant.SALE_STATUS_POTE.getName());
            }
            //已流失客户重新接待后应该变成潜客
            if (Constant.saleCustomerStatusConstant.SALE_STATUS_LOST.getName().equals(customer.getSaleStatus())) {
                customer.setSaleStatus(Constant.saleCustomerStatusConstant.SALE_STATUS_POTE.getName());
            }

            //放入公海客户，清除跟进人
            if (Constant.IntentionConstant.SEA.getValue().equals(cusFollowVO.getIntention())) {
                customer.setFollowStaffs(new ArrayList<>());
                customer.setSaleStatus(Constant.saleCustomerStatusConstant.SALE_STATUS_INTE.getName());
            } else {
                if (!users.contains(authUtils.getStaff().getStaffId())) {
                    List arrList = new ArrayList(users);
                    arrList.add(authUtils.getStaff().getStaffId());
                    customer.setFollowStaffs(arrList);
                }
            }
            //已流失客户，修改状态为流失
            if (Constant.IntentionConstant.LOST.getValue().equals(cusFollowVO.getIntention())) {
                customer.setSaleStatus(Constant.saleCustomerStatusConstant.SALE_STATUS_LOST.getName());
            }

            //如果不是留资接待 修改客户信息
            if (!Constant.BasicDataConstant.FOLLOW_STATUS_4.getValue().equals(cusFollowVO.getFollowStatus())) {
                customer.setCusName(cusFollowVO.getCusName());
                customer.setCusPhone(cusFollowVO.getCusPhone());
                customer.setAddressName(cusFollowVO.getAddressName());
                customer.setAddressNo(cusFollowVO.getAddressNo());
                customer.setAddressGcj02(cusFollowVO.getAddressGcj02());
                customer.setAddressFull(cusFollowVO.getAddressFull());
                customer.setAddressArea(cusFollowVO.getAddressArea());
            }
            customer.setCpId(authUtils.getStaff().getCpId());
            // 同商户 电话不同
            List<CustomerResponse> cusList = customerMapper.selectByCond(
                    new CustomerQuery().setCpId(customer.getCpId()).setCusPhone(customer.getCusPhone()).setFlgValid(true)
            );
//            if (cusList != null && cusList.size() > 0 && cusList.stream().anyMatch(a -> !a.getCusId().equals(customer.getCusId()))) {
//                throw new BaseBusinessException(ErrorCodeEnum.CUSTOMER_SAME_COMPANY_TELEPHONE.getCode(),
//                        ErrorCodeEnum.CUSTOMER_SAME_COMPANY_TELEPHONE.getMessage());
//            }
            customer.setLastFollowId(cusFollow.getFollowId());
            customer.setLastFollowTime(cusFollow.getFollowTime());
            customer.setLastFollowStaff(cusFollow.getFollowStaff());
            //修改跟进次数
            customer.setFollowCount(customer.getFollowCount() + 1);
            customerService.updateByUuid(customer);
        } else if (cusFollowVO.getCusPhone() != null && cusFollowVO.getCusName() != null) {
            //留资接待 新建客户
            Customer customer = new Customer();
            //设置编码
            Map<String, Object> customerNoteCode = commonService.getUniqueNoteCode(Constant.docNameConstant.CUSTOMER.getName(), true);
            customer.setCusId(customerNoteCode.get("outId").toString());
            customer.setCusCode(customerNoteCode.get("outNote").toString());
            //TODO  渠道 取当前登录人员工的渠道
            customer.setChannelId("10112024-0302-0000-0000-00000759d8a4");
            customer.setCusName(cusFollowVO.getCusName());
            customer.setCusPhone(cusFollowVO.getCusPhone());
            customer.setAddressName(cusFollowVO.getAddressName());
            customer.setAddressNo(cusFollowVO.getAddressNo());
            customer.setAddressGcj02(cusFollowVO.getAddressGcj02());
            customer.setAddressFull(cusFollowVO.getAddressFull());
            customer.setAddressArea(cusFollowVO.getAddressArea());
            customer.setReportStaff(authUtils.getStaff().getStaffId());
            customer.setReportTime(LocalDateTime.now());
            customer.setCpId(authUtils.getStaff().getCpId());
            customer.setStaffId(authUtils.getStaff().getStaffId());
            customer.setOrgId(cusFollowVO.getFollowOrg());
            customer.setFollowCount(1);
            customer.setLastFollowId(cusFollow.getFollowId());
            customer.setLastFollowTime(cusFollow.getFollowTime());
            customer.setLastFollowStaff(cusFollow.getFollowStaff());
            cusFollow.setCusId(customer.getCusId());
            // 同商户 电话不同
            Long count = customerMapper.countByCond(
                    new CustomerQuery().setCpId(customer.getCpId()).setCusPhone(customer.getCusPhone()).setFlgValid(true)
            );
//            if (count > 0) {
//                return ResponseResultUtil.error(ErrorCodeEnum.CUSTOMER_SAME_COMPANY_TELEPHONE.getCode(),
//                        ErrorCodeEnum.CUSTOMER_SAME_COMPANY_TELEPHONE.getMessage());
//            }

            //放入公海客户，清除跟进人
            if (Constant.IntentionConstant.SEA.getValue().equals(cusFollowVO.getIntention())) {
                customer.setFollowStaffs(new ArrayList<>());
                customer.setSaleStatus(Constant.saleCustomerStatusConstant.SALE_STATUS_INTE.getName());
            } else {
                //当前跟进人（业务员）
                customer.setFollowStaffs(new ArrayList<String>() {{
                    add(authUtils.getStaff().getStaffId());
                }});
                customer.setSaleStatus(Constant.saleCustomerStatusConstant.SALE_STATUS_POTE.getName());
            }


            //新建客户或编辑客户
            customerMapper.insert(customer);


        }


        // 约量尺
        if (Constant.BasicDataConstant.FOLLOW_STATUS_3.getValue().equals(cusFollow.getFollowStatus())) {
            // 量尺状态：待量尺
            cusFollow.setMeasureStatus(Constant.BasicDataConstant.MEASURE_STATUS_2.getValue());
        }
        if (cusFollow.getFollowData() == null) {
            cusFollow.setFollowData("无");
        }
        super.insert(cusFollow);


        //设计师
        StaffResponse designStaff = null;
        if (cusFollow.getDesignStaff() != null) {

            designStaff = staffMapper.selectById(cusFollow.getDesignStaff());

        }

        // 约尺 同意邀约 有设计师 设计师绑定企微
        boolean pushFlag = Constant.BasicDataConstant.FOLLOW_STATUS_3.getValue().equals(cusFollow.getFollowStatus()) &&
                Constant.BasicDataConstant.FOLLOW_INVITE_RESULT.getValue().equals(cusFollow.getInviteResult()) &&
                designStaff != null;

        if (cusFollow.getNextFollowTime() != null || pushFlag) {
            // 保存跟进信息
            //  saveToXxlJob(cusFollow);
        }

        return ResponseResultUtil.success();
    }


/**
 * @desc : 保存跟进信息到xxl job
 * @author : 于继渤海
 * @date : 2022-05-27 09:53
 */
//    @Transactional(rollbackFor = {Exception.class})
//    public void saveToXxlJob(CusFollow cusFollow) {
//
//        Long nextId = followPlanMapper.getNextId();
//
//
//        // 约量尺 && 接受邀约
////        预约量尺，邀约结果接受，通知设计师提醒时间是(服务时间)；邀约结果拒绝，通知创建者提醒时间是(提醒时间)
//        if (Constant.BasicDataConstant.FOLLOW_STATUS_3.getValue().equals(follow.getFollowStatus()) &&
//                Constant.BasicDataConstant.FOLLOW_INVITE_RESULT.getValue().equals(follow.getInviteResult())) {
//            follow.setNextFollowTime(follow.getInviteTime()).setFollowUser(follow.getDesignUser());
//        }
//
//        int id = xxlJobUtils.create(Math.toIntExact(
//                (follow.getNextFollowTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() - System.currentTimeMillis()) / 1000
//        ), nextId, Constant.XxlJobInfo.FOLLOW.getValue());
//
//
//        // 生成主键
//        followPlanMapper.insert(
//                new FollowPlan().setPlanId(nextId).setCustomerId(follow.getCustomerId())
//                        .setPlanType(Constant.IntegerConstant.PLAN_TYPE_FOLLOW.getValue())
//                        .setFollowId(follow.getFollowId())
//                        .setFollowUser(follow.getFollowUser())
//                        .setNextFollowPlan(follow.getNextFollowPlan())
//                        .setNextFollowTime(follow.getNextFollowTime())
//                        .setXxlJobId(id)
//                        .setCpId(follow.getCpId())
//        );
//    }

    /**
     * @desc : 新建量尺回执
     * @author : 于继渤
     * @date : 2023/1/5 9:39
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> saveMeasure(CusFollowVO cusFollowVO) {
        CusFollow cusFollow = cusFollowConvert.convertToPo(cusFollowVO);
        //更新总单
        //  int update = cusFollowMapper.updateMeasure(cusFollow);
        //更新客户信息
        Customer customer = new Customer();
        customer.setCusId(cusFollowVO.getCusId());
        customer.setCusName(cusFollowVO.getCusName());
        customer.setCusPhone(cusFollowVO.getCusPhone());

        customer.setAddressName(cusFollowVO.getAddressName());
        customer.setAddressNo(cusFollowVO.getAddressNo());
        customer.setAddressFull(cusFollowVO.getAddressFull()); //全路径地址
        customer.setAddressArea(cusFollowVO.getAddressArea()); //省市区
        customer.setAddressGcj02(cusFollowVO.getAddressGcj02());//经纬度
        customerService.updateByUuid(customer);


        CusFollow Follow = cusFollowMapper.selectById(cusFollowVO.getFollowId());
        if (Follow == null) {
            return ResponseResultUtil.error(ResponseCodeEnum.SELECT_NULL);
        } else if (Constant.BasicDataConstant.MEASURE_STATUS_1.getValue().equals(Follow.getMeasureStatus())) {
            return ResponseResultUtil.error(ErrorCodeEnum.CUSTOMER_FOLLOW_MEASURE_STATUS_DONE.getCode(),
                    ErrorCodeEnum.CUSTOMER_FOLLOW_MEASURE_STATUS_DONE.getMessage());
        }

        StaffEntity staff = authUtils.getStaff();

        //设置id
        Map<String, Object> uniqueNoteCode = commonService.getUniqueNoteCode(Constant.docNameConstant.RECEIPT.getName(), true);
        // 新建一条量尺记录
        MeasureReceipt measureReceipt = new MeasureReceipt();
        if (cusFollowVO.getFlgAgainMeasure() != null) {
            measureReceipt.setFlgAgainMeasure(cusFollowVO.getFlgAgainMeasure());
        } else {
            measureReceipt.setFlgAgainMeasure(false);
        }

        measureReceipt.setReceiptId(uniqueNoteCode.get("outId").toString());
        measureReceipt.setCusId(cusFollowVO.getCusId());
        measureReceipt.setFollowId(cusFollowVO.getFollowId());
        measureReceipt.setMeasureStatus(Constant.BasicDataConstant.MEASURE_STATUS_1.getValue());
        measureReceipt.setMeasureTime(LocalDateTime.now());
        measureReceipt.setMeasureRemarks(cusFollowVO.getMeasureRemarks());
        //剩下参数有前台传
        measureReceiptService.insert(measureReceipt);

        //     新建空间
        if (cusFollowVO.getMeasureRoomList() != null && cusFollowVO.getMeasureRoomList().size() > 0) {
            for (MeasureRoom measureRoom : cusFollowVO.getMeasureRoomList()) {
                //设置ID
                Map<String, Object> uniqueNoteCode1 = commonService.getUniqueNoteCode(Constant.docNameConstant.ROOM.getName(), true);
                measureRoom.setRoomId(uniqueNoteCode1.get("outId").toString());
                measureRoom.setFollowId(cusFollowVO.getFollowId());
                measureRoom.setCusId(cusFollowVO.getCusId());
                measureRoom.setCpId(authUtils.getStaff().getCpId());
                measureRoom.setReceiptId(measureReceipt.getReceiptId());
                measureRoomService.insert(measureRoom);
            }
        }

        //修改量尺状态为  已量尺
        cusFollow.setMeasureStatus(Constant.BasicDataConstant.MEASURE_STATUS_1.getValue());
        //修改跟进
        super.updateByUuid(cusFollow);


        return ResponseResultUtil.success();
    }


    /**
     * @desc : 编辑量尺回执
     * @author : 于继渤
     * @date : 2023/1/5 9:39
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> updateMeasure(MeasureReceiptVO measureReceipt) {
        //     新建空间
        if (measureReceipt.getMeasureRoomList() != null && measureReceipt.getMeasureRoomList().size() > 0) {

            for (MeasureRoom measureRoom : measureReceipt.getMeasureRoomList()) {
                if (measureRoom.getRoomId() != null) {
                    measureRoomMapper.deleteByUuid(measureRoom.getRoomId());
                    //设置ID
                    Map<String, Object> uniqueNoteCode1 = commonService.getUniqueNoteCode(Constant.docNameConstant.ROOM.getName(), true);
                    measureRoom.setRoomId(uniqueNoteCode1.get("outId").toString());
                    measureRoom.setFollowId(measureReceipt.getFollowId());
                    measureRoom.setCusId(measureReceipt.getCusId());
                    measureRoom.setCpId(authUtils.getStaff().getCpId());
                    measureRoom.setReceiptId(measureReceipt.getReceiptId());
                    measureRoomService.insert(measureRoom);
                }


            }
            MeasureReceipt measureReceipt1 = measureReceiptConvert.convertToPo(measureReceipt);
            measureReceiptService.updateByUuid(measureReceipt1);
        }
        return ResponseResultUtil.success();
    }


    /**
     * @desc : 编辑
     * @author : 于继渤
     * @date : 2024-03-13 17:03
     */
    @Transactional(rollbackFor = {Exception.class})
    public ResponseResultVO<?> update(CusFollowVO cusFollowVO) {
        CusFollow cusFollow = cusFollowConvert.convertToPo(cusFollowVO);

        //编辑时更改客户意向要把对应客户也需要更改
        if (cusFollowVO.getSaleStatus() != null && (cusFollowVO.getSaleStatus().equals(Constant.saleCustomerStatusConstant.SALE_STATUS_INTE.getName()) || cusFollowVO.getSaleStatus().equals(Constant.saleCustomerStatusConstant.SALE_STATUS_LOST.getName()))) {
            //公海客户清空跟进人
            if (cusFollowVO.getSaleStatus().equals(Constant.saleCustomerStatusConstant.SALE_STATUS_INTE.getName())) {
                customerMapper.updateFollowStaffs(new Customer().setCusId(cusFollowVO.getCusId()));
            }


        }
        if (cusFollowVO.getCusId() != null) {
            Customer customer = new Customer();
            customer.setCusId(cusFollowVO.getCusId());
            customer.setAddressName(cusFollowVO.getAddressName());
            customer.setAddressNo(cusFollowVO.getAddressNo());
            customer.setCusPhone(cusFollowVO.getCusPhone());
            customer.setCusName(cusFollowVO.getCusName());
            customer.setOrgId(cusFollowVO.getFollowOrg());
            customer.setAddressFull(cusFollowVO.getAddressFull());
            customer.setAddressArea(cusFollowVO.getAddressArea());
            customer.setSaleStatus(cusFollowVO.getSaleStatus());
            customer.setAddressGcj02(cusFollowVO.getAddressGcj02());
            //更新客户信息
            customerService.updateByUuid(customer);
        } else {
            //不是陌生接待
            if(!cusFollowVO.getFollowStatus().equals(Constant.BasicDataConstant.FOLLOW_STATUS_4.getValue())){
                StaffEntity staff = authUtils.getStaff();
                Customer customer = new Customer();
                customer.setCusName(cusFollowVO.getCusName());
                customer.setCusPhone(cusFollowVO.getCusPhone());
                customer.setAddressName(cusFollowVO.getAddressName());
                customer.setAddressNo(cusFollowVO.getAddressNo());
                customer.setOrgId(cusFollowVO.getFollowOrg());
                customer.setAddressFull(cusFollowVO.getAddressFull());
                customer.setAddressArea(cusFollowVO.getAddressArea());
                customer.setSaleStatus(cusFollowVO.getSaleStatus());
                customer.setAddressGcj02(cusFollowVO.getAddressGcj02());
                customer.setReportStaff(cusFollowVO.getFollowStaff());
                customer.setReportTime(LocalDateTime.now());
                customer.setCpId(staff.getCpId());
                List<String> list = new ArrayList<>();
                list.add(staff.getStaffId());
                customer.setFollowStaffs(list);
                customer.setSaleStatus("客成状态-潜客");
                customer.setChannelId(cusFollowVO.getChannelId());
                Map<String, Object> customerNoteCode = commonService.getUniqueNoteCode(Constant.docNameConstant.CUSTOMER.getName(), true);
                customer.setCusId(customerNoteCode.get("outId").toString());
                //新建客户
                customerMapper.insert(customer);
                cusFollow.setCusId(customer.getCusId());
            }

        }
        //更新总单
        super.updateByUuid(cusFollow);
        return ResponseResultUtil.success();

    }
}
