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

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.JSONResponse;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.AuthorizedUser;
import com.gic.commons.util.DateUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.manage.web.qo.open.AddTaskDataQO;
import com.gic.haoban.manage.web.qo.open.AddTaskMemberPageQO;
import com.gic.haoban.manage.web.qo.open.AddTaskPageQO;
import com.gic.haoban.manage.web.utils.CreatorUtils;
import com.gic.haoban.manage.web.vo.MemberTagGroupVO;
import com.gic.haoban.manage.web.vo.open.AddTaskDetailVO;
import com.gic.haoban.manage.web.vo.open.OpenAddDataVO;
import com.gic.haoban.task.manage.api.dto.open.*;
import com.gic.haoban.task.manage.api.qdto.open.AddTaskMemberPageQDTO;
import com.gic.haoban.task.manage.api.qdto.open.QwAddTaskPageQDTO;
import com.gic.haoban.task.manage.api.service.OpenQwApiService;
import com.gic.member.tag.api.dto.MemberTagDTO;
import com.gic.member.tag.api.dto.MemberTagGroupDTO;
import com.gic.member.tag.api.dto.MemberTagItemDTO;
import com.gic.member.tag.api.service.MemberTagApiService;
import com.gic.member.tag.api.service.MemberTagGroupApiService;
import com.gic.qcloud.BucketNameEnum;
import com.gic.web.common.download.DownloadTask;
import com.gic.web.common.download.DownloadTaskUtil;
import com.gic.web.common.download.constants.TaskTypeEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 企微托管任务
 */
@RestController
@RequestMapping("/qw-open-task")
public class QywxOpenTaskController {

    @Autowired
    private OpenQwApiService openQwApiService;
    @Autowired
    private OpenAddMemberExcelHandler openAddMemberExcelHandler;
    @Autowired
    private MemberTagApiService memberTagApiService;
    @Autowired
    private MemberTagGroupApiService memberTagGroupApiService;

    /**
     * 加好友任务列表
     */
    @RequestMapping("page-add-task")
    public RestResponse<Page<OpenQwAddTaskDTO>> pageAddTask(@RequestBody AddTaskPageQO qo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        BasePageInfo basePageInfo = new BasePageInfo();
        basePageInfo.setPageNum(qo.getPageNum());
        basePageInfo.setPageSize(qo.getPageSize());
        QwAddTaskPageQDTO qdto = EntityUtil.changeEntityByJSON(QwAddTaskPageQDTO.class, qo);
        qdto.setWxEnterpriseId(wxEnterpriseId);
        qdto.setEnterpriseId(enterpriseId);
        // 创建人
        List<String> creatorIdList = CreatorUtils.getCreatorIdList(0);
        if (CollectionUtils.isNotEmpty(creatorIdList)) {
            qdto.setCreatorIdList(creatorIdList);
        }
        ServiceResponse<Page<OpenQwAddTaskDTO>> resp = this.openQwApiService.addTaskPage(qdto, basePageInfo);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }

    /**
     * 保存更新加好友任务
     *
     * @param dto
     * @return
     */
    @RequestMapping("save-add-task")
    public RestResponse<OpenQwAddTaskDTO> saveAddTask(@RequestBody OpenQwAddTaskDTO dto) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        dto.setWxEnterpriseId(wxEnterpriseId);
        dto.setEnterpriseId(enterpriseId);
        dto.setCreatorId(loginUser.getClerkId());
        dto.setCreatorName(loginUser.getClerkName());
        ServiceResponse<OpenQwAddTaskDTO> resp = this.openQwApiService.saveAddTask(dto);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }

    /**
     * 获取加好友任务详情
     *
     * @param addTaskId
     * @return
     */
    @RequestMapping("get-add-task")
    public RestResponse<AddTaskDetailVO> getAddTask(Long addTaskId) {
        ServiceResponse<OpenQwAddTaskDTO> resp = this.openQwApiService.getAddTask(addTaskId);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        AddTaskDetailVO vo = EntityUtil.changeEntityByJSON(AddTaskDetailVO.class, resp.getResult());
        if (StringUtils.isNotBlank(vo.getMemberLabelId())) {
            MemberTagItemDTO tagItem = this.memberTagApiService.findMemberTagItem(vo.getMemberLabelId());
            if (null != tagItem) {
                String tagId = tagItem.getTagId();
                MemberTagDTO tag = this.memberTagApiService.getMemberTagById(tagId);
                vo.setMemberLabelName(tag.getTagName() + "-" + tagItem.getTagItemName());
                vo.setMemberLabelStatus(tagItem.getStatus());
            }
        }
        // 会员分组
        if (vo.getMemberType() == 1) {
            List<MemberTagGroupVO> memberTagGroupVOS = this.listMemberTagGroupInfoByGoupIds(vo
                    .getSearchParams());
            vo.setTagGroupList(memberTagGroupVOS);
        }
        return RestResponse.successResult(vo);
    }

    public List<MemberTagGroupVO> listMemberTagGroupInfoByGoupIds(String tagGroupIds) {
        List<MemberTagGroupVO> result = new ArrayList<>();
        if (StringUtils.isBlank(tagGroupIds)) {
            return result;
        }
        String[] tagGroupIdArr = tagGroupIds.split(",");
        if (ArrayUtils.isEmpty(tagGroupIdArr)) {
            return result;
        }
        List<MemberTagGroupDTO> memberTagGroupDTOList = memberTagGroupApiService.findListByIds(
                new ArrayList<>(Arrays.asList(tagGroupIdArr)));
        if (CollectionUtils.isNotEmpty(memberTagGroupDTOList)) {

            for (MemberTagGroupDTO memberTagGroupDTO : memberTagGroupDTOList) {
                MemberTagGroupVO memberTagGroupVO = new MemberTagGroupVO();
                memberTagGroupVO.setGroupName(memberTagGroupDTO.getGroupName());
                memberTagGroupVO.setMemberTagGroupId(memberTagGroupDTO.getMemberTagGroupId());
                memberTagGroupVO.setEffectiveStatus(memberTagGroupDTO.getEffectiveStatus());
                memberTagGroupVO.setIsRealTime(memberTagGroupDTO.getIsRealTime());
                memberTagGroupVO.setFixedType(memberTagGroupDTO.getFixedType());
                result.add(memberTagGroupVO);
            }
        }
        return result;
    }

    /**
     * 终止加好友任务
     *
     * @param addTaskId
     * @return
     */
    @RequestMapping("stop-add-task")
    public RestResponse<Void> stopAddTask(Long addTaskId) {
        ServiceResponse<Void> resp = this.openQwApiService.updateAddTaskStatus(addTaskId, 1);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult();
    }


    /**
     * 加好友任务-添加明细列表
     */
    @RequestMapping("page-add-task-member")
    public RestResponse<Page<OpenQwAddTaskMemberDTO>> pageAddTaskMember(@RequestBody AddTaskMemberPageQO qo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        BasePageInfo basePageInfo = new BasePageInfo();
        basePageInfo.setPageNum(qo.getPageNum());
        basePageInfo.setPageSize(qo.getPageSize());
        AddTaskMemberPageQDTO qdto = EntityUtil.changeEntityByJSON(AddTaskMemberPageQDTO.class, qo);
        qdto.setWxEnterpriseId(wxEnterpriseId);
        qdto.setEnterpriseId(enterpriseId);
        ServiceResponse<Page<OpenQwAddTaskMemberDTO>> resp = this.openQwApiService.addFriendPage(qdto, basePageInfo);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }

    /**
     * 加好友任务-添加明细列表-导出
     */
    @RequestMapping("add-task-member-excel")
    public RestResponse<String> addTaskMemberExcel(@RequestBody AddTaskMemberPageQO qo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        AddTaskMemberPageQDTO qdto = EntityUtil.changeEntityByJSON(AddTaskMemberPageQDTO.class, qo);
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        BasePageInfo basePageInfo = new BasePageInfo();
        basePageInfo.setPageNum(1);
        basePageInfo.setPageSize(1);
        ServiceResponse<Page<OpenQwAddTaskMemberDTO>> pageResp = this.openQwApiService.addFriendPage(qdto, basePageInfo);
        final int totalCount = pageResp.getResult().getTotalCount();
        if (totalCount == 0) {
            return RestResponse.failure("9999", "导出数据条数为0");
        }
        AuthorizedUser user = new AuthorizedUser();
        user.setUserId(loginUser.getClerkId());
        user.setEnterpriseId(loginUser.getEnterpriseId());
        user.setRealName(loginUser.getClerkName());
        String fileName = "好办自动加好友";
        Date startDate = qo.getStartDate();
        Date endDate = qo.getEndDate();
        if (null != startDate && null != endDate) {
            fileName = fileName + "-" + DateUtil.formatString(startDate, "yyyy-MM-dd") + "到" + DateUtil.formatString(endDate, "yyyy-MM-dd");
        }
        // 1.组装数据查询条件
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.HAOBAN_OPEN_ADD);
        task.setUser(user);
        task.setDataType(qo.getDataType());
        task.setTotalCount(totalCount);
        task.setFileName(fileName);
        task.setChannelName(TaskTypeEnum.HAOBAN_OPEN_ADD.getName());
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        task.setSearchDataParams(JSON.toJSONStringWithDateFormat(qdto, DatePattern.NORM_DATETIME_PATTERN));
        task.setHandler(openAddMemberExcelHandler);
        JSONResponse jsonResponse = DownloadTaskUtil.createDownloadTask(task);
        final String reportId;
        if (jsonResponse.isSuccess()) {
            reportId = (String) jsonResponse.getResult();
        } else {
            return RestResponse.failure("9999", jsonResponse.getErrorMessage());
        }
        return RestResponse.successResult(reportId);
    }

    /**
     * 加好友数据图表
     */
    @RequestMapping("list-add-data")
    public RestResponse<OpenAddDataVO> pageAdTask(@RequestBody AddTaskDataQO qo) {
        ServiceResponse<List<OpenQwAddTaskDataDTO>> resp = this.openQwApiService.taskData(qo.getAddTaskId(), qo.getStartDate(), qo.getEndDate());
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        OpenAddDataVO vo = new OpenAddDataVO();
        int applyNum = 0;
        int addNum = 0;
        for (OpenQwAddTaskDataDTO dto : resp.getResult()) {
            applyNum += dto.getApplyNum();
            addNum += dto.getAddNum();
        }
        vo.setApplyNum(applyNum);
        vo.setAddNum(addNum);
        vo.setList(resp.getResult());
        return RestResponse.successResult(vo);
    }

    /**
     * 添加好友规则设置
     *
     * @return
     */
    @RequestMapping("get-add-task-setting")
    public RestResponse<OpenQwAddTaskSettingDTO> getTaskSetting() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        ServiceResponse<OpenQwAddTaskSettingDTO> resp = this.openQwApiService.geAddSetting(wxEnterpriseId, enterpriseId);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }

    /**
     * 保存添加好友规则配置
     *
     * @param dto
     * @return
     */
    @RequestMapping("save-add-task-setting")
    public RestResponse<OpenQwAddTaskSettingDTO> saveTaskSetting(@RequestBody OpenQwAddTaskSettingDTO dto) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        dto.setWxEnterpriseId(wxEnterpriseId);
        dto.setEnterpriseId(enterpriseId);
        ServiceResponse<OpenQwAddTaskSettingDTO> resp = this.openQwApiService.saveAddSetting(dto);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }


    /**
     * 删除好友配置
     *
     * @return
     */
    @RequestMapping("get-del-task-setting")
    public RestResponse<OpenQwDelTaskDTO> getDelTaskSetting() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        ServiceResponse<OpenQwDelTaskDTO> resp = this.openQwApiService.getDelTask(wxEnterpriseId, enterpriseId);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }

    /**
     * 保存删除好友配置
     *
     * @param dto
     * @return
     */
    @RequestMapping("save-del-task-setting")
    public RestResponse<OpenQwDelTaskDTO> saveDelTaskSetting(@RequestBody OpenQwDelTaskDTO dto) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        dto.setWxEnterpriseId(wxEnterpriseId);
        dto.setEnterpriseId(enterpriseId);
        ServiceResponse<OpenQwDelTaskDTO> resp = this.openQwApiService.saveDelTask(dto);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }


    /**
     * 任务自动执行配置
     *
     * @return
     */
    @RequestMapping("get-auto-send-task-setting")
    public RestResponse<OpenQwAutoSendDTO> getAutoSendTaskSetting() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        ServiceResponse<OpenQwAutoSendDTO> resp = this.openQwApiService.getAutoSend(wxEnterpriseId, enterpriseId);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }

    /**
     * 保存任务自动执行配置
     *
     * @param dto
     * @return
     */
    @RequestMapping("save-auto-send-task-setting")
    public RestResponse<OpenQwAutoSendDTO> saveAutoSendTaskSetting(@RequestBody OpenQwAutoSendDTO dto) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        dto.setWxEnterpriseId(wxEnterpriseId);
        dto.setEnterpriseId(enterpriseId);
        ServiceResponse<OpenQwAutoSendDTO> resp = this.openQwApiService.saveAutoSend(dto);
        if (!resp.isSuccess()) {
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }


}
