package com.ruoyi.web.controller.visit;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.zqt.ZQTreeNode;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.visit.VisitFreePlan;
import com.ruoyi.system.domain.visit.VisitFreePlanModel;
import com.ruoyi.system.domain.visit.VisitFreePlanModelExample;
import com.ruoyi.system.domain.visit.enums.VisitTypeEnum;
import com.ruoyi.system.domain.visit.ext.VisitFreeInterviewExt;
import com.ruoyi.system.domain.visit.ext.VisitFreePlanModelExt;
import com.ruoyi.system.service.grid.GridCompanyService;
import com.ruoyi.system.service.grid.GridRegionUserService;
import com.ruoyi.system.service.grid.GridShopService;
import com.ruoyi.system.service.visit.VisitFreeInterviewService;
import com.ruoyi.system.service.visit.VisitFreePlanModelService;
import com.ruoyi.system.service.visit.VisitFreePlanService;
import com.ruoyi.system.service.visit.impl.VisitAsyncServiceImpl;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 自由走访相关接口
 */
@Api(tags = "走访管理 - 自由走访")
@RestController
@RequestMapping("/api/visit/freePlan")
public class VisitFreePlanController {

    @Autowired
    VisitFreePlanModelService visitFreePlanModelService;

    @Autowired
    VisitFreeInterviewService visitFreeInterviewService;

    @Autowired
    VisitFreePlanService visitFreePlanService;

    @Autowired
    VisitAsyncServiceImpl asyncService;

    @Autowired
    private GridShopService gridShopService;

    @Autowired
    private GridCompanyService gridCompanyService;

    @Autowired
    private GridRegionUserService gridRegionUserService;

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public AjaxResult list(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                           @RequestParam(value = "planAllNum", required = false) Long planAllNum,
                           @RequestParam(value = "startTime", required = false) String startTime,
                           @RequestParam(value = "endTime", required = false) String endTime,
                           @RequestParam(value = "planType", required = false) String planType,
                           @RequestParam(value = "planTitle", required = false) String planTitle,
                           @RequestParam(value = "planStatus", required = false) String planStatus,
                           @RequestParam(value = "wgCode", required = false) String wgCode) {
        try {
            PageInfo<VisitFreePlanModelExt> pageInfo = visitFreePlanModelService.freePlanModelPage(VisitTypeEnum.FREE_VISIT.getCode(), pageNum, pageSize,
                    planAllNum, startTime, endTime, planType, planTitle, planStatus, wgCode);
            return AjaxResult.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(500, "服务器内部错误");
        }
    }

    /**
     * APP端自由走访列表，1级网格员，看全部走访，2级看他下属网格的走访，3级看自己
     * @param pageNum
     * @param pageSize
     * @param wgCode    指定所选网格（可选1，2，3级）
     * @param hasDone
     * @param planTitle
     * @return
     */
    @RequestMapping(value = "/freePlanPage", method = RequestMethod.GET)
    public AjaxResult freePlanPage(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                   @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                   @RequestParam(value = "wgCode", required = false) String wgCode,
                                   @RequestParam(value = "hasDone", required = false) String hasDone,
                                   @RequestParam(value = "planTitle", required = false) String planTitle) {
        SysUser sysUser = getLoginUser().getUser();
        PageInfo<VisitFreePlan> pageInfo = visitFreePlanModelService.freePlanPage(sysUser,VisitTypeEnum.FREE_VISIT.getCode(), pageNum, pageSize,
                wgCode, hasDone, planTitle);
        return AjaxResult.success(pageInfo);
    }

    @RequestMapping(value = "/interviewPage", method = RequestMethod.GET)
    public AjaxResult interviewPage(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                    @RequestParam(value = "wgCodes", required = false) List<String> wgCodes,
                                    @RequestParam(value = "wgCode", required = false) String wgCode,
                                    @RequestParam(value = "startTime", required = false) String startTime,
                                    @RequestParam(value = "endTime", required = false) String endTime,
                                    @RequestParam(value = "type", required = false) String type,
                                    @RequestParam(value = "planModelId", required = false) String planModelId) {
        try {
            PageInfo<VisitFreeInterviewExt> pageInfo = visitFreeInterviewService.freeInterviewPage(VisitTypeEnum.FREE_VISIT.getCode(), pageNum, pageSize,
                    wgCodes, startTime, endTime, type, planModelId, wgCode);
            return AjaxResult.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(500, "服务器内部错误");
        }
    }

    @PostMapping(value = "/addPlanModel")
    public AjaxResult add(@RequestBody VisitFreePlanModelExt visitFreePlanModelExt) {
        visitFreePlanModelExt.setVisitType(VisitTypeEnum.FREE_VISIT.getCode());
        return visitFreePlanModelService.addVisitFreePlanModel(visitFreePlanModelExt);
    }


    @PutMapping(value = "/update")
    public AjaxResult update(@RequestBody VisitFreePlanModelExt visitFreePlanModelExt) {
        visitFreePlanModelExt.setVisitType(VisitTypeEnum.FREE_VISIT.getCode());
        return visitFreePlanModelService.updateVisitFreePlanModel(visitFreePlanModelExt);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public AjaxResult delete(@RequestBody VisitFreePlanModel planModel) {
        visitFreePlanModelService.delete(planModel.getId());
        return AjaxResult.success("success");
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public AjaxResult info(@RequestParam(value = "id") String id) {
        VisitFreePlanModelExt visitPlanExt = visitFreePlanModelService.info(id);
        return AjaxResult.success(visitPlanExt);
    }

    @RequestMapping(value = "/Tree", method = RequestMethod.GET)
    public AjaxResult Tree(@RequestParam(value = "id") String id) {
        ZQTreeNode treeNode = visitFreePlanModelService.freePlanTree(id);
        return AjaxResult.success(treeNode);
    }


    @PostMapping(value = "/addInterview")
    public AjaxResult addInterview(@RequestBody VisitFreeInterviewExt visitFreeInterviewExt) {
        visitFreeInterviewExt.setVisitType(VisitTypeEnum.FREE_VISIT.getCode());
        return visitFreeInterviewService.addVisitFreeInterview(visitFreeInterviewExt);
    }

    @GetMapping(value = "/interviewCountStatistic")
    public AjaxResult interviewCountStatistic() {
        Map<String, Long> result = visitFreeInterviewService.interviewCountStatistic(VisitTypeEnum.FREE_VISIT.getCode());
        return AjaxResult.success(result);
    }

    @RequestMapping(value = "/freePlanInterviewStatistic", method = RequestMethod.GET)
    public AjaxResult freePlanInterviewStatistic(@RequestParam(value = "planModelId") String planModelId,
                                                 @RequestParam(value = "wgCodes", required = false) List<String> wgCodes,
                                                 @RequestParam(value = "wgCode", required = false) String wgCode) {
        Map<String, Long> result = visitFreeInterviewService.freePlanInterviewStatistic(planModelId, wgCodes, wgCode);
        return AjaxResult.success(result);
    }

    @RequestMapping(value = "/interviewStatistic", method = RequestMethod.GET)
    public AjaxResult freePlanInterviewStatistic(@RequestParam(value = "wgCode", required = false) String wgCode,
                                                 @RequestParam(value = "startDate", required = false)String startDate,
                                                 @RequestParam(value = "endDate", required = false)String endDate,
                                                 @RequestParam(value = "visitType") String visitType) {
        Map<String, Long> result = visitFreeInterviewService.interviewStatistic(wgCode, visitType, startDate, endDate);
        return AjaxResult.success(result);
    }

    @RequestMapping(value = "/modelDoneStatistic", method = RequestMethod.GET)
    public AjaxResult modelDoneStatistic(@RequestParam(value = "planModelId") String planModelId) {
        Map<String, List<VisitFreePlan>> result = visitFreePlanService.modelHasDone(planModelId);
        return AjaxResult.success(result);
    }

    @GetMapping(value = "/dealFreePlanModel")
//    @SysJobLog(title = "手动自由走访计划任务分派")
    public void dealFreePlanModel(@RequestParam(value = "planModelId", required = false) String planModelId) {
        VisitFreePlanModelExample freePlanModelExample = new VisitFreePlanModelExample();

        VisitFreePlanModelExample.Criteria criteria = freePlanModelExample.createCriteria();
        criteria.andIsValidEqualTo("1")
                .andPlanStatusEqualTo("3")
                .andStartTimeLessThanOrEqualTo(DateUtils.getTime());

        if (StringUtils.isNotBlank(planModelId)) {
            criteria.andIdEqualTo(planModelId);
        }

        List<VisitFreePlanModel> freePlanModelList = visitFreePlanModelService.selectByExample(freePlanModelExample);

        if (CollectionUtils.isEmpty(freePlanModelList)) {
            return;
        }

        List<GridCompany> wsCompanies = new ArrayList<>();
        List<GridShop> wsShops = new ArrayList<>();

        GridCompanyExample companyExample = new GridCompanyExample();
        companyExample.createCriteria().andIsValidEqualTo(Byte.valueOf("1"))
                .andWgCodeIsNotNull();
        wsCompanies = gridCompanyService.selectByExample(companyExample);

        GridShopExample shopExample = new GridShopExample();
        shopExample.createCriteria().andValidEqualTo(Byte.valueOf("1"))
                .andWgCodeIsNotNull();
        wsShops = gridShopService.selectByExample(shopExample);

        List<String> modelIdList = new ArrayList<>();
        for (VisitFreePlanModel freePlanModel : freePlanModelList) {
            modelIdList.add(freePlanModel.getId());
            VisitFreePlanModelExt modelExt = new VisitFreePlanModelExt();
            BeanUtils.copyProperties(freePlanModel, modelExt);
            modelExt.setWsCompanies(wsCompanies);
            modelExt.setGridShops(wsShops);
            modelExt.setTaskFlag("1");

            asyncService.dealFreePlan(modelExt);
        }
    }

    @RequestMapping(value = "/freeInterviewStatistic", method = RequestMethod.GET)
    public AjaxResult freeInterviewStatistic() {
        Map<String, Object> result = visitFreeInterviewService.freeInterviewStatistic(VisitTypeEnum.FREE_VISIT.getCode());
        return AjaxResult.success(result);
    }
}
