package com.gic.haoban.manage.web.controller.moment;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.manage.api.dto.moment.QwMomentPlanDTO;
import com.gic.haoban.manage.api.dto.moment.QwMomentPlanWxaDTO;
import com.gic.haoban.manage.api.dto.moment.TaskDetailDTO;
import com.gic.haoban.manage.api.dto.moment.TaskListWxaDTO;
import com.gic.haoban.manage.api.qdto.moment.PlanListWxaQDTO;
import com.gic.haoban.manage.api.qdto.moment.SendResultQDTO;
import com.gic.haoban.manage.api.qdto.moment.TaskListWxaQDTO;
import com.gic.haoban.manage.api.qdto.moment.TaskNumQDTO;
import com.gic.haoban.manage.api.service.moment.QwMomentApiService;
import com.gic.haoban.manage.web.qo.moment.PlanClerkListQO;
import com.gic.haoban.manage.web.qo.moment.PlanListQO;
import com.gic.haoban.manage.web.vo.moment.PlanClerkListVO;
import com.gic.haoban.manage.web.vo.moment.PlanListVO;
import com.gic.haoban.manage.web.vo.moment.TaskDetailVO;
import com.gic.haoban.manage.web.vo.moment.TaskMaterialVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;

/**
 * 企微朋友圈 - 好办小程序
 */
@RestController
@RequestMapping("/qw-moment")
public class QwMomentController {

    private static Logger logger = LogManager.getLogger(QwMomentController.class);

    @Autowired
    private QwMomentApiService qwMomentApiService ;
    @Autowired
    private ClerkService clerkService ;

    /**
     * 获取任务数
     */
    @RequestMapping("get-task-num")
    @ResponseBody
    public RestResponse<Integer> getTaskNum(String wxEnterpriseId , String enterpriseId , String storeId , String clerkId , String staffId) {
        TaskNumQDTO qdto = new TaskNumQDTO() ;
        qdto.setWxEnterpriseId(wxEnterpriseId);
        qdto.setEnterpriseId(enterpriseId);
        qdto.setStoreId(storeId);
        ClerkDTO clerk  = this.clerkService.getclerkById(clerkId) ;
        if(0 == clerk.getClerkType()) {
            qdto.setClerkId(clerkId);
        }
        ServiceResponse<Integer> resp = this.qwMomentApiService.getTaskNum(qdto) ;
        return RestResponse.successResult(resp.getResult()==null?0:resp.getResult()) ;
    }

    /**
     * 活动列表
     */
    @RequestMapping("plan-list")
    public RestResponse<Page<PlanListVO>> planList(@RequestBody PlanListQO qo) {
        logger.info("查询活动列表={}", JSONObject.toJSONString(qo));
        PlanListWxaQDTO qdto = EntityUtil.changeEntityByJSON(PlanListWxaQDTO.class,qo) ;
        ClerkDTO clerk  = this.clerkService.getclerkById(qo.getClerkId()) ;
        if(0 != clerk.getClerkType()) {
            qdto.setClerkId(null);
        }
        ServiceResponse<Page<QwMomentPlanWxaDTO>> pageResp = this.qwMomentApiService.planListWxa(qdto) ;
        Page<PlanListVO> retPage = PageHelperUtils.changePageToCurrentPage(pageResp.getResult(), PlanListVO.class);
        if(qo.getPlanStatus()==1) {
            for(PlanListVO vo : retPage.getResult()) {
                // 作为失效的数量返回
                vo.setNotExecNum(vo.getTotalNum()-vo.getExecNum());
            }
        }
        return RestResponse.successResult(retPage) ;
    }

    /**
     * 活动任务-导购列表
     */
    @RequestMapping("task-list")
    public RestResponse<Page<PlanClerkListVO>> taskList(@RequestBody PlanClerkListQO qo) {
        logger.info("活动下任务列表={}", JSONObject.toJSONString(qo));
        TaskListWxaQDTO qdto = EntityUtil.changeEntityByJSON(TaskListWxaQDTO.class,qo) ;
        ClerkDTO clerk  = this.clerkService.getclerkById(qo.getClerkId()) ;
        if(0 != clerk.getClerkType()) {
            qdto.setClerkId(null);
        }
        ServiceResponse<QwMomentPlanDTO> resp = this.qwMomentApiService.detail(qo.getPlanId()) ;
        QwMomentPlanDTO plan = resp.getResult();
        if(null == plan) {
            return RestResponse.failure("9999","活动不存在或已删除") ;
        }
        ServiceResponse<Page<TaskListWxaDTO>> pageResp = this.qwMomentApiService.taskListWxa(qdto) ;
        Page<PlanClerkListVO> retPage = PageHelperUtils.changePageToCurrentPage(pageResp.getResult(), PlanClerkListVO.class);
        if(CollectionUtils.isNotEmpty(retPage.getResult())) {
            for(PlanClerkListVO vo : retPage.getResult()) {
                if(vo.getTaskStatus()==1) {
                    if(plan.getStatusFlag()==2 || plan.getEndDate().getTime()<System.currentTimeMillis()) {
                        vo.setTaskStatus(0);
                    }
                }
            }
        }
        return RestResponse.successResult(retPage) ;
    }

    /**
     * 活动任务详情
     */
    @RequestMapping("detail")
    public RestResponse<TaskDetailVO> detail(Long planId , String execClerkId) {
        ServiceResponse<TaskDetailDTO> detailResp = this.qwMomentApiService.taskDetail(planId , execClerkId) ;
        if(detailResp.isSuccess()) {
            TaskDetailVO vo = EntityUtil.changeEntityByJSON(TaskDetailVO.class,detailResp.getResult()) ;
            ServiceResponse<QwMomentPlanDTO> resp = this.qwMomentApiService.detail(planId) ;
            QwMomentPlanDTO plan = resp.getResult();
            if(vo.getTaskStatus()==1) {
                if(plan.getStatusFlag()==2 || plan.getEndDate().getTime()<System.currentTimeMillis()) {
                    vo.setTaskStatus(0);
                }
            }
            return RestResponse.successResult(vo) ;
        }
        return RestResponse.failure("9999",detailResp.getMessage()) ;
    }

    /**
     * 素材列表
     */
    @RequestMapping("material-list")
    public RestResponse<List<TaskMaterialVO>> getTaskMaterial(Long planId) {
        ServiceResponse<QwMomentPlanDTO> detailResp = this.qwMomentApiService.detail(planId) ;
        List<TaskMaterialVO> list = new ArrayList<>() ;
        if(detailResp.isSuccess() && null != detailResp.getResult()) {
            String json = detailResp.getResult().getMediaInfo() ;
            JSONArray arr = JSONArray.parseArray(json) ;
            for(int i=0;i<arr.size();i++) {
                JSONObject obj  = arr.getJSONObject(i) ;
                TaskMaterialVO vo = new TaskMaterialVO();
                vo.setMaterialType(obj.getInteger("materialType"));
                vo.setImgUrl(obj.getString("imgUrl"));
                if(vo.getMaterialType()==4) {
                    vo.setLink(obj.getString("videoUrl"));
                }
                if(vo.getMaterialType()==3) {
                    vo.setLink(obj.getString("link"));
                }
                vo.setMaterialTitle(obj.getString("title"));
                vo.setMaterialContent(obj.getString("contentText"));
                if(null !=detailResp.getResult().getMediaLinkFlag() &&  detailResp.getResult().getMediaLinkFlag()==1) {
                    vo.setContentMaterialId(obj.getString("materialId"));
                }
                list.add(vo);
            }
        }
        return RestResponse.successResult(list) ;
    }

    /**
     * 完成企微群饭任务
     */
    @RequestMapping("finish-moment-task")
    @ResponseBody
    public RestResponse<Void> finishTask(@RequestBody SendResultQDTO qdto) {
        logger.info("完成任务={}",JSONObject.toJSONString(qdto)) ;
        this.qwMomentApiService.finishTask(qdto) ;
        return RestResponse.successResult();
    }

}
