package com.gic.haoban.manage.service.service.out.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.ToolUtil;
import com.gic.haoban.manage.api.dto.OpenStaffDTO;
import com.gic.haoban.manage.api.dto.OpenStaffImportDTO;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.qdto.OpenStaffInitQDTO;
import com.gic.haoban.manage.api.service.OpenStaffApiService;
import com.gic.haoban.manage.api.service.OpenStaffImportTaskApiService;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
import com.gic.haoban.manage.service.dao.mapper.OpenStaffMapper;
import com.gic.haoban.manage.service.entity.TabOpenStaff;
import com.google.common.collect.Lists;
import com.task.allocation.dto.AuthDTO;
import com.task.allocation.exception.TaskAllocationException;
import com.task.allocation.operation.AbstractTaskCenterManageOperation;
import com.task.allocation.qo.TaskAllocationComputed;
import com.task.allocation.qo.TaskCenterInitTaskQo;
import com.task.allocation.qo.TaskFailInfoQo;
import com.task.allocation.util.TaskAllocationSdkClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("openStaffImportTaskApiService")
public class OpenStaffImportTaskApiServiceImpl extends AbstractTaskCenterManageOperation<OpenStaffImportDTO>  implements OpenStaffImportTaskApiService {

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

    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService;
    @Autowired
    private OpenStaffApiService openStaffApiService;
    @Autowired
    private OpenStaffMapper openStaffMapper;
    @Autowired
    private ClerkService clerkService ;

    // openStaffImportTaskMQ
    @Override
    public ServiceResponse<Void> callBack(String params) {
        log.info("批量导入托管账号callback", params);
        super.run(params);
        return ServiceResponse.success();
    }

    @Override
    public List<OpenStaffImportDTO> getListTasks(String params) {
        OpenStaffImportDTO dto = JSON.parseObject(params, OpenStaffImportDTO.class);
        List<OpenStaffImportDTO> tasks = Lists.partition(dto.getClerkCodeList(), 1)
                .stream()
                .map(item -> {
                    OpenStaffImportDTO sub = new OpenStaffImportDTO();
                    sub.setWxEnterpriseId(dto.getWxEnterpriseId());
                    sub.setEnterpriseId(dto.getEnterpriseId());
                    sub.setLoginClerkId(dto.getLoginClerkId());
                    sub.setClerkCode(item.get(0));
                    return sub;
                }).collect(Collectors.toList());
        log.info("导入托管总任务数 {}", tasks.size());
        return tasks;
    }

    @Override
    public TaskFailInfoQo dealSingle(OpenStaffImportDTO obj) throws TaskAllocationException {
        log.info("导入托管dealSingle={}",JSONObject.toJSONString(obj));
        String wxEnterpriseId = obj.getWxEnterpriseId();
        String enterpriseId = obj.getEnterpriseId() ;
        String clerkCode = obj.getClerkCode() ;
        ClerkDTO clerk = this.clerkService.getClerkByClerkCode(enterpriseId,clerkCode) ;
        if(null == clerk) {
            return fail().setColumns("导购code","失败说明")
                    .addValues(clerkCode,"该账号在当前企业下不存在");
        }
        String clerkId = clerk.getClerkId() ;
        StaffClerkRelationDTO staffClerkRelationDTO = this.staffClerkRelationApiService.getByClerkId(clerkId) ;
        if(null == staffClerkRelationDTO) {
            return fail().setColumns("导购code","失败原因")
                    .addValues(clerkCode,"该账号未绑定好办小程序");
        }
        String staffId = staffClerkRelationDTO.getStaffId() ;
        TabOpenStaff openStaff = this.openStaffMapper.getByStaffId(staffId) ;
        if(null != openStaff) {
            return fail().setColumns("导购code","失败说明")
                    .addValues(clerkCode,"导购账号已授权");
        }
        OpenStaffInitQDTO init = new OpenStaffInitQDTO() ;
        init.setWxEnterpriseId(wxEnterpriseId);
        init.setEnterpriseId(enterpriseId);
        init.setStaffId(staffId);
        init.setImportFlag(1);
        ServiceResponse<OpenStaffDTO> resp = this.openStaffApiService.init(init) ;
        if(!resp.isSuccess()) {
            return fail().setColumns("导购code","失败说明")
                    .addValues(clerkCode,resp.getMessage());
        }
        return success();
    }

    @Override
    public void computed(TaskAllocationComputed computed) {
        log.info("导入托管完成={}", JSONObject.toJSONString(computed));
    }

    @Override
    public OpenStaffImportDTO singleClass() {
        return new OpenStaffImportDTO();
    }

    @Override
    public ServiceResponse<String> createTask(OpenStaffImportDTO dto) {
        TaskCenterInitTaskQo initTaskQo = new TaskCenterInitTaskQo();
        String uuid = ToolUtil.randomUUID();
        initTaskQo.setParams(JSONObject.toJSONString(dto));
        initTaskQo.setBusinessParams(uuid);
        initTaskQo.setTaskCategoryCode("openStaffImportTask");
        initTaskQo.setTaskType(1);
        AuthDTO user = new AuthDTO();
        user.setUserId(dto.getLoginClerkId()) ;
        user.setEnterpriseId(dto.getEnterpriseId()) ;
        user.setLoginName(dto.getLoginName());
        user.setRealName(dto.getRealName()) ;
        initTaskQo.setLoginUser(user);
        initTaskQo.setTaskModelName("好办企微托管");
        initTaskQo.setTaskName("导入托管账号");
        initTaskQo.setTaskContent("批量导入托管账号" + dto.getClerkCodeList().size() + "个");
        initTaskQo.setSourceUrl(dto.getSourceUrl());
        try {
            TaskAllocationSdkClient instance = TaskAllocationSdkClient.getInstance();
            String taskId = instance.initTask(initTaskQo);
            return ServiceResponse.success(taskId);
        } catch (Exception e) {
            log.info("批量导入托管账号dto任务异常", e);
        }
        return ServiceResponse.failure("9999", "创建任务异常");
    }
}
