package cn.iocoder.yudao.module.inspection.service.impl;

import java.util.*;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.shop.entity.ShopConfig;
import cn.iocoder.yudao.module.shop.service.IShopConfigService;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.SendSmsUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.iocoder.yudao.util.DateUtils;
import cn.iocoder.yudao.util.StringUtils;
import cn.iocoder.yudao.module.inspection.entity.InspectionAppointment;
import cn.iocoder.yudao.module.inspection.entity.InspectionGoodsSku;
import cn.iocoder.yudao.module.inspection.entity.InspectionPickCar;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionGoods;
import cn.iocoder.yudao.module.inspection.mapper.InspectionAppointmentMapper;
import cn.iocoder.yudao.module.inspection.service.*;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static cn.iocoder.yudao.util.DistanceUtil.getDistanceMeter;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-24
 */
@Service
public class InspectionAppointmentServiceImpl extends ServiceImpl<InspectionAppointmentMapper,InspectionAppointment> implements IInspectionAppointmentService
{

    @Autowired
    private AppInspectionPartnerService partnerService;
    @Autowired
    private AppInspectionGoodsService goodsService;
    @Autowired
    private InspectionGoodsSkuService skuService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    private IShopConfigService configService;
    @Autowired
    private IInspectionPickCarService pickCarService;
    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public InspectionAppointment selectInspectionAppointmentById(Long id)
    {
        return baseMapper.selectInspectionAppointmentById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param inspectionAppointment 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public IPage<InspectionAppointment> selectInspectionAppointmentList(Page<InspectionAppointment> page, InspectionAppointment inspectionAppointment)
    {
        return baseMapper.selectInspectionAppointmentList(page,inspectionAppointment);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param inspectionAppointment 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertInspectionAppointment(InspectionAppointment inspectionAppointment)
    {
        return baseMapper.insertInspectionAppointment(inspectionAppointment);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param inspectionAppointment 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateInspectionAppointment(InspectionAppointment inspectionAppointment)
    {
        inspectionAppointment.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateInspectionAppointment(inspectionAppointment);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteInspectionAppointmentByIds(Long[] ids)
    {
        return baseMapper.deleteInspectionAppointmentByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteInspectionAppointmentById(Long id)
    {
        return baseMapper.deleteInspectionAppointmentById(id);
    }

    @Override
    public Long appointmentInspection(InspectionAppointment appointment) {
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        appointment.setUserId(loginUser.getId());
        AdminUserDO ownUser = userService.getUser(loginUser.getId());
        InspectionGoodsSku sku = skuService.getById(appointment.getSkuId());
        ShopInspectionGoods goods = goodsService.getById(sku.getGoodsId());
        appointment.setPartnerId(Long.parseLong(goods.getPartnerId().toString()));
        appointment.setGoodsTitle(goods.getTitle()+"-"+sku.getSkuName());
        appointment.setGoodsId(goods.getId());

        //预约到店需要下发短信
        try {
            ShopMallPartners partners = partnerService.getById(goods.getPartnerId());
            AdminUserDO sysUser = userService.getUser(partners.getUserId());

            if (appointment.getIsPickCar().equals("0")){
                if (StringUtils.isNotEmpty(appointment.getOtherPhone())){
                    //给联系人发送
                    SendSmsUtil.sendMsgCommon(new String[]{Optional.ofNullable(appointment.getCarNo()).orElse(""),
                            appointment.getAppointmentDay(),partners.getPartnerName(),partners.getAddress(),sysUser.getNickname()+" "+sysUser.getMobile()
                    },appointment.getOtherPhone(),"1400852709","机动车管家小程序","2112754");

                }else {
                    //给本人发送
                    //给联系人发送
                    SendSmsUtil.sendMsgCommon(new String[]{Optional.ofNullable(appointment.getCarNo()).orElse(""),
                            appointment.getAppointmentDay(),partners.getPartnerName(),partners.getAddress(),sysUser.getNickname()+" "+sysUser.getMobile()
                    },ownUser.getMobile(),"1400852709","机动车管家小程序","2112754");
                }
        }else {
                if (StringUtils.isNotEmpty(appointment.getOtherPhone())){
                    //给联系人发送
                    SendSmsUtil.sendMsgCommon(new String[]{Optional.ofNullable(appointment.getCarNo()).orElse("")
                            ,partners.getPartnerName(),sysUser.getNickname(),sysUser.getMobile()
                    },appointment.getOtherPhone(),"1400852709","机动车管家小程序","2112792");

                }else {
                    //给本人发送
                    //给联系人发送
                    SendSmsUtil.sendMsgCommon(new String[]{Optional.ofNullable(appointment.getCarNo()).orElse("")
                            ,partners.getPartnerName(),sysUser.getNickname(),sysUser.getMobile()
                    },ownUser.getMobile(),"1400852709","机动车管家小程序","2112792");
                }
            }
            //给检测站发送
            //给联系人发送
            SendSmsUtil.sendMsgCommon(new String[]{Optional.ofNullable(appointment.getCarNo()).orElse("")
                    ,appointment.getGoodsTitle()
            },sysUser.getMobile(),"1400852709","机动车管家小程序","2112868");
        }catch (Exception ignored){
            log.error(ignored.getMessage());
        }
        baseMapper.insert(appointment);
        return appointment.getId();
    }

    @Override
    public Long editAppointment(InspectionAppointment appointment) {

        //判断是否需要删除上门取车
        InspectionAppointment oldAppointment = baseMapper.selectById(appointment.getId());
        if (oldAppointment.getIsPickCar().equals("1")&&appointment.getIsPickCar().equals("0")){
            pickCarService.removeById(oldAppointment.getPickCarId());
        }
        if (oldAppointment.getIsPickCar().equals("1")&&appointment.getIsPickCar().equals("1")){
            if(!oldAppointment.getPickCarId().equals(appointment.getPickCarId())){
                pickCarService.removeById(oldAppointment.getPickCarId());
            }
        }

        baseMapper.updateById(appointment);
        try {
            //取消预约发送短信
            ShopMallPartners partners = partnerService.getById(oldAppointment.getPartnerId());
            AdminUserDO sysUser = userService.getUser(partners.getUserId());
            //给检测站发送
            //给联系人发送
            SendSmsUtil.sendMsgCommon(new String[]{Optional.ofNullable(oldAppointment.getCarNo()).orElse("")},
                    sysUser.getMobile(),"1400852709","机动车管家小程序","2112863");

        }catch (Exception e){

        }

        return appointment.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delAppointment(Long appointmentId) {
        InspectionAppointment oldAppointment = baseMapper.selectById(appointmentId);
        if (ObjectUtil.isNotEmpty(oldAppointment.getOrderId())){
            baseMapper.deleteById(appointmentId);

        }else {
            baseMapper.deleteById(appointmentId);
            if (ObjectUtil.isNotEmpty(oldAppointment.getPickCarId())){
                pickCarService.removeById(oldAppointment.getPickCarId());

            }
        }
        //取消预约发送短信
        ShopMallPartners partners = partnerService.getById(oldAppointment.getPartnerId());
        AdminUserDO sysUser = userService.getUser(partners.getUserId());
        //给检测站发送
        //给联系人发送
        SendSmsUtil.sendMsgCommon(new String[]{Optional.ofNullable(oldAppointment.getCarNo()).orElse("")},
                sysUser.getMobile(),"1400852709","机动车管家小程序","2112869");
    }

    @Override
    public Long pickCarInspection(InspectionPickCar pickCar) throws Exception {
        JSONObject jsonObject = this.computeDistanceAndPrice(pickCar.getGoodsId(), pickCar.getLongitude(), pickCar.getLatitude(),pickCar.getType());
        if (pickCar.getType().equals("sku")){
            InspectionGoodsSku goodsSku = skuService.getById(pickCar.getGoodsId());
            pickCar.setGoodsId(Long.parseLong(goodsSku.getGoodsId().toString()));
        }
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        pickCar.setUserId(loginUser.getId());
        pickCar.setDistance(jsonObject.getLong("distance"));
        pickCar.setNeedPrice(jsonObject.getLong("pickPrice"));
        ShopInspectionGoods goods = goodsService.getById(pickCar.getGoodsId());
        ShopMallPartners partner = partnerService.getById(goods.getPartnerId());
        pickCar.setPartnerId(partner.getPartnerId());
        pickCar.setGoodsTitle(goods.getTitle());
        pickCarService.save(pickCar);
        return pickCar.getId();
    }

    @Override
    public JSONObject appointmentDateList(Long goodsId,String type) {
        if (type.equals("sku")){
            InspectionGoodsSku goodsSku = skuService.getById(goodsId);
            goodsId = Long.parseLong(goodsSku.getGoodsId().toString());
        }
        JSONObject res =new JSONObject();
        List<JSONObject> resList =new ArrayList<>();
        List<Date> sevenDaysList = getSevenDaysList();
        for (Date date : sevenDaysList) {
            JSONObject item =new JSONObject();
            String dateStr = DateUtil.format(date,"yyyy-MM-dd");
            item.put("dateStr",dateStr);
            item.put("weekStr", getDayOfWeek(date));
            LambdaQueryWrapper<InspectionAppointment> queryWrapper  = new LambdaQueryWrapper<>();
            queryWrapper.eq(InspectionAppointment::getAppointmentDay, dateStr).eq(InspectionAppointment::getAppointmentPeriod,"0");
            long morningCount = this.count(queryWrapper);
            queryWrapper  = new LambdaQueryWrapper<>();
            queryWrapper.eq(InspectionAppointment::getAppointmentDay, dateStr).eq(InspectionAppointment::getAppointmentPeriod,"1");
            long afterCount = this.count(queryWrapper);
            item.put("morningCount", morningCount);
            item.put("afterCount", afterCount);
            resList.add(item);

        }
        res.put("dataList",resList);
        ShopInspectionGoods goods = goodsService.getById(goodsId);
        ShopMallPartners partner = partnerService.getById(goods.getPartnerId());
        res.put("partnerName",partner.getPartnerName());
        res.put("address",partner.getAddress());
        res.put("partnerId",partner.getPartnerId());
        return res;
    }

    @Override
    public JSONObject pickCarInfo( ) {
        JSONObject res =new JSONObject();
        List<JSONObject> resList =new ArrayList<>();
        List<Date> sevenDaysList = getSevenDaysList();
        for (Date date : sevenDaysList) {
            JSONObject item =new JSONObject();
            String dateStr = DateUtil.format(date,"yyyy-MM-dd");
            item.put("dateStr",dateStr);
            item.put("weekStr", getDayOfWeek(date));
            resList.add(item);

        }
        res.put("dataList",resList);
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());
        res.put("userPhone",user.getMobile());
        return res;
    }

    @Override
    public JSONObject computeDistanceAndPrice(Long goodsId,Double longitude,Double latitude,String type) throws Exception {
        if (StringUtils.isNotEmpty(type)&&type.equals("sku")){
            InspectionGoodsSku sku = skuService.getById(goodsId);
            goodsId = Long.parseLong(sku.getGoodsId().toString());
        }
        ShopInspectionGoods goods = goodsService.getById(goodsId);
        ShopMallPartners partner = partnerService.getById(goods.getPartnerId());
        JSONObject res =new JSONObject();
        String longitude1 = partner.getLongitude();
        String latitude1 = partner.getLatitude();
        if (StringUtils.isEmpty(longitude1)||StringUtils.isEmpty(latitude1)){
            throw new Exception("超出距离无法上门");
        }
        Long distanceMeter = getDistanceMeter(Double.parseDouble(longitude1), Double.parseDouble(latitude1), longitude, latitude);
        if (distanceMeter>20000){
            throw new Exception("超出距离无法上门");
        }
        res.put("distance",distanceMeter);
        ShopConfig shopConfig = configService.selectShopConfigById(1L);
        //20公里价格
        res.put("pickPrice",shopConfig.getPickCarTwenty());

        if (distanceMeter<10000){
            //10公里价格
            res.put("pickPrice",shopConfig.getPickCarTen());
        }
        if (distanceMeter<5000){
            //5公里价格
            res.put("pickPrice",shopConfig.getPickCarFive());
        }
        return res;
    }

    @Override
    public IPage<InspectionAppointment> getAppointmentList(Page<InspectionAppointment> page, Long partnerId, String phoneNum) {
        return baseMapper.getAppointmentList(page,partnerId,phoneNum);
    }

    @Override
    public List<InspectionAppointment> getAppointmentOwn() {
        //获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();

        return baseMapper.getAppointmentOwn(loginUser.getId());
    }


    public static List<Date> getSevenDaysList() {
        List<Date> sevenDaysList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        sevenDaysList.add(calendar.getTime());
        for (int i = 0; i < 7; i++) {
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            sevenDaysList.add(calendar.getTime());

        }

        return sevenDaysList;
    }
    public static String getDayOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        // 星期日为1，依此类推
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

        String[] weekDays = {"周天", "周一", "周二", "周三", "周四", "周五", "周六"};

        return weekDays[dayOfWeek - 1];
    }
}
