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

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.anno.IgnoreLogin;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.manage.api.service.OpenStaffApiService;
import com.gic.haoban.manage.web.controller.MemberController;
import com.gic.haoban.manage.web.log.LogRecordUserServiceImpl;
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.log.record.anno.GicLogRecord;
import com.gic.log.record.util.GicLogRecordCategoryEnum;
import com.gic.log.record.util.GicLogRecordEvaluationContext;
import com.gic.log.record.util.GicLogRecordOptTypeEnum;
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.redis.data.util.RedisUtil;
import com.gic.thirdparty.cloudfile.CloudFileUtil;
import com.gic.thirdparty.cloudfile.enums.CloudFileBusinessOptEnum;
import com.gic.thirdparty.cloudfile.enums.CloudFileTypeEnum;
import com.gic.thirdparty.cloudfile.pojo.CloudFileInfo;
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.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

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

    private static final Logger log = LogManager.getLogger(QywxOpenTaskController.class);

    @Autowired
    private OpenQwApiService openQwApiService;
    @Autowired
    private OpenAddMemberExcelHandler openAddMemberExcelHandler;
    @Autowired
    private MemberTagApiService memberTagApiService;
    @Autowired
    private MemberTagGroupApiService memberTagGroupApiService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private OpenStaffApiService openStaffApiService;
    @Autowired
    private MemberController memberController;
    @Autowired
    private EnterpriseService enterpriseService;

    /**
     * 加好友任务列表
     */
    @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);
        if (null != qdto.getEndDate()) {
            qdto.setEndDate(DateUtil.getEndTimeOfDay(qdto.getEndDate()));
        }
        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")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.QW_ADD, optType = GicLogRecordOptTypeEnum.QW_ADD_02, userFunc = LogRecordUserServiceImpl.class, optPage = "企微运营-自动加好友")
    public RestResponse<OpenQwAddTaskDTO> saveAddTask(@RequestBody OpenQwAddTaskDTO dto) {
        OpenQwAddTaskSettingDTO setting = this.getAddSetting();
        if (null == setting) {
            return RestResponse.failure("9999", "请先设置添加好友规则");
        }
        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());
        Long addTaskId = dto.getAddTaskId();
        OpenQwAddTaskDTO oldDTO = null;
        if (null != addTaskId) {
            ServiceResponse<OpenQwAddTaskDTO> oldResp = this.openQwApiService.getAddTask(addTaskId);
            oldDTO = oldResp.getResult();
        }
        if (null != oldDTO) {
            String oldName = oldDTO.getName() + "-" + addTaskId;
            String title = "编辑任务【" + oldName + "】";
            int oldMemberType = oldDTO.getMemberType();
            int newMemberType = dto.getMemberType();
            String oldMemberTypeTitle = oldMemberType == 0 ? "客户筛选" : "客户分组";
            String newMemberTypeTitle = newMemberType == 0 ? "客户筛选" : "客户分组";
            String logContent1 = this.otherLog(oldMemberType, newMemberType, "参与人群", oldMemberTypeTitle, newMemberTypeTitle);
            int oldMemberRule = oldDTO.getMemberRule();
            int newMemberRule = dto.getMemberRule();
            String oldMemberRuleTitle = oldMemberRule == 1 ? "和专属导购没有好友关系的客户" : "和企业下所有导购均没有好友关系的客户";
            String newMemberRuleTitle = newMemberRule == 1 ? "和专属导购没有好友关系的客户" : "和企业下所有导购均没有好友关系的客户";
            String logContent2 = this.otherLog(oldMemberRule, newMemberRule, "人群规则", oldMemberRuleTitle, newMemberRuleTitle);
            String oldLabel = oldDTO.getMemberLabelId();
            String newLabel = dto.getMemberLabelId();
            String oldApplyLabel = oldDTO.getApplyMemberLabelId() ;
            String newApplyLabel = dto.getApplyMemberLabelId() ;
            String logContent3 = this.memberLabel("好友申请通过后添加",oldLabel, newLabel);
            String logContent4 = this.memberLabel("发起好友申请时添加",oldApplyLabel, newApplyLabel);
            String logContent = this.addListForLog(logContent1, logContent2, logContent3,logContent4);
            if (StringUtils.isNotBlank(logContent)) {
                logContent = title + logContent;
                GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
                GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
            } else {
                GicLogRecordEvaluationContext.noWriteLog();
            }
        }else {
            GicLogRecordEvaluationContext.noWriteLog();
        }
        ServiceResponse<OpenQwAddTaskDTO> resp = this.openQwApiService.saveAddTask(dto);
        if (!resp.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }

    private String otherLog(int oldValue, int newValue, String s1, String s2, String s3) {
        if (oldValue != newValue) {
            return s1 + "从【" + s2 + "】修改为【" + s3 + "】";
        }
        return "";
    }

    private String memberLabel(String title,String oldValue, String newValue) {
        if(null == oldValue) {
            oldValue = "";
        }
        if(null == newValue) {
            newValue = "" ;
        }
        if (!oldValue.equals(newValue)) {
            MemberTagItemDTO oldResp = null ;
            if(StringUtils.isNotBlank(oldValue)) {
                oldResp = this.memberTagApiService.findMemberTagItem(oldValue);
            }
            MemberTagItemDTO newResp = null ;
            if(StringUtils.isNotBlank(newValue)) {
                newResp = this.memberTagApiService.findMemberTagItem(newValue);
            }
            if (null != oldResp) {
                oldValue = oldResp.getTagItemName();
            }
            if (null != newResp) {
                newValue = newResp.getTagItemName();
            }
            return title+"标签从【" + oldValue + "】修改为【" + newValue + "】";
        }
        return "";
    }


    /**
     * 获取加好友任务详情
     *
     * @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(StringUtils.isNotBlank(vo.getApplyMemberLabelId())) {
            MemberTagItemDTO tagItem = this.memberTagApiService.findMemberTagItem(vo.getApplyMemberLabelId());
            if (null != tagItem) {
                String tagId = tagItem.getTagId();
                MemberTagDTO tag = this.memberTagApiService.getMemberTagById(tagId);
                vo.setApplyMemberLabelName(tag.getTagName() + "-" + tagItem.getTagItemName());
                vo.setApplyMemberLabelStatus(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")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.QW_ADD, optType = GicLogRecordOptTypeEnum.QW_ADD_02, userFunc = LogRecordUserServiceImpl.class, optPage = "企微运营-自动加好友")
    public RestResponse<Void> stopAddTask(Long addTaskId) {
        ServiceResponse<Void> resp = this.openQwApiService.updateAddTaskStatus(addTaskId, 1);
        if (!resp.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", resp.getMessage());
        }
        ServiceResponse<OpenQwAddTaskDTO> taskResp = this.openQwApiService.getAddTask(addTaskId);
        String logContent = "终止【" + taskResp.getResult().getName() + "-" + addTaskId + "】";
        GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
        GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
        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);
        if (null != qdto.getEndDate()) {
            qdto.setEndDate(DateUtil.getEndTimeOfDay(qdto.getEndDate()));
        }
        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());
        if (null != qdto.getEndDate()) {
            qdto.setEndDate(DateUtil.getEndTimeOfDay(qdto.getEndDate()));
        }
        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() {
        OpenQwAddTaskSettingDTO dto = this.getAddSetting();
        return RestResponse.successResult(dto);
    }

    private OpenQwAddTaskSettingDTO getAddSetting() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        ServiceResponse<OpenQwAddTaskSettingDTO> resp = this.openQwApiService.geAddSetting(wxEnterpriseId, enterpriseId);
        if (!resp.isSuccess()) {
            return null;
        }
        return resp.getResult();
    }

    /**
     * 保存添加好友规则配置
     *
     * @param dto
     * @return
     */
    @RequestMapping("save-add-task-setting")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.QW_ADD, optType = GicLogRecordOptTypeEnum.QW_ADD_01, userFunc = LogRecordUserServiceImpl.class, optPage = "企微运营-自动加好友")
    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> oldResp = this.openQwApiService.geAddSetting(wxEnterpriseId, enterpriseId);
        if (null != oldResp.getResult()) {
            OpenQwAddTaskSettingDTO oldDTO = oldResp.getResult();
            String logContent1 = "";
            String logContent2 = "";
            String oldAddTime = oldDTO.getAddTime();
            String newAddTime = dto.getAddTime();
            if (!oldAddTime.equals(newAddTime)) {
                logContent1 = "添加时段从【" + oldAddTime + "】修改为【" + newAddTime + "】 ";
            }
            String oldInt = oldDTO.getAddIntervalStart() + "-" + oldDTO.getAddIntervalEnd();
            String newInt = dto.getAddIntervalStart() + "-" + dto.getAddIntervalEnd();
            if (!oldInt.equals(newInt)) {
                logContent2 = "添加间隔从【" + oldInt + "】修改为【" + newInt + "】 ";
            }
            String n1 = this.numLog(oldDTO.getReAddTime(), dto.getReAddTime(), "客户未通过好友重新添加时间从【%s】修改未【%s】");
            String n2 = this.numLog(oldDTO.getReAddTimes(), dto.getReAddTimes(), "最多重新添加次数从【%s】修改为【%s】");
            String n3 = this.openLog(oldDTO.getReAddFlag(), dto.getReAddFlag(), "自动重新添加");
            String logContent3 = "";
            if (!StringUtils.isAllBlank(n1, n2, n3)) {
                logContent3 = this.addListForLog(n1, n2, n3);
            }
            String logContent4 = this.storeLog(oldDTO.getMainStoreJson(), dto.getMainStoreJson(), "服务门店");
            String logContent5 = this.storeLog(oldDTO.getOtherStoreJson(), dto.getOtherStoreJson(), "协管门店");
            String logContent6 = this.storeLog(oldDTO.getAssignStoreJson(), dto.getAssignStoreJson(), "指定门店");
            String logContent = this.addListForLog(logContent1, logContent2, logContent3, logContent4, logContent5, logContent6);
            if (StringUtils.isNotBlank(logContent)) {
                GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
                GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
            } else {
                GicLogRecordEvaluationContext.noWriteLog();
            }
        }else {
            GicLogRecordEvaluationContext.noWriteLog();
        }
        ServiceResponse<OpenQwAddTaskSettingDTO> resp = this.openQwApiService.saveAddSetting(dto);
        if (!resp.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", resp.getMessage());
        }
        return RestResponse.successResult(resp.getResult());
    }

    private String storeLog(String oldStr, String newStr, String name) {
        JSONObject oldJson = JSONObject.parseObject(oldStr);
        int oldFlag = oldJson.getIntValue("open");
        JSONObject newJson = JSONObject.parseObject(newStr);
        int newFlag = newJson.getInteger("open");
        String s1 = this.openLog(oldFlag, newFlag, name);

        String s2Old = this.getLogOption(oldJson.getIntValue("zs"), oldJson.getIntValue("dz"), oldJson.getIntValue("dy"), oldJson.getIntValue("xg"));
        String s2New = this.getLogOption(newJson.getIntValue("zs"), newJson.getIntValue("dz"), newJson.getIntValue("dy"), newJson.getIntValue("xg"));

        String s2 = "";
        if (!s2Old.equals(s2New)) {
            s2 = String.format("%s从【%s】修改为【%s】", name, s2Old, s2New);
        }
        String s3 = "";
        if ("指定门店".equals(name)) {
            s3 = this.getStore(oldJson.getString("store"), newJson.getString("store"));
        }
        return this.addListForLog(s1, s3, s2);
    }

    private String getStore(String oldStoreId, String newStoreId) {
        if (null == oldStoreId) {
            oldStoreId = "";
        }
        if (null == newStoreId) {
            newStoreId = "";
        }
        if (!oldStoreId.equals(newStoreId)) {
            String oldName = "--";
            if (StringUtils.isNotBlank(oldStoreId)) {
                StoreDTO oldStore = this.storeService.getStore(oldStoreId);
                if (null != oldStore) {
                    oldName = oldStore.getStoreName() + "、" + oldStore.getStoreCode();
                }
            }
            String newName = "--";
            if (StringUtils.isNotBlank(newStoreId)) {
                StoreDTO newStore = this.storeService.getStore(newStoreId);
                if (null != newStore) {
                    newName = newStore.getStoreName() + "、" + newStore.getStoreCode();
                }
            }
            String s = String.format("指定门店从【%s】修改为【%s】", oldName, newName);
            return s;
        }
        return "";
    }

    private String getLogOption(int zs, int dz, int dy, int xg) {
        List<String> list = new ArrayList<>();
        if (zs == 1) {
            list.add("专属导购");
        }
        if (xg == 1) {
            list.add("协管导购");
        }
        if (dz == 1) {
            list.add("店长");
        }
        if (dy == 1) {
            list.add("其他导购随机");
        }
        return list.stream().collect(Collectors.joining("、"));
    }

    private String openLog(int oldFlag, int openFlag, String title) {
        if (oldFlag == openFlag) {
            return "";
        }
        if (oldFlag == openFlag) {
            return "";
        }
        if (openFlag == 1) {
            return "开启" + title;
        }
        return "关闭" + title;
    }

    private String numLog(int old, int newValue, String title) {
        if (old != newValue) {
            return String.format(title, old + "", newValue + "");
        }
        return "";
    }

    /**
     * 删除好友配置
     *
     * @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")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.QW_DEL, optType = GicLogRecordOptTypeEnum.QW_DEL_01, userFunc = LogRecordUserServiceImpl.class, optPage = "企微运营-自动删好友")
    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> oldResp = this.openQwApiService.getDelTask(wxEnterpriseId, enterpriseId);
        OpenQwDelTaskDTO oldDTO = null;
        if (null != oldResp.getResult()) {
            oldDTO = oldResp.getResult();
        }
        ServiceResponse<OpenQwDelTaskDTO> resp = this.openQwApiService.saveDelTask(dto);
        if (!resp.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", resp.getMessage());
        }
        if (null != oldDTO) {
            String logContent1 = "";
            String logContent2 = "";
            String logContent3 = "";
            String oldAddTime = oldDTO.getAddTime();
            String newAddTime = dto.getAddTime();
            if (!oldAddTime.equals(newAddTime)) {
                logContent1 = "删除时段从【" + oldAddTime + "】修改为【" + newAddTime + "】";
            }
            String oldInt = oldDTO.getAddIntervalStart() + "-" + oldDTO.getAddIntervalEnd();
            String newInt = dto.getAddIntervalStart() + "-" + dto.getAddIntervalEnd();
            if (!oldInt.equals(newInt)) {
                logContent2 = "删除间隔从【" + oldInt + "】修改为【" + newInt + "】";
            }
            int oldOpenFlag = oldDTO.getOpenFlag();
            int newOpenFlag = dto.getOpenFlag();
            if (oldOpenFlag != newOpenFlag) {
                if (newOpenFlag == 1) {
                    logContent3 = "状态从【停用自动删除】修改为【启用自动删除】";
                } else {
                    logContent3 = "状态从【启用自动删除】修改为【停用自动删除】";
                }
            }
            String logContent = this.addListForLog(logContent1, logContent2, logContent3);
            if (StringUtils.isNotBlank(logContent)) {
                GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
                GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
            } else {
                GicLogRecordEvaluationContext.noWriteLog();
            }
        }else {
            GicLogRecordEvaluationContext.noWriteLog();
        }
        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")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.QW_AUTO_SEND, optType = GicLogRecordOptTypeEnum.QW_AUTO_SEND_01, userFunc = LogRecordUserServiceImpl.class, optPage = "企微运营-任务自动执行")
    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> oldResp = this.openQwApiService.getAutoSend(wxEnterpriseId, enterpriseId);
        OpenQwAutoSendDTO oldDTO = null;
        if (null != oldResp.getResult()) {
            oldDTO = oldResp.getResult();
        }
        ServiceResponse<OpenQwAutoSendDTO> resp = this.openQwApiService.saveAutoSend(dto);
        if (!resp.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", resp.getMessage());
        }
        if (null != oldDTO) {
            int oldOpenFlag = oldDTO.getOpenFlag();
            int newOpenFlag = dto.getOpenFlag();
            String logContent1 = "";
            if (oldOpenFlag != newOpenFlag) {
                if (newOpenFlag == 1) {
                    logContent1 = "任务从【关闭】修改为【启用】";
                } else {
                    logContent1 = "任务从【启用】修改为【关闭】";
                }
            }
            String logContent2 = "";
            String oldType = "";
            String newType = "";
            String oldSendType = oldDTO.getSendType();
            String newSendType = dto.getSendType();
            if (oldSendType.contains("1")) {
                oldType += "客户群发";
            }
            if (newSendType.contains("1")) {
                newType += "客户群发";
            }
            if (oldSendType.contains("2")) {
                if (StringUtils.isNotBlank(oldType)) {
                    oldType += "、";
                }
                oldType += "社群群发";
            }
            if (newSendType.contains("2")) {
                if (StringUtils.isNotBlank(newType)) {
                    newType += "、";
                }
                newType += "社群群发";
            }
            if (oldSendType.contains("3")) {
                if (StringUtils.isNotBlank(oldType)) {
                    oldType += "、";
                }
                oldType += "企微朋友圈";
            }
            if (newSendType.contains("3")) {
                if (StringUtils.isNotBlank(newType)) {
                    newType += "、";
                }
                newType += "企微朋友圈";
            }
            if (!oldType.equals(newType)) {
                logContent2 += "执行消息类型从【" + oldType + "】修改为【" + newType + "】";
            }
            String logContent = this.addListForLog(logContent1, logContent2);
            if (StringUtils.isNotBlank(logContent)) {
                GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
                GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
            } else {
                GicLogRecordEvaluationContext.noWriteLog();
            }
        }else {
            GicLogRecordEvaluationContext.noWriteLog();
        }
        return RestResponse.successResult(resp.getResult());
    }

    private String addListForLog(String... arr) {
        List<String> list = new ArrayList<>();
        for (String s : arr) {
            if (StringUtils.isNotBlank(s)) {
                list.add(s);
            }
        }
        if (CollectionUtils.isNotEmpty(list)) {
            return list.stream().collect(Collectors.joining("，"));
        }
        return "";
    }

    /**
     * 预估需要执行的天数
     *
     * @param dto
     * @return
     */
    @RequestMapping("calculate-add-day")
    public RestResponse<Integer> calculateAddDay(@RequestBody OpenQwAddTaskDTO dto) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        // 添加的人数 1和专属无好友 2和所有无好友
        int memberRule= dto.getMemberRule() ;
        int qywxFlag = 0 ;
        if(memberRule==2) {
            qywxFlag = 1 ;
        }
        int memberNum = this.getMemberNum(dto.getSearchParams(), dto.getMemberType(),qywxFlag);
        // 成员数
        int staffNum = this.openStaffApiService.listAllOnlineStaff(wxEnterpriseId, enterpriseId).size();
        if (staffNum == 0) {
            return RestResponse.successResult(0);
        }
        // 一次添加人数
        OpenQwAddTaskSettingDTO setting = this.getAddSetting();
        if (null == setting) {
            return RestResponse.successResult(0);
        }
        int min = (setting.getAddIntervalEnd() + setting.getAddIntervalStart()) / 2;
        int hour = Integer.valueOf(setting.getAddTime().split("-")[1].split(":")[0]) -
                Integer.valueOf(setting.getAddTime().split("-")[0].split(":")[0]);
        int m = (hour * 60 / min);
        int days = BigDecimal.valueOf(memberNum).divide(BigDecimal.valueOf(m * staffNum), BigDecimal.ROUND_UP).intValue();
        log.info("member={},staff={},m={}", memberNum, staffNum, m);
        return RestResponse.successResult(days);
    }

    private int getMemberNum(String searchParams, int memberType , int qywxFlag) {
        RestResponse<Object> resp = this.memberController.getMemberCount(searchParams, memberType,qywxFlag);
        return Integer.valueOf(resp.getResult().toString());
    }

    @RequestMapping("test")
    public RestResponse<Object> test(String memberId) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        String ret = this.openQwApiService.matchStaffTest(wxEnterpriseId, enterpriseId, memberId);
        return RestResponse.successResult(ret);
    }

    /**
     * 音频文件转mp3
     * @return
     */
    @RequestMapping("list-silk")
    @com.gic.web.common.ano.IgnoreLogin
    @IgnoreLogin
    public Object listSilk() {
        List<OpenQwSilkMp3DTO> ret = this.openQwApiService.listSilk();
        RedisUtil.setCache("haobansilk2mp3",1,5L, TimeUnit.MINUTES);
        return RestResponse.successResult(ret);
    }

    @RequestMapping("silk2mp3")
    @com.gic.web.common.ano.IgnoreLogin
    @IgnoreLogin
    public Object silk2Mp3(HttpServletRequest request, String enterpriseId, int type, Long id , Long relationId) throws IOException {
        EnterpriseDTO enterpriseDTO = this.enterpriseService.getEnterpriseById(enterpriseId);
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> list = multiRequest.getMultiFileMap().get("media");
        MultipartFile mf = list.get(0);
        byte[] data = mf.getBytes();
        CloudFileInfo uploadInfo = CloudFileUtil.uploadFile(data, "mp3", CloudFileTypeEnum.AUDIO, enterpriseDTO.getFactoryCode(), CloudFileBusinessOptEnum.COMMON_QYWX);
        log.info("silk2mp3={}",uploadInfo);
        this.openQwApiService.updateToMp3(enterpriseId,type,id,relationId,uploadInfo.getOrgFileUrl());
        return uploadInfo;
    }

}
