package com.tzld.piaoquan.api.service.contentplatform.impl;

import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.api.common.enums.ExceptionEnum;
import com.tzld.piaoquan.api.common.enums.contentplatform.AccountStatusEnum;
import com.tzld.piaoquan.api.common.enums.contentplatform.PlanStatusEnum;
import com.tzld.piaoquan.api.common.exception.CommonException;
import com.tzld.piaoquan.api.component.AigcApiService;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ContentPlatformGzhAccountMapper;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ext.ContentPlatformGzhAccountMapperExt;
import com.tzld.piaoquan.api.model.config.LoginUserContext;
import com.tzld.piaoquan.api.model.param.contentplatform.CooperateAccountListParam;
import com.tzld.piaoquan.api.model.param.contentplatform.CooperateAccountSaveParam;
import com.tzld.piaoquan.api.model.param.contentplatform.GzhAuthResultParam;
import com.tzld.piaoquan.api.model.po.contentplatform.ContentPlatformAccount;
import com.tzld.piaoquan.api.model.po.contentplatform.ContentPlatformGzhAccount;
import com.tzld.piaoquan.api.model.po.contentplatform.ContentPlatformGzhAccountExample;
import com.tzld.piaoquan.api.model.po.contentplatform.ContentPlatformGzhPlan;
import com.tzld.piaoquan.api.model.vo.contentplatform.CooperateAccountItemVO;
import com.tzld.piaoquan.api.model.vo.contentplatform.GenerateQrcodeVO;
import com.tzld.piaoquan.api.model.vo.contentplatform.GzhAccountItem;
import com.tzld.piaoquan.api.model.vo.contentplatform.GzhAuthResultVO;
import com.tzld.piaoquan.api.service.GhDetailService;
import com.tzld.piaoquan.api.service.contentplatform.ContentPlatformAccountService;
import com.tzld.piaoquan.api.service.contentplatform.ContentPlatformCooperateAccountService;
import com.tzld.piaoquan.api.service.contentplatform.ContentPlatformPlanService;
import com.tzld.piaoquan.growth.common.model.po.GhDetail;
import com.tzld.piaoquan.growth.common.utils.page.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ContentPlatformCooperateAccountServiceImpl implements ContentPlatformCooperateAccountService {

    @Autowired
    private AigcApiService aigcApiService;
    @Autowired
    private ContentPlatformGzhAccountMapper gzhAccountMapper;
    @Autowired
    private ContentPlatformGzhAccountMapperExt gzhAccountMapperExt;
    @Autowired
    private GhDetailService ghDetailService;
    @Autowired
    private ContentPlatformPlanService planService;
    @Autowired
    private ContentPlatformAccountService accountService;

    @Override
    public Page<CooperateAccountItemVO> gzhList(CooperateAccountListParam param) {
        ContentPlatformAccount loginAccount = LoginUserContext.getUser();
        Page<CooperateAccountItemVO> result = new Page<>(param.getPageNum(), param.getPageSize());
        int offset = (param.getPageNum() - 1) * param.getPageSize();
        int count = gzhAccountMapperExt.getCooperateAccountCount(param, loginAccount.getId());
        result.setTotalSize(count);
        if (count == 0) {
            return result;
        }
        List<ContentPlatformGzhAccount> accountList = gzhAccountMapperExt.getCooperateAccountList(param,
                loginAccount.getId(), offset, param.getPageSize());
        List<CooperateAccountItemVO> list = buildCooperateAccountItemVOList(accountList);
        result.setObjs(list);
        return result;
    }

    private List<CooperateAccountItemVO> buildCooperateAccountItemVOList(List<ContentPlatformGzhAccount> accountList) {
        if (CollectionUtils.isEmpty(accountList)) {
            return null;
        }
        List<CooperateAccountItemVO> result = new ArrayList<>();
        for (ContentPlatformGzhAccount account : accountList) {
            CooperateAccountItemVO accountVO = new CooperateAccountItemVO();
            accountVO.setId(account.getId());
            accountVO.setName(account.getName());
            accountVO.setGhId(account.getGhId());
            accountVO.setType(account.getType());
            accountVO.setContentType(account.getContentType());
            accountVO.setCreateTimestamp(account.getCreateTimestamp());
            result.add(accountVO);
        }
        return result;
    }

    @Override
    public void gzhSave(CooperateAccountSaveParam param) {
        ContentPlatformAccount loginAccount = LoginUserContext.getUser();
        List<ContentPlatformAccount> ghIdExistList = gzhAccountMapperExt.getGhIdExists(loginAccount.getId(), param.getGhId());
        if (CollectionUtils.isNotEmpty(ghIdExistList)) {
            throw new CommonException(ExceptionEnum.GZH_EXISTS);
        }
        // 已存在则可重新授权
        Long existId = getExistGzhAccountId(loginAccount.getId(), param.getGhId());
        if (Objects.nonNull(existId)) {
            param.setId(existId);
        }
        Long now = System.currentTimeMillis();
        ContentPlatformGzhAccount account = new ContentPlatformGzhAccount();
        account.setName(param.getName());
        account.setGhId(param.getGhId());
        account.setType(param.getType());
        account.setContentType(param.getContentType());
        account.setUpdateTimestamp(now);
        if (Objects.isNull(param.getId())) {
            String externalId = aigcApiService.getDetailByGhId(param.getGhId());
            if (StringUtils.hasText(externalId)) {
                account.setExternalId(externalId);
            }
            account.setCreateAccountId(loginAccount.getId());
            account.setCreateTimestamp(now);
            gzhAccountMapper.insertSelective(account);
        } else {
            ContentPlatformGzhAccount existing = gzhAccountMapper.selectByPrimaryKey(param.getId());
            if (!Objects.equals(loginAccount.getId(), existing.getCreateAccountId())) {
                throw new CommonException(ExceptionEnum.PARAM_ERROR);
            }
            account.setId(param.getId());
            account.setStatus(AccountStatusEnum.NORMAL.getVal());
            gzhAccountMapper.updateByPrimaryKeySelective(account);
        }
    }

    private Long getExistGzhAccountId(Long loginUserId, String ghId) {
        ContentPlatformGzhAccountExample example = new ContentPlatformGzhAccountExample();
        example.createCriteria().andCreateAccountIdEqualTo(loginUserId).andGhIdEqualTo(ghId);
        List<ContentPlatformGzhAccount> accountList = gzhAccountMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(accountList)) {
            return accountList.get(0).getId();
        }
        return null;
    }

    @Override
    public GenerateQrcodeVO getGzhAuthQrCode(GzhAuthResultParam param) {
        String qrcodeStr = aigcApiService.generateQrcode(param.getCode());
        return GenerateQrcodeVO.builder().qrcodeStr(qrcodeStr).build();
    }


    @Override
    public GzhAuthResultVO getGzhAuthResult(GzhAuthResultParam param) {
        String publishAccountId = aigcApiService.getAuthResult(param.getCode());
        if (StringUtils.hasText(publishAccountId)) {
            JSONObject detail = aigcApiService.getAccountDetail(publishAccountId);
            String name = detail.getString("name");
            String ghId = detail.getString("ghId");
            return GzhAuthResultVO.builder().name(name).ghId(ghId).build();
        }
        return null;
    }

    @Override
    public List<String> getGzhContentType() {
        return Arrays.asList("泛历史", "泛生活");
    }

    @Override
    public List<GzhAccountItem> getGzhAccountList(Integer accountType, String name) {
        ContentPlatformAccount loginAccount = LoginUserContext.getUser();
        return gzhAccountMapperExt.getGzhAccountList(loginAccount.getId(), accountType, name);
    }

    @Override
    public void gzhDelete(Long id) {
        ContentPlatformGzhAccount existing = gzhAccountMapper.selectByPrimaryKey(id);
        if (Objects.isNull(existing)) {
            return;
        }
        if (!Objects.equals(LoginUserContext.getUser().getId(), existing.getCreateAccountId())) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR);
        }
        List<ContentPlatformGzhPlan> planList = planService.getGzhPlanListByCooperateAccountId(id);
        if (CollectionUtils.isNotEmpty(planList)) {
            throw new CommonException(ExceptionEnum.GZH_DELETE_PLAN_EXISTS);
        }
        ContentPlatformGzhAccount gzhAccount = new ContentPlatformGzhAccount();
        gzhAccount.setId(id);
        gzhAccount.setStatus(AccountStatusEnum.FORBIDDEN.getVal());
        gzhAccount.setUpdateTimestamp(System.currentTimeMillis());
        gzhAccountMapper.updateByPrimaryKeySelective(gzhAccount);
    }

    @Override
    public List<ContentPlatformGzhAccount> getAccountListByIds(List<Long> ids) {
        ContentPlatformGzhAccountExample example = new ContentPlatformGzhAccountExample();
        example.createCriteria().andIdIn(ids);
        return gzhAccountMapper.selectByExample(example);
    }

    @Override
    public List<ContentPlatformGzhAccount> getAccountListByGhIds(List<String> ghIds, Long creatorId) {
        ContentPlatformGzhAccountExample example = new ContentPlatformGzhAccountExample();
        example.createCriteria().andGhIdIn(ghIds).andCreateAccountIdEqualTo(creatorId);
        return gzhAccountMapper.selectByExample(example);
    }

    @Override
    public ContentPlatformGzhAccount getById(Long id) {
        return gzhAccountMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<ContentPlatformGzhAccount> getCooperateAccountListByGhIds(Long loginAccountId, List<String> ghIds) {
        ContentPlatformGzhAccountExample gzhAccountExample = new ContentPlatformGzhAccountExample();
        gzhAccountExample.createCriteria().andCreateAccountIdEqualTo(loginAccountId).andGhIdIn(ghIds)
                .andStatusEqualTo(AccountStatusEnum.NORMAL.getVal());
        return gzhAccountMapper.selectByExample(gzhAccountExample);
    }


    @Override
    public void gzhImport(List<String> channels) {
        List<ContentPlatformAccount> accountList = accountService.getAccountListByChannels(channels);
        if (CollectionUtils.isEmpty(accountList)) {
            throw new CommonException(ExceptionEnum.ACCOUNT_NOT_EXISTS_WRONG);
        }
        for (ContentPlatformAccount account : accountList) {
            List<GhDetail> ghDetailList = ghDetailService.getByChannel(account.getChannel());
            Map<String, GhDetail> ghDetailMap = ghDetailList.stream().collect(Collectors.toMap(GhDetail::getGhId, Function.identity()));
            List<String> ghIds = ghDetailList.stream().map(GhDetail::getGhId).collect(Collectors.toList());
            List<ContentPlatformGzhAccount> gzhAccountList = getCooperateAccountListByGhIds(account.getId(), ghIds);
            List<String> existGhIdList = new ArrayList<>();
            for (ContentPlatformGzhAccount gzhAccount : gzhAccountList) {
                existGhIdList.add(gzhAccount.getGhId());
            }
            Long now = System.currentTimeMillis();
            List<String> addFailGhIds = new ArrayList<>();
            for (String ghId : ghIds) {
                if (existGhIdList.contains(ghId)) {
                    continue;
                }
                List<ContentPlatformAccount> ghIdExistList = gzhAccountMapperExt.getGhIdExists(account.getId(), ghId);
                if (CollectionUtils.isNotEmpty(ghIdExistList)) {
                    addFailGhIds.add(ghId);
                }
                GhDetail ghDetail = ghDetailMap.get(ghId);
                ContentPlatformGzhAccount gzhAccount = new ContentPlatformGzhAccount();
                gzhAccount.setName(ghDetail.getGhName());
                gzhAccount.setGhId(ghDetail.getGhId());
                gzhAccount.setContentType(ghDetail.getCategory1());
                gzhAccount.setUpdateTimestamp(now);
                String externalId = aigcApiService.getDetailByGhId(ghDetail.getGhId());
                if (StringUtils.hasText(externalId)) {
                    gzhAccount.setExternalId(externalId);
                }
                gzhAccount.setCreateAccountId(account.getId());
                gzhAccount.setCreateTimestamp(now);
                gzhAccountMapper.insertSelective(gzhAccount);
            }
            if (CollectionUtils.isNotEmpty(addFailGhIds)) {
                log.error("导入失败账号 channel:{} ghIds:{}", account.getChannel(), addFailGhIds);
            }
        }
    }

    @Override
    public ContentPlatformGzhAccount getGzhAccount(String ghId) {
        ContentPlatformGzhAccountExample example = new ContentPlatformGzhAccountExample();
        example.createCriteria().andGhIdEqualTo(ghId).andStatusEqualTo(PlanStatusEnum.NORMAL.getVal());
        List<ContentPlatformGzhAccount> accountList = gzhAccountMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(accountList)) {
            return accountList.get(0);
        }
        return null;
    }

    @Override
    public List<ContentPlatformGzhAccount> getAccountListByCreatorId(Long creatorId) {
        ContentPlatformGzhAccountExample example = new ContentPlatformGzhAccountExample();
        example.createCriteria().andCreateAccountIdEqualTo(creatorId).andStatusEqualTo(PlanStatusEnum.NORMAL.getVal());
        return gzhAccountMapper.selectByExample(example);
    }
}
