package com.wgb.system.service.service;

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.wgb.system.service.component.SmsUtil;
import com.wgb.system.service.domain.mapper.BusinessCategoryMapper;
import com.wgb.system.service.domain.mapper.BusinessMapper;
import com.wgb.system.service.domain.mapper.RegionMapper;
import com.wgb.system.service.domain.mapper.SysMapMapper;
import com.wgb.system.service.domain.mapper.UserMapper;
import com.wgb.system.service.domain.mapper.UserTaskMapper;
import com.wgb.system.service.domain.model.Business;
import com.wgb.system.service.domain.model.BusinessCategory;
import com.wgb.system.service.domain.model.Region;
import com.wgb.system.service.domain.model.User;
import com.wgb.system.service.domain.model.UserTask;
import com.wgb.system.service.domain.request.BusinessRequest;
import com.wgb.system.service.domain.request.BusinessTask;
import com.wgb.system.service.domain.response.LayuiTableResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BusinessService extends ServiceBase{

    private final BusinessMapper businessMapper;
    private final BusinessCategoryMapper businessCategoryMapper;
    private final UserMapper userMapper;
    private final UserTaskMapper userTaskMapper;
    private final RegionMapper regionMapper;
    private final SysMapMapper sysMapMapper;

    @Autowired
    public BusinessService(BusinessMapper businessMapper,UserMapper userMapper,UserTaskMapper userTaskMapper,RegionMapper regionMapper,BusinessCategoryMapper businessCategoryMapper,SysMapMapper sysMapMapper) {
        this.businessMapper = businessMapper;
        this.userMapper=userMapper;
        this.userTaskMapper=userTaskMapper;
        this.regionMapper=regionMapper;
        this.businessCategoryMapper=businessCategoryMapper;
        this.sysMapMapper=sysMapMapper;
    }


    public LayuiTableResponse getBusinessList(BusinessRequest businessRequest){
        QueryWrapper<Business> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(Business::getCreateTime);
        if (StringUtils.isNotBlank(businessRequest.getQueryUserPhone())){
            queryWrapper.lambda().like(Business::getUserCellphone,businessRequest.getQueryUserPhone());
        }
        if (StringUtils.isNotBlank(businessRequest.getQueryMaintenanceState())){
            queryWrapper.lambda().eq(Business::getMaintenanceState,businessRequest.getQueryMaintenanceState());
        }
        IPage<Business>iPage=new Page<>(businessRequest.getPage(),businessRequest.getLimit());
        IPage<Business> pageList= businessMapper.selectPage(iPage,queryWrapper);
        return new LayuiTableResponse(0,"",pageList.getTotal(),pageList.getRecords());
    }


    public boolean saveOrUpdate(Business business){
//        SysMap sysMap= sysMapMapper.selectOne(new QueryWrapper<SysMap>().lambda().eq(SysMap::getAdcode,business.getRegionId()));
        BusinessCategory businessCategory= businessCategoryMapper.selectOne(new QueryWrapper<BusinessCategory>().lambda().eq(BusinessCategory::getId,business.getCategoryId()));
        switch (business.getInstallType()){
            case "installationPrice":business.setRepairPrice(businessCategory.getUserInstallationPrice());
            case "modifyPrice":business.setRepairPrice(businessCategory.getModifyPrice());
            case "openingPrice":business.setRepairPrice(businessCategory.getUserOpeningPrice());
            case "newOpeningPrice":business.setRepairPrice(businessCategory.getUserNewOpeningPrice());
        }
        if (business.getId()==null){
            business.setBusinessNo(System.currentTimeMillis()+RandomStringUtils.random(4, false, true));//时间戳+随机4位数字
            business.setCreateTime(LocalDateTime.now());
            businessMapper.insert(business);
        }else{
            businessMapper.updateById(business);
        }
        return true;
    }

    public Business getBusinessById(Long id){
       return businessMapper.selectOne(new QueryWrapper<Business>().lambda().eq(Business::getId,id));
    }

    @Transactional
    public void deleteBusinessById(String ids){
        for (String id:ids.split(",")){
            businessMapper.deleteById(id);
        }
    }

    public void pushTask(BusinessTask businessTask)throws Exception{
        QueryWrapper<Business> businessQueryWrapper=new QueryWrapper<>();
        businessQueryWrapper.lambda().eq(Business::getBusinessNo,businessTask.getBusinessNo());
        Business business=businessMapper.selectOne(businessQueryWrapper);
        handlerBusines(business);

        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.lambda().eq(User::getUserNo,businessTask.getUserNo());
        User user=userMapper.selectOne(userQueryWrapper);
        handlerUser(user);

        UserTask userTask=userTaskMapper.getlastUserTask(business.getId());
        handlerUserTask(userTask,user.getId());

        business.setRepairId(user.getId());
        business.setMaintenanceState(1);
        businessMapper.updateById(business);
        userTaskMapper.insert(new UserTask(business.getId(),user.getId(),LocalDateTime.now()));

        QueryWrapper<Region> regionQueryWrapper=new QueryWrapper<>();
        regionQueryWrapper.lambda().in(Region::getId,business.getProvinceId(),business.getCity(),business.getRegionId()).orderByAsc(Region::getId);
        List<Region> regionList= regionMapper.selectList(regionQueryWrapper);
        StringBuffer addressBuffer=new StringBuffer();
        regionList.stream().forEach(i->{
            addressBuffer.append(i.getRegionName());
        });
        String address=addressBuffer.toString()+business.getAddress();
        //发送短信
        SmsUtil.pushBusinessSMS(user.getUserCellphone(),user.getName(),business.getUserName(),business.getUserCellphone(),address);
    }


    public List<Business> getUseBusinessInfo(String userCellphone, Long repairId){
        QueryWrapper<Business> queryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotBlank(userCellphone)){
            queryWrapper.lambda().eq(Business::getUserCellphone,userCellphone);
        }
        if(repairId!=null){
            queryWrapper.lambda().eq(Business::getRepairId,repairId);
        }
        return businessMapper.selectList(queryWrapper);
    }

}
