package com.sqx.modules.artificer.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserCertificationService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.artificer.entity.*;
import com.sqx.modules.artificer.service.*;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.utils.excel.ExcelData;
import com.sqx.modules.utils.excel.ExportExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/artificer")
@Api(value = "技师管理", tags = {"技师管理"})
public class ArtificerController {

    @Autowired
    private ArtificerService artificerService;
    @Autowired
    private ArtificerMassageService artificerMassageService;
    @Autowired
    private MassageTypeService massageTypeService;
    @Autowired
    private RealNameService realNameService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private AgencyService agencyService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private RealNameService userCertificationService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private CommonInfoService commonInfoService;

    @PostMapping("/insertMassageType")
    @ApiOperation("添加按摩分类")
    public Result insertMassageType(@RequestBody MassageType massageType){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        massageType.setCreateTime(sdf.format(new Date()));
        massageType.setSales(0);
        massageTypeService.save(massageType);
        return Result.success();
    }

    @PostMapping("/updateMassageType")
    @ApiOperation("修改按摩分类")
    public Result updateMassageType(@RequestBody MassageType massageType){
        massageTypeService.updateById(massageType);
        return Result.success();
    }

    @PostMapping("/updateArtificerMassageStatus")
    @ApiOperation("修改按摩分类")
    public Result updateArtificerMassageStatus(@RequestBody ArtificerMassage artificerMassage){
        artificerMassageService.updateArtificerMassageStatus(artificerMassage);
        return Result.success();
    }

    @PostMapping("/deleteMassageType")
    @ApiOperation("删除按摩分类")
    public Result deleteMassageType(Long massageTypeId){
        massageTypeService.removeById(massageTypeId);
        artificerMassageService.remove(new QueryWrapper<ArtificerMassage>().eq("massage_type_id",massageTypeId));
        return Result.success();
    }


    @GetMapping("/selectMassageTypePage")
    @ApiOperation("查询按摩分类（分页）")
    public Result selectMassageTypePage(Integer page,Integer limit,Integer status,Integer sort,String city,Integer authentication,Integer by,String title,Long artificerId,Long userId,Long parentId,Long classifyId){
        return massageTypeService.selectMassageTypePage(page, limit, status, city, sort,authentication,by,title,artificerId,userId,parentId,classifyId);
    }
    @GetMapping("/selectMassageTypeChildrenPage")
    @ApiOperation("查询按摩分类子项目（分页）")
    public Result selectMassageTypeChildrenPage(Integer page,Integer limit,Integer status,Integer sort,String city,Integer authentication,Integer by,String title,Long artificerId,Long userId,Long parentId,Long classifyId){
        return massageTypeService.selectMassageTypeChildrenPage(page, limit, status, city, sort,authentication,by,title,artificerId,userId,parentId,classifyId);
    }
    @GetMapping("/selectMassageTypeList")
    @ApiOperation("查询按摩分类（不带分页）")
    public Result selectMassageTypeList(Integer status){
        return Result.success().put("data",massageTypeService.list(new QueryWrapper<MassageType>().eq(status!=0,"status",status)));
    }

    @GetMapping("/selectMassageTypeById")
    @ApiOperation("查询详情")
    public Result selectMassageTypeById(Long massageTypeId){
        return Result.success().put("data",massageTypeService.getById(massageTypeId));
    }

    @GetMapping("/selectArtificerList")
    @ApiOperation("查询技师列表")
    public Result selectArtificerList(Integer page, Integer limit, Long massageTypeId, String artificerName,
                                      String longitude,String latitude,Integer sort,Integer authentication,
                                      Integer by,Integer status,String city,Long classifyId,String phone,Integer isStart,Integer technicianType,String isBack){
        return artificerService.selectArtificerList(page, limit, massageTypeId, artificerName,longitude,latitude,
                sort,authentication,by,status,city,classifyId,phone,null,isStart,technicianType,isBack);
    }

    @GetMapping("/selectArtificer")
    @ApiOperation("查询技师列表（不带分页）")
    public Result selectArtificer(String city,String classifyId,String artificerName){
        List<Artificer> artificerList = artificerService.list(new QueryWrapper<Artificer>()
                .eq("status",1)
                .eq(StringUtils.isNotBlank(classifyId),"classify_id",classifyId)
                .like(StringUtils.isNotBlank(artificerName),"artificer_name",artificerName)
                .like(StringUtils.isNotBlank(city), "city", city));
        for(Artificer artificer:artificerList){
            artificer.setServiceCount(ordersService.count(new QueryWrapper<Orders>()
                    .eq("status",2)
                    .eq("artificer_id",artificer.getArtificerId()).isNull("parent_id")));
        }
        return Result.success().put("data",artificerList);
    }

    @GetMapping("/selectArtificerMassageList")
    @ApiOperation("查询技师服务列表")
    public Result selectArtificerMassageList(Long artificerId,Integer status){
        return massageTypeService.selectArtificerMassageList(artificerId,status);
    }

    @GetMapping("/selectArtificerById")
    @ApiOperation("查询技师详情")
    public Result selectArtificerById(Long artificerId){
        return Result.success().put("data",artificerService.selectArtificerById(null,artificerId,null,null));
    }

    @PostMapping("/updateArtificers")
    @ApiOperation("修改技师")
    public Result updateArtificers(@RequestBody Artificer artificer){
        artificerService.updateById(artificer);
        return Result.success();
    }

    @PostMapping("/cancellationSuspension/{userId}")
    @ApiOperation("解除停牌")
    public Result cancellationSuspension(@PathVariable("userId") Long userId){
        userService.update(Wrappers.<UserEntity>lambdaUpdate().eq(UserEntity::getUserId, userId).set(UserEntity::getStatus, 1));
        return Result.success();
    }


    @PostMapping("/deleteArtificer")
    @ApiOperation("删除技师")
    public Result deleteArtificer(Long artificerId){
        Artificer artificer = artificerService.getById(artificerId);
        if(artificer!=null){
            UserEntity userEntity = userService.selectUserById(artificer.getUserId());
            if(userEntity!=null){
                userEntity.setIsAuthentication(0);
                userService.updateById(userEntity);
                realNameService.remove(new QueryWrapper<Certification>().eq("user_id",userEntity.getUserId()));
            }
            artificerService.removeById(artificer.getArtificerId());
        }
        return Result.success();
    }

    @PostMapping("/accomplishOrders")
    @ApiOperation("完成订单")
    public Result accomplishOrders(Long ordersId){
        return ordersService.accomplishOrders(ordersId,1,null,null,null, null,null,null);
    }


    @GetMapping("/selectOrdersList")
    @ApiOperation("查询订单列表")
    public Result selectOrdersList(Long userId,Integer page,Integer limit,Integer status,String city,
                                   String name,String phone,Long artificerId,Long parentId,String startTime,
                                   String endTime,Integer isAdd,String ordersNo,String artificerName,
                                   String oneUserName,String oneArtificerUserName,
                                   String startServeTime,String endServeTime,Integer overTimeOrders,Long shopId,
                                   String shopName,Integer warning,String title,String classifyId, Long userPackageId){
        return ordersService.selectOrdersList(userId, page, limit, status, city, name, phone,
                artificerId, parentId, startTime, endTime, isAdd, ordersNo, artificerName,
                oneUserName, oneArtificerUserName, startServeTime, endServeTime,overTimeOrders,shopId,shopName,warning,title,classifyId, userPackageId);
    }

    @GetMapping("/excelOrdersList")
    @ApiOperation("导出订单列表")
    public void excelOrdersList(Long userId,Integer status,String city,
                                String name,String phone,Long artificerId,Long parentId,String startTime,
                                String endTime,Integer isAdd,String ordersNo,String artificerName,
                                String oneUserName,String oneArtificerUserName,
                                String startServeTime,String endServeTime,Integer overTimeOrders,Long shopId,
                                String shopName,Integer warning,String title,String classifyId, HttpServletResponse response) throws Exception{
        ExcelData excelData = ordersService.excelOrdersList(userId, status, city, name, phone, artificerId, parentId,
                startTime, endTime, isAdd, ordersNo, artificerName, oneUserName, oneArtificerUserName, startServeTime,
                endServeTime,overTimeOrders,shopId,shopName,warning,title,classifyId);
        ExportExcelUtils.exportExcel(response,"订单列表.xlsx",excelData);
    }

    @PostMapping("/deleteOrders")
    @ApiOperation("删除订单")
    public Result deleteOrders(Long ordersId){
        ordersService.removeById(ordersId);
        return Result.success();
    }

    @PostMapping("/cancelOrders")
    @ApiOperation("取消订单")
        public Result cancelOrders(Long ordersId){
        return ordersService.cancelOrders(null,ordersId);
    }

    @PostMapping("/cancelSupplementOrders")
    @ApiOperation("待补单处理及待补单全单退款")
    public Result cancelSupplementOrders(Long ordersId,Integer isAuto,Integer type){
        return ordersService.cancelSupplementOrders(null,ordersId,isAuto,type);
    }

    @PostMapping("/updateOrders")
    @ApiOperation("修改订单")
    public Result updateOrders(@RequestBody Orders orders){
        return ordersService.updateOrders(orders);
    }

    @PostMapping("/refundOrdersMoney")
    @ApiOperation("退款订单（可部分退款）")
    public Result refundOrdersMoney(Long ordersId,BigDecimal refundMoney){
        return ordersService.refundOrdersMoney(ordersId,refundMoney);
    }


    @GetMapping("/selectAgencyList")
    @ApiOperation("查询申请记录")
    public Result selectAgencyList(Integer page,Integer limit,String city,String phone,String userName){
        return Result.success().put("data",agencyService.page(new Page<>(page,limit),new QueryWrapper<Agency>().eq(StringUtils.isNotBlank(city),"city",city).eq(StringUtils.isNotBlank(phone),"phone",phone).eq(StringUtils.isNotBlank(userName),"name",userName).orderByDesc("create_time")));
    }


    @PostMapping("/auditArtificer")
    @ApiOperation("审核申请记录")
    public Result auditArtificer(@RequestBody Certification certification){
        Certification certification1 = userCertificationService.getById(certification.getId());
        Agency agency = agencyService.selectAgencyByUserId(certification1.getUserId());
        if(agency.getStatus().equals(0)){
            agency.setStatus(certification.getStatus());
            if(certification.getStatus().equals(1)){
                UserEntity user = userService.getById(certification1.getUserId());
                certification1.setStatus(1);
                certification1.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                user.setIsAuthentication(2);
                Artificer artificer = artificerService.selectArtificerByUserId(user.getUserId());
                if(artificer==null){
                    artificer=new Artificer();
                    artificer.setStatus(2);
                    artificer.setUserId(certification1.getUserId());
                    artificer.setArtificerSales(0);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    artificer.setCreateTime(sdf.format(new Date()));
                    artificer.setCreditScore(BigDecimal.valueOf(100));
                    artificer.setTripWay(1);
                    artificer.setRate(new BigDecimal(commonInfoService.findOne(381).getValue()));
                }
                artificer.setArtificerName(certification1.getName());
                artificer.setArtificerImg(certification1.getAvatar());
                artificer.setLifePhoto(certification1.getImagePhoto());
                artificer.setCertificate(certification1.getCertification());
                artificer.setContent(certification1.getIndividualResume());
                artificerService.updateById(artificer);

                BigDecimal cashDeposit = certification1.getMoney();
                Long userId = user.getUserId();
                userMoneyDao.updateCashDeposit(1, userId, cashDeposit.doubleValue());
                user.setIsCashDeposit(2);
                userService.updateById(user);
            }
            agencyService.updateById(agency);
        }else{
            return Result.error("已经审核过了！");
        }
        return Result.success();
    }


    @ApiOperation("技师添加服务")
    @PostMapping(value = "insertArtificerMassage")
    public Result insertArtificerMassage(Long userId, String artificerMassages){
        return artificerMassageService.insertArtificerMassage(artificerMassages, userId);
    }

    @ApiOperation("技师删除服务")
    @PostMapping(value = "deleteArtificerMassage")
    public Result deleteArtificerMassage(Long artificerMassageId){
        return artificerMassageService.deleteArtificerMassage(artificerMassageId);
    }

    @ApiOperation("查看商户主页信息")
    @GetMapping(value = "selectArtificerIndex")
    public Result selectArtificerIndex(Long userId,String startTime,String endTime){
        Artificer artificer = artificerService.selectArtificerByUserId(userId);
        return ordersService.selectArtificerIndex(artificer.getArtificerId(),startTime,endTime);
    }

    @ApiOperation("退款订单")
    @PostMapping("/refundOrders")
    public Result refundOrders(Long ordersId){
        return ordersService.refundOrders(ordersId);
    }

    @PostMapping("/updateArtificerCreditScore")
    @ApiOperation("修改技师信誉分")
    public Result updateArtificerCreditScore(Integer type,BigDecimal creditScore,Long artificerId){
        return ordersService.updateArtificerCreditScore(type, creditScore, artificerId);
    }

//    @Scheduled(cron = "0 */1 * * * ?")
    public void endOrders(){
        ordersService.endOrders();
    }


    @GetMapping("/selectTeamUserList")
    @ApiOperation("获取团队列表")
    public Result selectTeamUserList(Long userId, Integer page, Integer limit, Integer type){
        UserEntity user = userService.selectUserById(userId);
        return ordersService.selectTeamUserList(page,limit,user.getInvitationCode(),type,userId);
    }


    @PostMapping("/updateArtificer")
    @ApiOperation("技师上线下线")
    public Result updateArtificer(Long userId,String longitude,String latitude,String city){
        Artificer artificer = artificerService.selectArtificerByUserId(userId);
        UserEntity userEntity = userService.selectUserById(userId);
        String value = commonInfoService.findOne(320).getValue();
        if("是".equals(value)){
            if(userEntity.getIsCashDeposit()==null || !userEntity.getIsCashDeposit().equals(2)){
                return Result.error("当前账号未缴纳保证金，暂无法上线接单！");
            }
        }

        if(userEntity.getIsAuthentication()==null || !userEntity.getIsAuthentication().equals(2)){
            return Result.error("当前账号未实名认证，暂无法上线接单！");
        }
        artificer.setLongitude(longitude);
        artificer.setLatitude(latitude);
        artificer.setCity(city);
        if(artificer.getStatus()==1){
            artificer.setStatus(2);
        }else{
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            String time = simpleDateFormat.format(new Date());
//            MessageInfo messageInfo = messageService.selectMessageByUserIdAndTime(userId, time);
//            if(messageInfo==null){
//                return Result.error("您今天还没签到，请签到后进行上线！");
//            }
            artificer.setStatus(1);
        }
        artificerService.updateById(artificer);
        return Result.success();
    }

    @GetMapping("/selectOrdersCountStatisticsByYear")
    @ApiOperation("订单数量统计")
    public Result selectOrdersCountStatisticsByYear(String startTime,String endTime){
        //总数量 1待支付 2待服务 3待评论 4已取消  5已完成  6进行中
        List<Integer> ordersCountList=new ArrayList<>();
        List<Integer> ordersDaiFuKuanCountList=new ArrayList<>();
        List<Integer> ordersDaiFuWuCountList=new ArrayList<>();
        List<Integer> ordersDaiPingLunCountList=new ArrayList<>();
        List<Integer> ordersYiQuXiaoCountList=new ArrayList<>();
        List<Integer> ordersYiWanCengCountList=new ArrayList<>();
        List<Integer> ordersJinxXinZhongCountList=new ArrayList<>();
        List<String> year=new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar=Calendar.getInstance();
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(startTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.setTime(parse);
        while (true){
            String dateTime = simpleDateFormat.format(calendar.getTime());
            //状态 1待支付 2待服务 3待评论 4已取消  5已完成  6进行中
            //总订单数
            Integer ordersCount = ordersService.selectOrdersCountStatisticsByYear(1, dateTime, null);
            ordersCountList.add(ordersCount);
            //待付款
            Integer ordersDaiFuKuanCount = ordersService.selectOrdersCountStatisticsByYear(1, dateTime, 1);
            ordersDaiFuKuanCountList.add(ordersDaiFuKuanCount);
            //2待服务
            Integer ordersJinXinCount = ordersService.selectOrdersCountStatisticsByYear(1, dateTime, 2);
            ordersDaiFuWuCountList.add(ordersJinXinCount);
            //3待评论
            Integer ordersQuXiaoCount = ordersService.selectOrdersCountStatisticsByYear(1, dateTime, 3);
            ordersDaiPingLunCountList.add(ordersQuXiaoCount);
            //4已取消
            Integer ordersBuFeiCount = ordersService.selectOrdersCountStatisticsByYear(1, dateTime, 4);
            ordersYiQuXiaoCountList.add(ordersBuFeiCount);
            //5已完成
            Integer ordersTuiFeiCount = ordersService.selectOrdersCountStatisticsByYear(1, dateTime, 5);
            ordersYiWanCengCountList.add(ordersTuiFeiCount);
            //6进行中
            Integer ordersShenSuCount = ordersService.selectOrdersCountStatisticsByYear(1, dateTime, 6);
            ordersJinxXinZhongCountList.add(ordersShenSuCount);
            year.add(dateTime);
            if(dateTime.equals(endTime)){
                break;
            }
            calendar.add(Calendar.DATE,1);
        }
        Map<String,Object> result=new HashMap<>();
        result.put("ordersCountList",ordersCountList);
        result.put("ordersDaiFuKuanCountList",ordersDaiFuKuanCountList);
        result.put("ordersDaiFuWuCountList",ordersDaiFuWuCountList);
        result.put("ordersDaiPingLunCountList",ordersDaiPingLunCountList);
        result.put("ordersYiQuXiaoCountList",ordersYiQuXiaoCountList);
        result.put("ordersYiWanCengCountList",ordersYiWanCengCountList);
        result.put("ordersJinxXinZhongCountList",ordersJinxXinZhongCountList);
        result.put("year",year);
        return Result.success().put("data",result);
    }

    @GetMapping("/selectArtificerMoneyList")
    @ApiOperation("技师收益排行榜(在线时长+业绩++加钟率+充值率)")
    public Result selectArtificerMoneyList(Integer page,Integer limit,String startTime,String endTime,String title,String classifyId){
        return artificerService.selectArtificerMoneyList(page, limit, startTime, endTime, title,classifyId);
    }


    @GetMapping("/selectArtificerPhbList")
    @ApiOperation("排行榜(在线时长+业绩++加钟率+充值率)")
    public Result selectArtificerPhbList(Integer page,Integer limit,String startTime,String endTime,String type){
        return artificerService.selectArtificerPhbList(page, limit, startTime, endTime, type);
    }


    @GetMapping("/selectArtificerOrdersList")
    @ApiOperation("查询进行中的技师订单")
    public Result selectArtificerOrdersList(Integer page,Integer limit,String artificerName,
                                            String artificerPhone,String userName,String phone,
                                            Integer warning,Integer overTimeOrders){
        return ordersService.selectArtificerOrdersList(page, limit, artificerName, artificerPhone, userName, phone,warning,overTimeOrders);
    }

    @GetMapping("/selectWarningOrdersCount")
    @ApiOperation("查询警告订单总数")
    public Result selectWarningOrdersCount(){
        return Result.success().put("data",ordersService.count(new QueryWrapper<Orders>().in("status",6,7,8).eq("warning",1)));
    }

    @GetMapping("/selectOverTimeOrdersCount")
    @ApiOperation("查询超时订单总数")
    public Result selectOverTimeOrdersCount(){
        return Result.success().put("data",ordersService.count(new QueryWrapper<Orders>().in("status",6,7,8).eq("over_time_orders",1)));
    }

    @GetMapping("/selectShopMoney")
    @ApiOperation("查询商家抽成")
    public Result selectShopMoney(Integer page,Integer limit,String userName,String phone,String flag,String time){
        return ordersService.selectShopMoney(page, limit, userName,phone, flag, time);
    }

    @GetMapping("/selectOneUserMoney")
    @ApiOperation("查询用户代理抽成")
    public Result selectOneUserMoney(Integer page,Integer limit,String userName,String phone,String flag,String time){
        return ordersService.selectOneUserMoney(page, limit, userName,phone, flag, time);
    }

    @GetMapping("/selectOneArtificerMoney")
    @ApiOperation("查询技师代理抽成")
    public Result selectOneArtificerMoney(Integer page,Integer limit,String userName,String phone,String flag,String time){
        return ordersService.selectOneArtificerMoney(page, limit, userName,phone, flag, time);
    }

    @GetMapping("/selectArtificerMoney")
    @ApiOperation("查询技师抽成")
    public Result selectArtificerMoney(Integer page,Integer limit,String userName,String phone,String flag,String time){
        return ordersService.selectArtificerMoney(page, limit, userName,phone, flag, time);
    }

    @GetMapping("/selectNewUserOrdersCount")
    @ApiOperation("查询新用户下单数")
    public Result selectNewUserOrdersCount(Integer page,Integer limit,String userName,String phone){
        return ordersService.selectNewUserOrdersCount(page, limit, userName, phone);
    }

    @GetMapping("/selectNewUserOrdersRate")
    @ApiOperation("查询新用户下单数")
    public Result selectNewUserOrdersRate(){
        return ordersService.selectNewUserOrdersRate();
    }

    @GetMapping("/jszd")
    @ApiOperation("技师转单")
    public Result jszd(Long orderId,Long artificerId){
        return ordersService.jszd(orderId, artificerId);
    }

    @PostMapping("/updateJfgz")
    @ApiOperation("修改技师是否参与积分规则计算")
    public Result updateArtificer(Long userId,Integer ynJfgz){
        Artificer artificer = artificerService.selectArtificerByUserId(userId);
        artificer.setYnJfgz(ynJfgz);
        artificerService.updateById(artificer);
        return Result.success();
    }

}
