package com.ruixuan.live.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruixuan.common.core.domain.ResultResponse;
import com.ruixuan.common.core.domain.entity.SysUser;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.PageUtils;
import com.ruixuan.data.utils.LiveDataExcelUtils;
import com.ruixuan.live.entity.KuaishouLiveProject;
import com.ruixuan.live.entity.KuaishouLiveUserAccount;
import com.ruixuan.live.mapper.KuaishouLiveProjectMapper;
import com.ruixuan.live.mapper.KuaishouLiveUserAccountMapper;
import com.ruixuan.live.mapper.KuaishouLiveUserAccountPartMapper;
import com.ruixuan.live.service.IKuaishouLiveUserAccountService;
import com.ruixuan.system.service.ISysRoleService;
import com.ruixuan.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 快手直播账户Service业务层处理
 *
 * @author ruoyi
 * @date 2022-05-31
 */
@Service
public class KuaishouLiveUserAccountServiceImpl implements IKuaishouLiveUserAccountService {

    @Autowired
    private KuaishouLiveUserAccountMapper kuaishouLiveUserAccountMapper;

    @Autowired
    private KuaishouLiveUserAccountPartMapper accountPartMapper;

    @Autowired
    private KuaishouLiveProjectMapper kuaishouLiveProjectMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 查询快手直播账户
     *
     * @param id 快手直播账户主键
     * @return 快手直播账户
     */
    @Override
    public JSONObject selectKuaishouLiveUserAccountById(String id) {
        KuaishouLiveUserAccount account = kuaishouLiveUserAccountMapper.selectKuaishouLiveUserAccountById(id);
        JSONObject object = JSONObject.parseObject(JSON.toJSONString(account));
        if (object != null) {
            List<JSONObject> parts = accountPartMapper.queryCollaboratorsById(account.getKsId(), account.getAccountId());
            object.put("collaborators", parts);
        }
        return object;
    }

    /**
     * 查询快手直播账户列表
     *
     * @param kuaishouLiveUserAccount 快手直播账户
     * @return 快手直播账户
     */
    @Override
    public List<KuaishouLiveUserAccount> selectKuaishouLiveUserAccountList(KuaishouLiveUserAccount kuaishouLiveUserAccount) {
        List<KuaishouLiveUserAccount> list = new ArrayList<>();
        String roleCode = roleService.selectRoleByUserId(kuaishouLiveUserAccount.getUserId());
        if ("admin".equals(roleCode)) {
            PageUtils.startPage();
            list = kuaishouLiveUserAccountMapper.selectKuaishouLiveUserAccountList(kuaishouLiveUserAccount);
        } else {
            List<Long> accountIds = kuaishouLiveUserAccountMapper.queryAccountIdsByUserId(kuaishouLiveUserAccount.getUserId());
            if (Check.isNotNull(accountIds) && accountIds.size() > 0) {
                kuaishouLiveUserAccount.setAccountIds(accountIds);
                PageUtils.startPage();
                list = kuaishouLiveUserAccountMapper.selectAllListByAccountIds(kuaishouLiveUserAccount);
            }
        }
        return list;
    }

    @Override
    public List<KuaishouLiveUserAccount> queryAllList(KuaishouLiveUserAccount userAccount) {
        List<KuaishouLiveUserAccount> list = new ArrayList<>();
        String roleCode = roleService.selectRoleByUserId(userAccount.getUserId());
        if ("admin".equals(roleCode)) {
            PageUtils.startPage();
            list = kuaishouLiveUserAccountMapper.queryAllList(userAccount);
        } else {
            List<Long> accountIds = kuaishouLiveUserAccountMapper.queryAccountIdsByUserId(userAccount.getUserId());
            if (Check.isNotNull(accountIds) && accountIds.size() > 0) {
                userAccount.setAccountIds(accountIds);
                PageUtils.startPage();
                list = kuaishouLiveUserAccountMapper.queryAllListByAccountIds(userAccount);
            }
        }
        return list;
    }


    /**
     * @param kuaishouLiveUserAccount 快手直播账户
     * @return 结果
     */
    @Override
    public ResultResponse insertKuaishouLiveUserAccount(KuaishouLiveUserAccount account) {
        if (Check.isNull(account.getAccountId())) {
            account.setAccountId(System.currentTimeMillis());
        }
        KuaishouLiveUserAccount one = kuaishouLiveUserAccountMapper.getOne(account);
        if (one != null) {
            return ResultResponse.error("快手ID：" + account.getKsId() + "下已存在该账户ID，请重新填写！");
        }
        String collaboratorList = account.getCollaboratorList();
        if (collaboratorList != null) {
            List<JSONObject> collaborators = JSONArray.parseArray(collaboratorList, JSONObject.class);
            for (JSONObject obj : collaborators) {
                obj.put("ksId", account.getKsId());
                obj.put("ksName", account.getKsName());
                obj.put("accountId", account.getAccountId());
                obj.put("accountName", account.getAccountName());
                obj.put("createrId", account.getCreaterId());
            }
            if (Check.isNotNull(collaborators)) {
                accountPartMapper.replaceBatch(collaborators);
            }
        }
        account.setId(UUID.randomUUID().toString().replace("-", ""));
        account.setProjectId(getAndInsertProject(account.getKsId(), account.getKsName()));
        account.setAccountStatus("审核通过");
        int num = kuaishouLiveUserAccountMapper.insertKuaishouLiveUserAccount(account);
        if (num > 0) {
            return ResultResponse.success();
        }
        return ResultResponse.error("fail");
    }

    private Long getAndInsertProject(Long id, String projectName) {
        KuaishouLiveProject project = kuaishouLiveProjectMapper.getOne(id, projectName);
        if (Check.isNull(project)) {
            KuaishouLiveProject kuaishouLiveProject = new KuaishouLiveProject();
            kuaishouLiveProject.setId(id);
            kuaishouLiveProject.setProjectName(projectName);
            kuaishouLiveProjectMapper.insertKuaishouLiveProject(kuaishouLiveProject);
        }
        return id;
    }

    @Override
    public ResultResponse insertByExcel(MultipartFile file, Long createrId) {
        List<KuaishouLiveUserAccount> accountList = new ArrayList<>();
        try {
            String fileName = file.getOriginalFilename();
            List<JSONObject> list = LiveDataExcelUtils.analysisFile(file, fileName);
            for (JSONObject object : list) {
                KuaishouLiveUserAccount account = new KuaishouLiveUserAccount(object, createrId);
                account.setOperatorLeaderId(getUserIdByName(account.getOperatorLeader()));
                account.setSaleLeaderId(getUserIdByName(account.getSaleLeader()));
                account.setProjectId(getAndInsertProject(account.getKsId(), account.getProjectName()));
                insertAccountPart(account);
                accountList.add(account);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponse.error("导入异常");
        }
        if (Check.isNotNull(accountList)) {
            kuaishouLiveUserAccountMapper.replaceBatch(accountList);
        }
        return ResultResponse.success();
    }


    private void insertAccountPart(KuaishouLiveUserAccount account) {
        String collaborators = account.getCollaboratorList();
        if (Check.isNotNull(collaborators)) {
            List<String> users = Arrays.asList(collaborators.split(";"));
            List<JSONObject> list = new ArrayList<>();
            for (String user : users) {
                JSONObject obj = new JSONObject();
                obj.put("ksId", account.getKsId());
                obj.put("ksName", account.getKsName());
                obj.put("accountId", account.getAccountId());
                obj.put("accountName", account.getAccountName());
                obj.put("createrId", account.getCreaterId());
                String idAndName = user.replace("(", "（").replace(")", "）").trim();
                String[] split = idAndName.split("（");
                obj.put("userId", getUserIdByName(split[0]));
                obj.put("nickName", split[0]);
                list.add(obj);
            }
            if (Check.isNotNull(collaborators)) {
                accountPartMapper.replaceBatch(list);
            }
        }
    }

    // 通过人员名字查询人员ID
    private String getUserIdByName(String name) {
        if (Check.isNull(name)) {
            return null;
        }
        SysUser user = sysUserService.selectUserByNickName(name);
        if (Check.isNotNull(user)) {
            return user.getUserId().toString();
        }
        return null;
    }

    /**
     * 修改快手直播账户
     */
    @Override
    public ResultResponse updateKuaishouLiveUserAccount(KuaishouLiveUserAccount account) {
        KuaishouLiveUserAccount one = kuaishouLiveUserAccountMapper.getOne(account);
        if (one == null) {
            return ResultResponse.error("未查询到账户");
        }
        int i = kuaishouLiveUserAccountMapper.updateKuaishouLiveUserAccount(account);
        if (i > 0) {
            String collaboratorList = account.getCollaboratorList();
            if (Check.isNotNull(collaboratorList) && !"[]".equals(collaboratorList)) {
                List<JSONObject> collaborators = JSONArray.parseArray(collaboratorList, JSONObject.class);
                for (JSONObject obj : collaborators) {
                    obj.put("ksId", account.getKsId());
                    obj.put("ksName", account.getKsName());
                    obj.put("accountId", account.getAccountId());
                    obj.put("accountName", account.getAccountName());
                    obj.put("createrId", account.getCreaterId());
                }

                if (Check.isNotNull(collaborators)) {
                    accountPartMapper.deleteByAccountId(account.getKsId(), account.getAccountId(), null);
                    accountPartMapper.replaceBatch(collaborators);
                }
            } else {
                accountPartMapper.deleteByAccountId(account.getKsId(), account.getAccountId(), null);
            }
            return ResultResponse.success();
        }
        return ResultResponse.error("fail");
    }

    /**
     * 批量删除快手直播账户
     *
     * @param ids 需要删除的快手直播账户主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouLiveUserAccountByIds(String[] ids) {
        return kuaishouLiveUserAccountMapper.deleteKuaishouLiveUserAccountByIds(ids);
    }

    /**
     * 删除快手直播账户信息
     *
     * @param id 快手直播账户主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouLiveUserAccountById(String id) {
        return kuaishouLiveUserAccountMapper.deleteKuaishouLiveUserAccountById(id);
    }

    @Override
    public List<JSONObject> queryNicknameList() {
        return kuaishouLiveUserAccountMapper.queryNicknameList();
    }

    @Override
    public List<JSONObject> queryAccountListByKsId(Long ksId) {
        return kuaishouLiveUserAccountMapper.queryAccountListByKsId(ksId);
    }

    @Override
    public ResultResponse queryRoles(String type) {
        List<JSONObject> list = sysUserService.queryRoles(type);
        return ResultResponse.success(list);
    }

    @Override
    public ResultResponse queryAccountAllUsers(Long ksId, Long accountId) {
        List<JSONObject> collaborators = accountPartMapper.queryAccountCollaborators(ksId, accountId);
        KuaishouLiveUserAccount account = new KuaishouLiveUserAccount();
        account.setAccountId(accountId);
        account.setKsId(ksId);
        KuaishouLiveUserAccount one = kuaishouLiveUserAccountMapper.getOne(account);
        if (Check.isNotNull(one)) {
            if (Check.isNotNull(one.getSaleLeaderId())) {
                JSONObject obj = new JSONObject();
                obj.put("role", "saleLeader");
                obj.put("roleName", "销售负责人");
                obj.put("userId", one.getSaleLeaderId());
                obj.put("name", one.getSaleLeader());
                collaborators.add(obj);
            }
            if (Check.isNotNull(one.getOperatorLeaderId())) {
                JSONObject obj = new JSONObject();
                obj.put("role", "operatorLeader");
                obj.put("roleName", "运营负责人");
                obj.put("userId", one.getOperatorLeaderId());
                obj.put("name", one.getOperatorLeader());
                collaborators.add(obj);
            }
            if (Check.isNotNull(one.getDesignerLeaderId())) {
                JSONObject obj = new JSONObject();
                obj.put("role", "designerLeader");
                obj.put("roleName", "设计负责人");
                obj.put("userId", one.getDesignerLeaderId());
                obj.put("name", one.getDesignerLeader());
                collaborators.add(obj);
            }
        }
        return ResultResponse.success(collaborators);
    }

    @Override
    public ResultResponse deleteAccountAllUser(Long ksId, Long accountId, String role, Long userId) {
        if ("collaborator".equals(role)) {
            accountPartMapper.deleteByAccountId(ksId, accountId, userId);
        } else {
            KuaishouLiveUserAccount account = new KuaishouLiveUserAccount();
            account.setAccountId(accountId);
            account.setKsId(ksId);
            KuaishouLiveUserAccount one = kuaishouLiveUserAccountMapper.getOne(account);
            if ("saleLeader".equals(role)) {
                one.setSaleLeader("");
                one.setSaleLeaderId("");
            }
            if ("operatorLeader".equals(role)) {
                one.setOperatorLeader("");
                one.setOperatorLeaderId("");
            }
            if ("designerLeader".equals(role)) {
                one.setDesignerLeader("");
                one.setDesignerLeaderId("");
            }
            kuaishouLiveUserAccountMapper.updateKuaishouLiveUserAccount(one);
        }
        return ResultResponse.success();
    }

}
