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

import com.gic.api.base.commons.Constant;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.EntityUtil;
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.manage.api.dto.hm.HmWelcomeRelationDTO;
import com.gic.haoban.manage.api.dto.welcome.dto.FriendSettingDetailDTO;
import com.gic.haoban.manage.api.dto.welcome.dto.WelcomeDetailDTO;
import com.gic.haoban.manage.api.dto.welcome.dto.WelcomeListDTO;
import com.gic.haoban.manage.api.dto.welcome.dto.WelcomeMediaDTO;
import com.gic.haoban.manage.api.dto.welcome.dto.WelcomeRemoveCheckDTO;
import com.gic.haoban.manage.api.dto.welcome.qdto.QueryWelcomeQDTO;
import com.gic.haoban.manage.api.dto.welcome.qdto.QueryWelcomeRelationQDTO;
import com.gic.haoban.manage.api.dto.welcome.qdto.SaveFriendSettingQDTO;
import com.gic.haoban.manage.api.dto.welcome.qdto.SaveWelcomeMediaQDTO;
import com.gic.haoban.manage.api.dto.welcome.qdto.SaveWelcomeQDTO;
import com.gic.haoban.manage.api.enums.WelcomeMediaTypeEnum;
import com.gic.haoban.manage.api.enums.hm.HmWelcomeType;
import com.gic.haoban.manage.api.service.hm.HmWelcomeRelationApiService;
import com.gic.haoban.manage.api.service.out.WelcomeApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.log.LogRecordAfterServiceImpl;
import com.gic.haoban.manage.web.log.LogRecordUserServiceImpl;
import com.gic.haoban.manage.web.qo.welcome.ListWelcomeQO;
import com.gic.haoban.manage.web.qo.welcome.SaveFriendSettingQO;
import com.gic.haoban.manage.web.qo.welcome.SaveWelcomeQO;
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 org.apache.commons.collections.CollectionUtils;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * desc：欢迎语controller
 *
 * @author: YongEn
 * @date: 2022/2/8
 **/
@RestController
@RequestMapping("/welcome")
public class WelcomeController extends WebBaseController {

    @Autowired
    private WelcomeApiService welcomeApiService;

    @Autowired
    private HmWelcomeRelationApiService welcomeRelationApiService;


    /**
     * desc: 校验企业是否存在全员欢迎语
     *
     * @param wxEnterpriseId 微信企业id
     * @return : {@link RestResponse< Boolean>}
     * @author : YongEn
     * @date : 2022/3/9
     */
    @RequestMapping(value = "/exist-default-welcome")
    public RestResponse<Boolean> existDefaultWelcome(@RequestParam("wxEnterpriseId") String wxEnterpriseId) {
        ServiceResponse<Boolean> response = welcomeApiService.existDefaultWelcome(wxEnterpriseId);
        return RestResponse.successResult(response.getResult());
    }

    /**
     * desc: 保存欢迎语
     *
     * @param qo qo
     * @return : {@link RestResponse< Boolean>}
     * @author : YongEn
     * @date : 2022/2/11
     */
    @GicLogRecord(value = "${#logContent}", category = GicLogRecordCategoryEnum.WELCOME, optType = GicLogRecordOptTypeEnum.NORMAL_WELCOME_ADD
            ,optPage = "欢迎语设置-新建欢迎语", userFunc = LogRecordUserServiceImpl.class, afterFunc = LogRecordAfterServiceImpl.class)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public RestResponse<Boolean> saveWelcome(@RequestBody @Valid SaveWelcomeQO qo) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        SaveWelcomeQDTO qdto = new SaveWelcomeQDTO();
        qdto.setWelcomeId(qo.getWelcomeId());
        qdto.setWxEnterpriseId(qo.getWxEnterpriseId());
        qdto.setTitle(qo.getTitle());
        qdto.setWelcomeContent(qo.getWelcomeContent());
        qdto.setOperatorId(login.getClerkId());
        qdto.setOperatorName(login.getClerkName());
        qdto.setDefaultWelcomeFlag(qo.getDefaultWelcomeFlag());
        qdto.setWelcomeMediaList(EntityUtil.changeEntityListNew(SaveWelcomeMediaQDTO.class, qo.getWelcomeMediaList()));
        qdto.setSuitDepartmentAddList(qo.getSuitDepartmentAddList());
        qdto.setSuitDepartmentDeleteList(qo.getSuitDepartmentDeleteList());
        qdto.setCreatorId(login.getClerkId());
        qdto.setCreatorName(login.getClerkFullName());
        qdto.setModifierId(login.getClerkId());
        qdto.setModifierName(login.getClerkFullName());
        qdto.setType(qo.getType());
        qdto.setScene(qo.getScene());
        if (qo.getType() == null) {
            qdto.setType(HmWelcomeType.NORMAL.getCode());
        }
        StringBuilder logContent = new StringBuilder();
        if (StringUtils.isBlank(qdto.getWelcomeId())){
            logContent.append("新增");
        }else {
            logContent.append("修改");
        }
        if (HmWelcomeType.NORMAL.getCode().equals(qdto.getType())){
            GicLogRecordEvaluationContext.putAttribute(LogRecordAfterServiceImpl.WELCOME_TYPE, HmWelcomeType.NORMAL.getCode());
            logContent.append("普通欢迎语");
            GicLogRecordEvaluationContext.noWriteLog();
        }else {
            GicLogRecordEvaluationContext.putAttribute(LogRecordAfterServiceImpl.WELCOME_TYPE, HmWelcomeType.SPECIAL.getCode());
            logContent.append("特殊欢迎语");
        }
        if (qdto.getWelcomeId() == null) {
            logContent.append("【");
            logContent.append(qdto.getTitle());
            logContent.append("】");
            GicLogRecordEvaluationContext.putAttribute(LogRecordAfterServiceImpl.WELCOME_OPT, "add");
        } else {
            GicLogRecordEvaluationContext.putAttribute(LogRecordAfterServiceImpl.WELCOME_OPT, "edit");
            ServiceResponse<WelcomeDetailDTO> welcomeResult = welcomeApiService.getWelcome(qdto.getWelcomeId(), qdto.getWxEnterpriseId());
            if (welcomeResult.getResult() != null) {
                WelcomeDetailDTO welcomeDetail = welcomeResult.getResult();
                logContent.append(this.buildEditWelcomeOpLog(welcomeDetail, qdto));
            }
        }
        GicLogRecordEvaluationContext.putAttribute("logContent", logContent.toString());
        ServiceResponse<Boolean> response = welcomeApiService.saveWelcome(qdto);
        if (!response.isSuccess()){
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        return RestResponse.successResult(response.getResult());
    }

    private String buildEditWelcomeOpLog(WelcomeDetailDTO welcomeDetail, SaveWelcomeQDTO qdto) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("编辑特殊欢迎语：欢迎语标题「")
                .append(welcomeDetail.getTitle())
                .append("」变更为「 ")
                .append(qdto.getTitle())
                .append("」，欢迎语内容「")
                .append(welcomeDetail.getWelcomeContent())
                .append("」更改为「")
                .append(qdto.getWelcomeContent())
                .append("」");
        List<String> oldMedia = new ArrayList<>();
        for (WelcomeMediaDTO welcomeMediaDTO : welcomeDetail.getWelcomeMediaList()) {
            oldMedia.add(WelcomeMediaTypeEnum.getDescByCode(welcomeMediaDTO.getMediaType()) + "-" + welcomeMediaDTO.getMediaTitle());
        }
        List<String> newMedia = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(qdto.getWelcomeMediaList())) {
            for (SaveWelcomeMediaQDTO saveWelcomeMediaQDTO : qdto.getWelcomeMediaList()) {
                newMedia.add(WelcomeMediaTypeEnum.getDescByCode(saveWelcomeMediaQDTO.getMediaType()) + "-" + saveWelcomeMediaQDTO.getMediaTitle());
            }
        }
        if (CollectionUtils.isNotEmpty(oldMedia) || CollectionUtils.isNotEmpty(newMedia)) {
            stringBuilder.append("，附件「");
            stringBuilder.append(StringUtils.join(oldMedia, "、"))
                    .append("」变更为「")
                    .append(StringUtils.join(newMedia, "、"))
                    .append("」");
        }
        return stringBuilder.toString();
    }

    /**
     * desc: 删除欢迎语
     *
     * @param welcomeId 欢迎语id
     * @return : {@link RestResponse< Boolean>}
     * @author : YongEn
     * @date : 2022/2/11
     */
    @GicLogRecord(value = "${#logContent}", category = GicLogRecordCategoryEnum.WELCOME, optType = GicLogRecordOptTypeEnum.NORMAL_WELCOME_DEL
            ,optPage = "欢迎语设置-特殊欢迎语", userFunc = LogRecordUserServiceImpl.class, afterFunc = LogRecordAfterServiceImpl.class)
    @RequestMapping(value = "/remove")
    public RestResponse<?> removeWelcome(@RequestParam("welcomeId") String welcomeId) {
        if (StringUtils.isEmpty(welcomeId)) {
            return RestResponse.failure(Constant.STRING_1, "欢迎语id为空", Boolean.FALSE);
        }
        // 构建操作日志
        this.buildDelWelComeOpLog(welcomeId);
        ServiceResponse<WelcomeRemoveCheckDTO> serviceResponse = welcomeApiService.removeWelcomeWithErrorInfo(welcomeId);
        if (serviceResponse.getResult() != null) {
            // can't remove
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure(HaoBanErrCode.ERR_9.getCode() + "", this.buildErrorMessage(serviceResponse.getResult()));
        }
        return RestResponse.successResult();
    }

    private void buildDelWelComeOpLog(String welcomeId) {
        String logContent = "删除";
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        ServiceResponse<WelcomeDetailDTO> serviceWelcome = welcomeApiService.getWelcome(welcomeId, loginUser.getEnterpriseId());
        Integer welcomeType = HmWelcomeType.NORMAL.getCode();
        String oldWelcomeTitle = "";
        if (serviceWelcome.isSuccess() && serviceWelcome.getResult() != null){
            String title = serviceWelcome.getResult().getTitle();
            welcomeType = serviceWelcome.getResult().getType();
            if (HmWelcomeType.NORMAL.getCode().equals(welcomeType)){
                logContent += "普通";
            }else if (HmWelcomeType.SPECIAL.getCode().equals(welcomeType)){
                logContent += "特殊";
            }
            oldWelcomeTitle = title;
        }
        logContent += "欢迎语";
        if (StringUtils.isNotBlank(oldWelcomeTitle)){
            logContent = logContent + "【" + oldWelcomeTitle + "】";
        }
        GicLogRecordEvaluationContext.putAttribute("welcome_del_type", welcomeType);
        GicLogRecordEvaluationContext.putAttribute("logContent", logContent);
    }

    private String buildErrorMessage(WelcomeRemoveCheckDTO welcomeRemoveCheckDTO) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (welcomeRemoveCheckDTO.getQrCodeReferNum() != null
                && welcomeRemoveCheckDTO.getQrCodeReferNum() > 0
                && welcomeRemoveCheckDTO.getLinkReferNum() != null
                && welcomeRemoveCheckDTO.getLinkReferNum() > 0) {
            stringBuilder.append("当前模板已关联状态为正常的活码（")
                    .append(welcomeRemoveCheckDTO.getQrCodeReferNum())
                    .append("）、链接（")
                    .append(welcomeRemoveCheckDTO.getLinkReferNum())
                    .append("），请确认相关活码是否不再使用该欢迎语以及链接已投放结束，取消关联后才可删除该模板");
        } else if (welcomeRemoveCheckDTO.getQrCodeReferNum() != null
                && welcomeRemoveCheckDTO.getQrCodeReferNum() > 0) {
            stringBuilder.append("当前模板已关联状态为正常的活码（")
                    .append(welcomeRemoveCheckDTO.getQrCodeReferNum())
                    .append("），请确认相关活码是否不再使用该欢迎语，取消关联后才可删除该模板");
        } else if (welcomeRemoveCheckDTO.getLinkReferNum() != null
                && welcomeRemoveCheckDTO.getLinkReferNum() > 0) {
            stringBuilder.append("当前模板已关联状态为正常的链接（")
                    .append(welcomeRemoveCheckDTO.getLinkReferNum())
                    .append("），请确认相关链接已投放结束，取消关联后才可删除该模板");
        }
        return stringBuilder.toString();
    }

    /**
     * desc: 查询欢迎语列表
     *
     * @param qo qo
     * @return : {@link RestResponse< List< WelcomeListDTO>>}
     * @author : YongEn
     * @date : 2022/2/11
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public RestResponse<Page<WelcomeListDTO>> listWelcome(@RequestBody @Valid ListWelcomeQO qo) {
        QueryWelcomeQDTO queryWelcomeQDTO = new QueryWelcomeQDTO();
        queryWelcomeQDTO.setTitle(qo.getTitle());
        queryWelcomeQDTO.setWxEnterpriseId(qo.getWxEnterpriseId());
        queryWelcomeQDTO.setPageNum(qo.getPageNum());
        queryWelcomeQDTO.setPageSize(qo.getPageSize());
        queryWelcomeQDTO.setType(qo.getType());
        queryWelcomeQDTO.setScene(qo.getScene());
        if (qo.getType() == null) {
            queryWelcomeQDTO.setType(HmWelcomeType.NORMAL.getCode());
        }
        ServiceResponse<Page<WelcomeListDTO>> serviceResponse = welcomeApiService.listWelcomeWithCondition(queryWelcomeQDTO);
        return RestResponse.successResult(serviceResponse.getResult());
    }

    /**
     * desc: 获取欢迎语
     *
     * @param welcomeId 欢迎语id
     * @return : {@link RestResponse< WelcomeDetailDTO>}
     * @author : YongEn
     * @date : 2022/2/11
     */
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public RestResponse<WelcomeDetailDTO> getWelcome(@RequestParam("welcomeId") String welcomeId,
                                                     @RequestParam("enterpriseId") String enterpriseId) {
        if (StringUtils.isEmpty(welcomeId)) {
            RestResponse.failure(Constant.STRING_1, "欢迎语id为空");
        }
        ServiceResponse<WelcomeDetailDTO> response = welcomeApiService.getWelcome(welcomeId, enterpriseId);
        return RestResponse.successResult(response.getResult());
    }

    /**
     * desc: 保存加好友配置
     *
     * @param qo qo
     * @return : {@link RestResponse< Boolean>}
     * @author : YongEn
     * @date : 2022/2/11
     * @deprecated 本次迭代即将删除
     */
    @RequestMapping(value = "/save/friend-setting", method = RequestMethod.POST)
    public RestResponse<Boolean> saveFriendSetting(@RequestBody @Valid SaveFriendSettingQO qo) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        SaveFriendSettingQDTO qdto = EntityUtil.changeEntityNew(SaveFriendSettingQDTO.class, qo);
        ServiceResponse<Boolean> response = welcomeApiService.saveFriendSetting(qdto);
        return RestResponse.successResult(response.getResult());
    }

    /**
     * desc: 获取加好友配置
     *
     * @param wxEnterpriseId 微信企业id
     * @return : {@link RestResponse< FriendSettingDetailDTO>}
     * @author : YongEn
     * @date : 2022/2/11
     * @deprecated 本次迭代即将删除
     */
    @RequestMapping(value = "/get/friend-setting", method = RequestMethod.GET)
    public RestResponse<FriendSettingDetailDTO> getFriendSetting(@RequestParam("wxEnterpriseId") String wxEnterpriseId) {
        if (StringUtils.isEmpty(wxEnterpriseId)) {
            RestResponse.failure(Constant.STRING_1, "微信企业id为空", Boolean.FALSE);
        }
        ServiceResponse<FriendSettingDetailDTO> response = welcomeApiService.getFriendSetting(wxEnterpriseId);
        return RestResponse.successResult(response.getResult());
    }

    /**
     * desc: 保存默认欢迎语
     *
     * @param wxEnterpriseId 微信企业id
     * @return : {@link RestResponse< Boolean>}
     * @author : YongEn
     * @date : 2022/2/25
     */
    @RequestMapping(value = "/save-default-welcome", method = RequestMethod.GET)
    public RestResponse<Boolean> saveDefaultWelcome(@RequestParam("wxEnterpriseId") String wxEnterpriseId) {
        ServiceResponse<Boolean> response = welcomeApiService.saveDefaultWelcome(wxEnterpriseId);
        return RestResponse.successResult(response.getResult());
    }

    /**
     * desc: 刷新欢迎语媒体
     *
     * @return : {@link RestResponse< Boolean>}
     * @author : YongEn
     * @date : 2022/3/11
     */
    @RequestMapping(value = "/flush-welcome-media", method = RequestMethod.GET)
    public RestResponse<Boolean> flushWelcomeMedia() {
        ServiceResponse<Boolean> response = welcomeApiService.flushWelcomeMedia();
        return RestResponse.successResult(response.getResult());
    }

    @RequestMapping(path = "/relation/list")
    public RestResponse<Page<HmWelcomeRelationDTO>> queryWelcomeRelationList(@RequestParam("welcomeId") String welcomeId,
                                                                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                                             @RequestParam(value = "searchContent", required = false) String searchContent) {
        QueryWelcomeRelationQDTO queryWelcomeRelationQDTO = new QueryWelcomeRelationQDTO();
        queryWelcomeRelationQDTO.setWelcomeId(welcomeId);
        queryWelcomeRelationQDTO.setSearchContent(searchContent);
        queryWelcomeRelationQDTO.setPageNum(pageNum);
        queryWelcomeRelationQDTO.setPageSize(pageSize);
        ServiceResponse<Page<HmWelcomeRelationDTO>> serviceResponse = welcomeRelationApiService.queryWelcomeRelation(queryWelcomeRelationQDTO);
        if (serviceResponse.isSuccess()) {
            Page<HmWelcomeRelationDTO> result = serviceResponse.getResult();
            return RestResponse.successResult(result);
        }
        return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
    }


    @RequestMapping(path = "/statistics")
    public RestResponse<?> checkWelcomeReferStatistics(String welcomeId) {
        if (StringUtils.isBlank(welcomeId)) {
            return RestResponse.failure(HaoBanErrCode.ERR_2.getCode() + "", HaoBanErrCode.ERR_2.getMsg());
        }
        return RestResponse.successResult(welcomeApiService.welcomeReferStatistics(welcomeId).getResult());
    }

}
