package com.yh.saas.plugin.servicer.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.alipay.sofa.runtime.api.annotation.SofaService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.winsea.svc.base.base.entity.CommonCity;
import com.winsea.svc.base.base.entity.CommonCompany;
import com.winsea.svc.base.base.entity.CommonParameterCompany;
import com.winsea.svc.base.base.entity.CommonRoleResource;
import com.winsea.svc.base.base.service.ICommonCityService;
import com.winsea.svc.base.base.service.ICommonCompanyService;
import com.winsea.svc.base.base.service.ICommonParameterCompanyService;
import com.winsea.svc.base.base.service.ICommonRoleResourceService;
import com.winsea.svc.base.base.util.page.PageView;
import com.winsea.svc.base.security.entity.User;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.winsea.svc.base.workflow.entity.WorkflowHistoricTask;
import com.winsea.svc.notice.entity.base.BaseNotice;
import com.winsea.svc.notice.service.INoticeService;
import com.yh.saas.common.support.lock.DistributedLock;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.servicer.constant.ServicerFeatureConstant;
import com.yh.saas.plugin.servicer.constant.ServicerVariable;
import com.yh.saas.plugin.servicer.constant.ServicerWorkFlow;
import com.yh.saas.plugin.servicer.entity.ServicerMerchantBankInfo;
import com.yh.saas.plugin.servicer.entity.ServicerMerchantContactsInfo;
import com.yh.saas.plugin.servicer.entity.ServicerMerchantInfo;
import com.yh.saas.plugin.servicer.entity.view.ServicerView;
import com.yh.saas.plugin.servicer.enums.ServicerStatusEnum;
import com.yh.saas.plugin.servicer.exception.ServicerException;
import com.yh.saas.plugin.servicer.exception.ServicerExceptionEnum;
import com.yh.saas.plugin.servicer.mapper.ServicerMerchantInfoMapper;
import com.yh.saas.plugin.servicer.service.IServicerBillOperateHisService;
import com.yh.saas.plugin.servicer.service.IServicerMerchantBankInfoService;
import com.yh.saas.plugin.servicer.service.IServicerMerchantContactsInfoService;
import com.yh.saas.plugin.servicer.service.IServicerMerchantInfoService;
import com.yh.saas.plugin.servicer.ws.client.SupplyWebServiceClient;
import com.yh.saas.plugin.supply.servicer.entity.SupplyServicerMerchantBankInfo;
import com.yh.saas.plugin.supply.servicer.entity.SupplyServicerMerchantContactsInfo;
import com.yh.saas.plugin.supply.servicer.entity.SupplyServicerMerchantInfo;
import com.yh.saas.plugin.supply.servicer.service.ISupplyServicerMerchantBankInfoService;
import com.yh.saas.plugin.supply.servicer.service.ISupplyServicerMerchantContactsInfoService;
import com.yh.saas.plugin.supply.servicer.service.ISupplyServicerMerchantInfoService;
import com.yh.saas.toolkit.workflow.service.IWorkflowHistoryService;
import com.yh.saas.toolkit.workflow.service.IWorkflowService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 记录服务商信息表 服务实现类
 * </p>
 *
 * @author yul
 * @since 2019-11-11
 */
@SofaService
@Slf4j
public class ServicerMerchantInfoServiceImpl extends ServiceImpl<ServicerMerchantInfoMapper, ServicerMerchantInfo>
        implements IServicerMerchantInfoService {

    @Value("${purchase.webservice.address:}")
    public String webServiceUrl;

    @Value("${servicer.register.webservice.address:}")
    public String registerWebServiceUrl;

    @Autowired
    private IWorkflowService workflowService;

    @Autowired
    private IServicerMerchantContactsInfoService merchantContactsInfoService;

    @Autowired
    private IServicerMerchantBankInfoService merchantBankInfoService;

    @SofaReference
    private ICommonCityService commonCityService;

    @SofaReference
    private ICommonCompanyService commonCompanyService;

    @SofaReference
    private ICommonParameterCompanyService commonParameterCompanyService;

    @Autowired
    private IServicerBillOperateHisService billOperateHisService;

    @SofaReference
    private ICommonRoleResourceService roleResourceService;

    @Autowired
    private IWorkflowHistoryService workflowHistoryService;

    @SofaReference
    private ISupplyServicerMerchantInfoService supplyServicerMerchantInfoService;

    @SofaReference
    private ISupplyServicerMerchantContactsInfoService supplyServicerMerchantContactsInfoService;

    @SofaReference
    private ISupplyServicerMerchantBankInfoService supplyServicerMerchantBankInfoService;

    @SofaReference
    private INoticeService noticeService;

    @Override
    public Page<ServicerMerchantInfo> selectPageByCondition(PageView pageView) {

        // 状态类型（0：全部，1：待处理，2：待跟踪）
        String statusType = (String) pageView.get("statusType");
        User currentUser = AuthSecurityUtils.getCurrentUserInfo();
        pageView.put("startRecord", (Integer.parseInt((String) pageView.get("currentPage")) - 1)
                * Integer.parseInt((String) pageView.get("pageSize")));
        // 公司ID
        pageView.put("compId", AuthSecurityUtils.getCurrentUserInfo().getCompId());
        // 操作人ID
        pageView.put("staffId", currentUser.getUserId());
        // 排序设置
        if (StringUtils.isNotBlank(pageView.getOrderColunm())) {
            pageView.put("orderColumn", pageView.getOrderColunm());
            pageView.put("order", pageView.getOrder());
        }

        List<String> businessKeys = new ArrayList<>();
        // 获取待处理的服务商id列表
        if (StringUtils.equals("1", statusType)) {// 待处理
            businessKeys = workflowService.getTaskBusinessKeysByCode(ServicerWorkFlow.SERVICER_MERCHANT_ADD);
            // 权限集合
            List<String> resourceIdList = roleResourceService.getBindResourcesByUserId(currentUser.getUserId()).stream()
                    .map(CommonRoleResource::getResourceId).collect(Collectors.toList());
            pageView.put("statusList", this.getQueryStatusList(resourceIdList));
        } else if (StringUtils.equals("2", statusType)) {// 待跟踪
            businessKeys = workflowService.getDoneTaskBusinessKeysByCode(ServicerWorkFlow.SERVICER_MERCHANT_ADD);
        }
        pageView.put("businessKeys", businessKeys);

        // 不是服务商一览页 写死查非黑名单的
        if (!"1".equals(pageView.get("pageFlag"))) {
            pageView.put("blackFlag", "0");
        }
        // 查询服务商总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<ServicerMerchantInfo> dataList = null;
        List<String> idList = null;
        if (dataCount != null && dataCount > 0) {
            // 查询服务商id分页列表
            idList = baseMapper.getPageListByCondition(pageView);
        }

        // 根据服务商id分页列表获取服务商信息列表
        if (CollectionUtils.isNotEmpty(idList)) {
            Map<String, Object> sCondition = new HashMap<String, Object>();
            sCondition.put("compId", AuthSecurityUtils.getCurrentUserInfo().getCompId());
            sCondition.put("servicerIdList", idList);
            sCondition.put("currentPage", pageView.get("currentPage"));
            sCondition.put("pageSize", pageView.get("pageSize"));
            sCondition.put("startRecord", (Integer.parseInt((String) sCondition.get("currentPage")) - 1)
                    * Integer.parseInt((String) sCondition.get("pageSize")));

            // 排序设置
            if (StringUtils.isNotBlank(pageView.getOrderColunm())) {
                sCondition.put("orderColumn", pageView.getOrderColunm());
                sCondition.put("order", pageView.getOrder());

                // 服务商排序
                if ("service_type".equals((String) sCondition.get("orderColumn"))) {
                    Wrapper<CommonParameterCompany> wapperCommonParameter = new EntityWrapper<>();
                    wapperCommonParameter.eq(CommonParameterCompany.QueryFields.COMP_ID,
                            AuthSecurityUtils.getCurrentUserInfo().getCompId());
                    wapperCommonParameter.eq(CommonParameterCompany.QueryFields.CONST_CODE, "SERVICER_SERVICE_TYPE");
                    wapperCommonParameter.eq("delete_flag", ServicerVariable.DELETEFLAG_0);
                    List<CommonParameterCompany> commonParameterList = commonParameterCompanyService
                            .selectList(wapperCommonParameter);
                    if (CollectionUtils.isNotEmpty(commonParameterList)) {
                        sCondition.put("orderColumnServiceTypeIds",
                                commonParameterList.stream().map(CommonParameterCompany::getParameterKey)
                                        .filter(detail -> StringUtils.isNotBlank(detail)).collect(Collectors.toList()));
                    }
                }
            }
            // 不是服务商一览页 写死查非黑名单的
            if (!"1".equals(pageView.get("pageFlag"))) {
                sCondition.put("blackFlag", "0");
            }
            dataList = baseMapper.getListByCondition(sCondition);
        }

        Page<ServicerMerchantInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(pageView.getCurrentPage());
        page.setSize(pageView.getPageSize());

        return page;
    }

    @Override
    public List<ServicerMerchantInfo> selectListByCondition(Map<String, Object> params) {
        Map<String, Object> sCondition = new HashMap<String, Object>();
        sCondition.putAll(params);
        sCondition.put("compId", AuthSecurityUtils.getCurrentUserInfo().getCompId());

        // 排序设置
        String orderColumn = params.get("orderColumn") == null ? "" : params.get("orderColumn").toString();
        if (StringUtils.isNotEmpty(orderColumn)) {
            // 服务商排序
            if ("service_type".equals(orderColumn)) {
                Wrapper<CommonParameterCompany> wapperCommonParameter = new EntityWrapper<>();
                wapperCommonParameter.eq(CommonParameterCompany.QueryFields.COMP_ID,
                        AuthSecurityUtils.getCurrentUserInfo().getCompId());
                wapperCommonParameter.eq(CommonParameterCompany.QueryFields.CONST_CODE, "SERVICER_SERVICE_TYPE");
                wapperCommonParameter.eq("delete_flag", ServicerVariable.DELETEFLAG_0);
                List<CommonParameterCompany> commonParameterList = commonParameterCompanyService
                        .selectList(wapperCommonParameter);
                if (CollectionUtils.isNotEmpty(commonParameterList)) {
                    sCondition.put("orderColumnServiceTypeIds",
                            commonParameterList.stream().map(CommonParameterCompany::getParameterKey)
                                    .filter(detail -> StringUtils.isNotBlank(detail)).collect(Collectors.toList()));
                }
            }
        }

        // 只查不在黑名单中的服务商
        sCondition.put("blackFlag", "0");
        List<ServicerMerchantInfo> dataList = baseMapper.getListByCondition(sCondition);
        return dataList;
    }

    @Override
    public List<Map<String, Object>> selectBankListByCondition(Map<String, Object> params) {
        Map<String, Object> sCondition = new HashMap<String, Object>();
        sCondition.putAll(params);
        sCondition.put("compId", AuthSecurityUtils.getCurrentUserInfo().getCompId());

        // 只查不在黑名单中的服务商
        sCondition.put("blackFlag", "0");
        List<ServicerMerchantInfo> results = baseMapper.getBankListByCondition(sCondition);
        List<Map<String, Object>> dataList = null;
        if (CollectionUtils.isNotEmpty(results)) {
            dataList = new ArrayList<Map<String, Object>>();
            for (ServicerMerchantInfo mInfo : results) {
                JSONObject merchantInfo = new JSONObject();
                merchantInfo.put("servicerId", mInfo.getServicerId());
                merchantInfo.put("compId", mInfo.getCompId());
                merchantInfo.put("servicerName", mInfo.getServicerName());
                merchantInfo.put("servicerEnName", mInfo.getServicerEnName());

                JSONArray bankList = new JSONArray();
                merchantInfo.put("bankList", bankList);
                if (CollectionUtils.isNotEmpty(mInfo.getBankList())) {
                    for (ServicerMerchantBankInfo bInfo : mInfo.getBankList()) {
                        JSONObject bank = new JSONObject();
                        bank.put("bankId", bInfo.getBankId());
                        bank.put("payeeName", bInfo.getPayeeName());
                        bank.put("payeeSwft", bInfo.getPayeeSwft());
                        bank.put("payeeAddress", bInfo.getPayeeAddress());
                        bank.put("receiveBankAccount", bInfo.getReceiveBankAccount());
                        bank.put("receiveBankName", bInfo.getReceiveBankName());
                        bank.put("receiveBankAddress", bInfo.getReceiveBankAddress());
                        // 开户行国籍key
                        bank.put("nationalityKey", bInfo.getNationalityKey());
                        bank.put("nationalityValue", bInfo.getNationalityValue());
                        bank.put("nationalityEnValue", bInfo.getNationalityEnValue());
                        bankList.add(bank);
                    }
                }
                dataList.add(merchantInfo);
            }
        }
        return dataList;
    }

    @SuppressWarnings("deprecation")
    @Transactional
    @Override
    @DistributedLock(keys = "'servicer-merchant-info-' + #merchantInfoView.getMerchantInfo().getCompId() + '-action-create'")
    public String saveServicerMerchant(ServicerView<ServicerMerchantInfo> merchantInfoView) {
        boolean insertFlag = false;
        boolean saveRegisteredFlag = true;
        ServicerMerchantInfo merchantInfo = merchantInfoView.getMerchantInfo();
        String servicerId = merchantInfo.getServicerId();
        ServicerMerchantInfo newmerchantInfo = null;
        if (StringUtils.isBlank(servicerId)) {
            servicerId = IdGenerator.generateUUID();
            merchantInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
            // 保存校验（新增）
            checkSave(merchantInfo, ServicerVariable.OPER_MODEL_ADD);

            merchantInfo.setServicerId(servicerId);
            // 设置服务商状态，默认：待提交
            merchantInfo.setStatusFlag(ServicerStatusEnum.WAIT_SUBMIT.getFlag());
            merchantInfo.setStatusName(ServicerStatusEnum.WAIT_SUBMIT.getName());
            merchantInfo.setStatusEnName(ServicerStatusEnum.WAIT_SUBMIT.getNameEn());
            // 设置启用状态，默认不启用
            merchantInfo.setEnabled(Integer.valueOf(ServicerStatusEnum.NOT_ENABLED.getFlag()));
            insertFlag = true;
        } else {
            newmerchantInfo = this.selectById(servicerId);
            // 保存校验（编辑）
            checkSave(merchantInfo, ServicerVariable.OPER_MODEL_EDIT);
            merchantInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
            ServicerMerchantInfo newServicerMerchantInfo = this.selectById(servicerId);
            if (null != merchantInfo && CollectionUtils.isNotEmpty(merchantInfo.getContactsList())
                    && null != merchantInfo.getContactsList().get(0)) {
                if (StringUtils.isNotEmpty(merchantInfo.getContactsList().get(0).getMobileNumber())) {
                    // 查询联系人列表
                    Wrapper<ServicerMerchantContactsInfo> wapperContacts = new EntityWrapper<>();
                    wapperContacts.eq(ServicerMerchantContactsInfo.QueryFields.SERVICER_ID, servicerId);
                    wapperContacts.eq(ServicerMerchantContactsInfo.QueryFields.DELETE_FALG,
                            ServicerVariable.DELETEFLAG_0);
                    List<ServicerMerchantContactsInfo> contactsList = merchantContactsInfoService
                            .selectList(wapperContacts);
                    if (null != contactsList && contactsList.size() > 0) {
                        if (merchantInfo.getContactsList().get(0).getMobileNumber()
                                .equals(contactsList.get(0).getOldMobileNumber())) {
                            saveRegisteredFlag = false;
                        }
                    }

                }
            }
            if ("5".equals(newServicerMerchantInfo.getStatusFlag())) {// 判断是否再次编辑
                if (merchantInfoView.getOnlySubmit() == true) {
                    // 设置服务商状态，已提交
                    merchantInfo.setStatusFlag(ServicerStatusEnum.SUBMITED.getFlag());
                    merchantInfo.setStatusName(ServicerStatusEnum.SUBMITED.getName());
                    merchantInfo.setStatusEnName(ServicerStatusEnum.SUBMITED.getNameEn());
                } else {
                    // 设置服务商状态，默认：待提交
                    merchantInfo.setStatusFlag(ServicerStatusEnum.WAIT_SUBMIT.getFlag());
                    merchantInfo.setStatusName(ServicerStatusEnum.WAIT_SUBMIT.getName());
                    merchantInfo.setStatusEnName(ServicerStatusEnum.WAIT_SUBMIT.getNameEn());
                }

            }
        }

        // 设置地区全名（根据所选的最小行政级别地区id来查询）
        Integer cityId = null;
        if (merchantInfo.getCityKey() != null) {
            cityId = merchantInfo.getCityKey();
        } else if (merchantInfo.getProvKey() != null) {
            cityId = merchantInfo.getProvKey();
        }
        if (cityId != null) {
            CommonCity commonCity = commonCityService.getCityById(String.valueOf(cityId));
            if (commonCity != null) {
                merchantInfo.setArea_full_name(commonCity.getQueryCondition());
            }
        }

        boolean isStartWorkflow = false;
        boolean isActivateWorkflow = false;
        String workFlowId = null;
        // 提交操作
        if (merchantInfoView.getOnlySubmit().equals(Boolean.TRUE)) {
//            workFlowId = null != newmerchantInfo ? newmerchantInfo.getCurrentWorkflowId() : null;
            // 如果单据已经存在审核流，仍然始终继续走审核，不管你以后删不删工作流
//            if (StringUtils.isNotEmpty(workFlowId)) {
//                merchantInfo.setStatusFlag(ServicerStatusEnum.SUBMITED.getFlag());
//                merchantInfo.setStatusName(ServicerStatusEnum.SUBMITED.getName());
//                merchantInfo.setStatusEnName(ServicerStatusEnum.SUBMITED.getNameEn());
//                // 激活审核流
//                isActivateWorkflow = true;
//            } else {// 如果不存在，则要先判断是否配置了审核流
//                Workflow workflow = workflowService
//                        .findLatestWorkflowByBusinessCode(ServicerWorkFlow.SERVICER_MERCHANT_ADD);
//                // 如果没配置审核流，单据就直接完成
//                if (workflow == null) {
                    // 清空审核流ID
                    workFlowId = null;
                    merchantInfo.setWorkFlowId(workFlowId);
                    merchantInfo.setSpareWorkFlowId(workFlowId);
                    // 设置状态
                    merchantInfo.setStatusFlag(ServicerStatusEnum.COMPLETED.getFlag());
                    merchantInfo.setStatusName(ServicerStatusEnum.COMPLETED.getName());
                    merchantInfo.setStatusEnName(ServicerStatusEnum.COMPLETED.getNameEn());
                    merchantInfo.setPassFlag(1);
//                } else {// 否则，就走审核流
//                    workFlowId = workflow.getId();
//                    merchantInfo.setWorkFlowId(workFlowId);
//                    merchantInfo.setSpareWorkFlowId(workFlowId);
//                    // 设置状态
//                    merchantInfo.setStatusFlag(ServicerStatusEnum.SUBMITED.getFlag());
//                    merchantInfo.setStatusName(ServicerStatusEnum.SUBMITED.getName());
//                    merchantInfo.setStatusEnName(ServicerStatusEnum.SUBMITED.getNameEn());
//                    // 开启审核流
//                    isStartWorkflow = true;
//                }
//            }
        }

        // TODO:提交时注册供应平台账号（当从未注册过，或已注册的账号不在当前联系人手机列表中，说白了，就是必须保证注册账号匹配上手机号中的某个）
        if (Boolean.TRUE.equals(merchantInfoView.getOnlySubmit()) && Boolean.TRUE == saveRegisteredFlag) {
            if (insertFlag) {
                //不在此处调用供应商信息
//                this.registerServicerByWebService(merchantInfo);
            } else {
                // 查询服务商信息
                ServicerMerchantInfo merchantInfoEd = baseMapper.selectById(servicerId);
                if (merchantInfoEd != null) {
                    String servicerAccount = merchantInfoEd.getServicerAccount();
                    if (StringUtils.isEmpty(servicerAccount)) {
                        this.registerServicerByWebService(merchantInfo);
                    } else {
                        List<String> equalList = merchantInfo.getContactsList().stream()
                                .map(ServicerMerchantContactsInfo::getMobileNumber)
                                .filter(detail -> StringUtils.equals(servicerAccount, detail))
                                .collect(Collectors.toList());
                        if (CollectionUtils.isEmpty(equalList)) {
                            this.registerServicerByWebService(merchantInfo);
                        }
                    }
                }
            }
        }

        if (insertFlag) {
            this.saveAddMerchantInfo(merchantInfoView);
        } else {
            this.saveEditMerchantInfo(merchantInfoView, merchantInfoView.getOnlySubmit());
        }

        if (!merchantInfoView.getOnlySubmit().equals(Boolean.TRUE)) {
            if (StringUtils.isNotEmpty(servicerId)) {
                ServicerMerchantInfo ma = baseMapper.selectById(servicerId);
                ma.setWorkFlowId(null);
                this.updateAllColumnById(ma);

                SupplyServicerMerchantInfo supplyServicerMerchantInfo = new SupplyServicerMerchantInfo();
                BeanUtils.copyProperties(ma, supplyServicerMerchantInfo);
                supplyServicerMerchantInfoService.updateAllColumnById(supplyServicerMerchantInfo);
            }

        }

        // 开启工作流
//        if (isStartWorkflow) {
//            boolean approved = true;
//            List<WorkflowHistoricTask> historicTasks = this.workflowHistoryService.getInstanceHistories(workFlowId,
//                    servicerId);
//            Collections.sort(historicTasks, Comparator.comparing(WorkflowHistoricTask::getCreateTime).reversed());
//            if (CollectionUtils.isNotEmpty(historicTasks)) {
//                if (!historicTasks.get(0).getApproved()) {
//                    approved = false;
//                }
//            }
//            if (approved) {
//                workflowService.startInstance(workFlowId, servicerId);
//            } else {
//                workflowService.activateInstance(workFlowId, servicerId);
//            }
//
//        } else if (isActivateWorkflow) {// 激活工作流
//            workflowService.activateInstance(workFlowId, servicerId);
//        }

        return merchantInfo.getServicerId();
    }

    @Transactional
    @Override
    public void approveServicerMerchant(ServicerView<ServicerMerchantInfo> merchantInfoView) {
        String isApprove = merchantInfoView.getIsApprove();
        String auditMind = merchantInfoView.getAuditMind();
        ServicerMerchantInfo merchantInfo = baseMapper.selectById(merchantInfoView.getMerchantInfo().getServicerId());
        List<String> workflowIds = Lists.newArrayList(merchantInfo.getWorkFlowId());
        String taskId = workflowService.getActiveTask(workflowIds, merchantInfo.getServicerId())
                .getString(ServicerVariable.TASKID);
        if (taskId == null) {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_MERCHANT_ADD_WORKFLOW_ERROR);
        }

        // 审核通过
        /**
         * taskId:任务ID,approved:是否通过(1通过，0驳回),auditMind:审核意见
         */
        if (StringUtils.equals(ServicerVariable.APPROVE_PASS, isApprove)) {
            // 通过
            // 工作流方法中自动在任务监听调用任务Listener调用handleStatusChanged()处理业务;
            workflowService.handle(taskId, true, auditMind, false);
        } else {
            // 驳回
            // 工作流方法中自动在任务监听调用任务Listener调用handleRejectApplicationRepulsed()处理业务;
            workflowService.handle(taskId, false, auditMind, true);
        }
    }

    @Transactional
    @Override
    public void deleteMerchantById(ServicerMerchantInfo merchantInfo) {
        String servicerId = merchantInfo.getServicerId();
        if (StringUtils.isEmpty(servicerId)) {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_CREATE_ERROR);
        }

        // 删除联系人信息
        Wrapper<ServicerMerchantContactsInfo> wapperContacts = new EntityWrapper<>();
        wapperContacts.eq(ServicerMerchantContactsInfo.QueryFields.SERVICER_ID, servicerId);
        wapperContacts.eq(ServicerMerchantContactsInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
        merchantContactsInfoService.delete(wapperContacts);

//		// 删除联系人信息(同步到采购)
//		Wrapper<SupplyServicerMerchantContactsInfo> wapperSupplyContacts = new EntityWrapper<>();
//		wapperSupplyContacts.eq(SupplyServicerMerchantContactsInfo.QueryFields.SERVICER_ID, servicerId);
//		wapperSupplyContacts.eq(SupplyServicerMerchantContactsInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
//		supplyServicerMerchantContactsInfoService.delete(wapperSupplyContacts);

        // 删除银行账号信息
        Wrapper<ServicerMerchantBankInfo> wapperBank = new EntityWrapper<>();
        wapperBank.eq(ServicerMerchantBankInfo.QueryFields.SERVICER_ID, servicerId);
        wapperBank.eq(ServicerMerchantBankInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
        merchantBankInfoService.delete(wapperBank);

//		// 删除银行账号信息(同步到采购)
//		Wrapper<SupplyServicerMerchantBankInfo> wapperSupplyBank = new EntityWrapper<>();
//		wapperSupplyBank.eq(SupplyServicerMerchantBankInfo.QueryFields.SERVICER_ID, servicerId);
//		wapperSupplyBank.eq(SupplyServicerMerchantBankInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
//		supplyServicerMerchantBankInfoService.delete(wapperSupplyBank);

        // 删除后，如果有工作流的话，要结束工作流
        ServicerMerchantInfo merchant = this.selectById(servicerId);
        if (StringUtils.isNotBlank(merchant.getWorkFlowId())) {
            workflowService.stopInstance(merchant.getWorkFlowId(), merchant.getServicerId(), "已删除");
        }

        // 删除服务商信息
        this.deleteById(servicerId);
        // 同步到采购
        SupplyServicerMerchantInfo supplyServicerMerchantInfo = new SupplyServicerMerchantInfo();
        supplyServicerMerchantInfo.setServicerId(servicerId);
        supplyServicerMerchantInfoService.deleteMerchantById(supplyServicerMerchantInfo);

        // 可能有退回的任务 删除掉
        noticeService.removeNotice(BaseNotice.NoticeStatus.ALL, null, servicerId, null);

        // 插入操作历史
        billOperateHisService.saveBillOperateHis("SERVICER-MERCHANT", merchantInfo.getServicerId(), "服务商信息",
                billOperateHisService.getStaffAndName(), null, "删除", "Delete", "");
    }

    @Override
    public ServicerMerchantInfo selectServicerMerchantInfoById(String servicerId) {
        // 查询服务商信息
        ServicerMerchantInfo merchantInfo = baseMapper.selectById(servicerId);
        if (merchantInfo != null) {
//            if (StringUtils.isNotEmpty(merchantInfo.getSpareWorkFlowId())) {
//                merchantInfo.setWorkFlowId(merchantInfo.getSpareWorkFlowId());
//            }
            // 查询联系人列表
            Wrapper<ServicerMerchantContactsInfo> wapperContacts = new EntityWrapper<>();
            wapperContacts.eq(ServicerMerchantContactsInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            wapperContacts.eq(ServicerMerchantContactsInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            List<ServicerMerchantContactsInfo> contactsList = merchantContactsInfoService.selectList(wapperContacts);
            merchantInfo.setContactsList(contactsList);
            // 查询银行账号列表
            Wrapper<ServicerMerchantBankInfo> wapperBank = new EntityWrapper<>();
            wapperBank.eq(ServicerMerchantBankInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            wapperBank.eq(ServicerMerchantBankInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            List<ServicerMerchantBankInfo> bankList = merchantBankInfoService.selectList(wapperBank);
            merchantInfo.setBankList(bankList);
            String taskId = null;
            // 只有待审核状态才有taskId
            if (StringUtils.equals(ServicerStatusEnum.SUBMITED.getFlag(), merchantInfo.getStatusFlag())) {
                JSONObject jsonObject = workflowService
                        .getActiveTask(Lists.newArrayList(merchantInfo.getCurrentWorkflowId()), servicerId);
                taskId = jsonObject.getString(ServicerVariable.TASKID);
                merchantInfo.setTaskId(taskId);
            }
        }
        return merchantInfo;
    }

    /**
     * 保存校验
     *
     * @param merchantInfo
     * @param operFlag
     */
    private void checkSave(ServicerMerchantInfo merchantInfo, String operFlag) {
        // *** 暂时只做数据/业务层面的校验，而必填，格式等由前台处理 ***
        // 中文/英文名称至少有一项不空
        if (StringUtils.isEmpty(merchantInfo.getServicerName())
                && StringUtils.isEmpty(merchantInfo.getServicerEnName())) {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_NAME_AT_LEAST_ONE);
        }
        // 中文名称存在性校验（公司内唯一）
        if (StringUtils.isNotEmpty(merchantInfo.getServicerName())) {
            Wrapper<ServicerMerchantInfo> wapperMerchant = new EntityWrapper<>();
            wapperMerchant.eq(ServicerMerchantInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            // 忽略已删除的服务商
            wapperMerchant.eq(ServicerMerchantInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperMerchant.eq(ServicerMerchantInfo.QueryFields.SERVICER_NAME, merchantInfo.getServicerName());
            if (operFlag.equals(ServicerVariable.OPER_MODEL_EDIT)) {
                wapperMerchant.ne(ServicerMerchantInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            }
            ServicerMerchantInfo info = this.selectOne(wapperMerchant);
            if (info != null) {
                // 与黑名单中的重复
                if (info.getBlackFlag()) {
                    throw new ServicerException(ServicerExceptionEnum.SERVICER_ZH_NAME_REPEAT_BLACK);
                } else {
                    throw new ServicerException(ServicerExceptionEnum.SERVICER_ZH_NAME_REPEAT);
                }
            }
        }
        // 英文名称存在性校验（公司内唯一）
        if (StringUtils.isNotEmpty(merchantInfo.getServicerEnName())) {
            Wrapper<ServicerMerchantInfo> wapperMerchant = new EntityWrapper<>();
            wapperMerchant.eq(ServicerMerchantInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            // 忽略已删除的服务商
            wapperMerchant.eq(ServicerMerchantInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperMerchant.eq(ServicerMerchantInfo.QueryFields.SERVICER_EN_NAME, merchantInfo.getServicerEnName());
            if (operFlag.equals(ServicerVariable.OPER_MODEL_EDIT)) {
                wapperMerchant.ne(ServicerMerchantInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            }
            ServicerMerchantInfo info = this.selectOne(wapperMerchant);
            if (info != null) {
                // 与黑名单中的重复
                if (info.getBlackFlag()) {
                    throw new ServicerException(ServicerExceptionEnum.SERVICER_EN_NAME_REPEAT_BLACK);
                } else {
                    throw new ServicerException(ServicerExceptionEnum.SERVICER_EN_NAME_REPEAT);
                }
            }
        }

        // 统一社会信用代码不能为空
        if (StringUtils.isEmpty(merchantInfo.getUscc())) {
            // throw new
            // ServicerException(ServicerExceptionEnum.SERVICER_USCC_REQUIRE);
        }
        // 统一社会信用代码存在性校验（公司内唯一）
        if (StringUtils.isNotEmpty(merchantInfo.getUscc())) {
            Wrapper<ServicerMerchantInfo> wapperMerchant = new EntityWrapper<>();
            wapperMerchant.eq(ServicerMerchantInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            // 忽略已删除的服务商
            wapperMerchant.eq(ServicerMerchantInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperMerchant.eq(ServicerMerchantInfo.QueryFields.USCC, merchantInfo.getUscc());
            if (operFlag.equals(ServicerVariable.OPER_MODEL_EDIT)) {
                wapperMerchant.ne(ServicerMerchantInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            }
            int checkCount = this.selectCount(wapperMerchant);
            if (checkCount > 0) {
                throw new ServicerException(ServicerExceptionEnum.SERVICER_USCC_REPEAT);
            }
        }

        // 联系人至少填写一个
        if (CollectionUtils.isEmpty(merchantInfo.getContactsList())) {
            // throw new
            // ServicerException(ServicerExceptionEnum.SERVICER_LINK_MAN_AT_LEAST_ONE);
        }
    }

    /**
     * 新增服务商信息
     *
     * @param merchantInfoView
     * @return
     */
    private void saveAddMerchantInfo(ServicerView<ServicerMerchantInfo> merchantInfoView) {
        ServicerMerchantInfo merchantInfo = merchantInfoView.getMerchantInfo();
        this.insert(merchantInfo);

        SupplyServicerMerchantInfo supplyServicerMerchantInfo = new SupplyServicerMerchantInfo();
        BeanUtils.copyProperties(merchantInfo, supplyServicerMerchantInfo);
//        supplyServicerMerchantInfoService.insert(supplyServicerMerchantInfo);

        // *** 新增联系人信息 ***
        if (CollectionUtils.isNotEmpty(merchantInfo.getContactsList())) {
            for (ServicerMerchantContactsInfo contactsInfo : merchantInfo.getContactsList()) {
                // contactsInfo.setContactsId(IdGenerator.generateUUID());
                contactsInfo.setServicerId(merchantInfo.getServicerId());
                contactsInfo.setCompId(merchantInfo.getCompId());
            }
            merchantContactsInfoService.insertBatch(merchantInfo.getContactsList());
            log.info("---------------------supplyServicerMerchantContactsInfoService-----------" + getCopyServicerMerchantContactsInfoList(merchantInfo.getContactsList()).toString());
            supplyServicerMerchantContactsInfoService.insertBatch(getCopyServicerMerchantContactsInfoList(merchantInfo.getContactsList()));
        }

        // *** 新增银行账户信息 ***
        if (CollectionUtils.isNotEmpty(merchantInfo.getBankList())) {
            for (ServicerMerchantBankInfo bankInfo : merchantInfo.getBankList()) {
                // bankInfo.setBankId(IdGenerator.generateUUID());
                bankInfo.setServicerId(merchantInfo.getServicerId());
                bankInfo.setCompId(merchantInfo.getCompId());
            }
            merchantBankInfoService.insertBatch(merchantInfo.getBankList());
            log.info("---------------------supplyServicerMerchantBankInfoService-----------" + getCopyServicerMerchantBankInfoList(merchantInfo.getBankList()).toString());
            supplyServicerMerchantBankInfoService.insertBatch(getCopyServicerMerchantBankInfoList(merchantInfo.getBankList()));
        }

        // 插入操作历史
        billOperateHisService.saveBillOperateHis("SERVICER-MERCHANT", merchantInfo.getServicerId(), "服务商信息",
                billOperateHisService.getStaffAndName(), null, ServicerStatusEnum.WAIT_SUBMIT.getName(),
                ServicerStatusEnum.WAIT_SUBMIT.getNameEn(), "");
    }

    /**
     * 编辑服务商信息
     *
     * @param merchantInfoView
     * @param merBoolean
     */
    private void saveEditMerchantInfo(ServicerView<ServicerMerchantInfo> merchantInfoView, boolean merBoolean) {
        // 更新服务商信息
        ServicerMerchantInfo merchantInfo = merchantInfoView.getMerchantInfo();
        this.updateById(merchantInfo);

        SupplyServicerMerchantInfo supplyServicerMerchantInfo = new SupplyServicerMerchantInfo();
        BeanUtils.copyProperties(merchantInfo, supplyServicerMerchantInfo);
        supplyServicerMerchantInfoService.updateById(supplyServicerMerchantInfo);

        // 更新联系人信息
        if (CollectionUtils.isNotEmpty(merchantInfo.getContactsList())) {
            for (ServicerMerchantContactsInfo contactsInfo : merchantInfo.getContactsList()) {
                if (StringUtils.isEmpty(contactsInfo.getContactsId())) {
                    // contactsInfo.setContactsId(IdGenerator.generateUUID());
                }
            }

            merchantInfo.getContactsList().stream().forEach(contacts -> {
                contacts.setServicerId(merchantInfo.getServicerId()).setCompId(merchantInfo.getCompId())
                        .setDeleteFlag(ServicerVariable.DELETEFLAG_0);
            });
            // 先删后插（or更新）
            Wrapper<ServicerMerchantContactsInfo> wapperContactsDel = new EntityWrapper<>();
            wapperContactsDel.eq(ServicerMerchantContactsInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            wapperContactsDel.eq(ServicerMerchantContactsInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            wapperContactsDel.eq(ServicerMerchantContactsInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperContactsDel.notIn(ServicerMerchantContactsInfo.QueryFields.CONTACTS_ID,
                    merchantInfo.getContactsList().stream().map(ServicerMerchantContactsInfo::getContactsId)
                            .filter(detail -> StringUtils.isNotBlank(detail)).collect(Collectors.toList()));
            merchantContactsInfoService.delete(wapperContactsDel);

            // 先删后插（or更新）
            Wrapper<SupplyServicerMerchantContactsInfo> wapperContactsDe2 = new EntityWrapper<>();
            wapperContactsDe2.eq(SupplyServicerMerchantContactsInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            wapperContactsDe2.eq(SupplyServicerMerchantContactsInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            wapperContactsDe2.eq(SupplyServicerMerchantContactsInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperContactsDe2.notIn(SupplyServicerMerchantContactsInfo.QueryFields.CONTACTS_ID,
                    merchantInfo.getContactsList().stream().map(ServicerMerchantContactsInfo::getContactsId)
                            .filter(detail -> StringUtils.isNotBlank(detail)).collect(Collectors.toList()));
            supplyServicerMerchantContactsInfoService.delete(wapperContactsDe2);


            merchantInfo.getContactsList().forEach(contacts -> {
                if (merBoolean) {
                    contacts.setOldMobileNumber(contacts.getMobileNumber());
                }
            });

            supplyServicerMerchantContactsInfoService.insertOrUpdateBatch(getCopyServicerMerchantContactsInfoList(merchantInfo.getContactsList()));
            merchantContactsInfoService.insertOrUpdateBatch(merchantInfo.getContactsList());

        } else {
            // 先删后插（or更新）
            Wrapper<ServicerMerchantContactsInfo> wapperContactsDel = new EntityWrapper<>();
            wapperContactsDel.eq(ServicerMerchantContactsInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            wapperContactsDel.eq(ServicerMerchantContactsInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            wapperContactsDel.eq(ServicerMerchantContactsInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperContactsDel.notIn(ServicerMerchantContactsInfo.QueryFields.CONTACTS_ID,
                    merchantInfo.getContactsList().stream().map(ServicerMerchantContactsInfo::getContactsId)
                            .filter(detail -> StringUtils.isNotBlank(detail)).collect(Collectors.toList()));
            merchantContactsInfoService.delete(wapperContactsDel);

            // 先删后插（or更新）
            Wrapper<SupplyServicerMerchantContactsInfo> wapperContactsDe2 = new EntityWrapper<>();
            wapperContactsDe2.eq(SupplyServicerMerchantContactsInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            wapperContactsDe2.eq(SupplyServicerMerchantContactsInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            wapperContactsDe2.eq(SupplyServicerMerchantContactsInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperContactsDe2.notIn(SupplyServicerMerchantContactsInfo.QueryFields.CONTACTS_ID,
                    merchantInfo.getContactsList().stream().map(ServicerMerchantContactsInfo::getContactsId)
                            .filter(detail -> StringUtils.isNotBlank(detail)).collect(Collectors.toList()));
            supplyServicerMerchantContactsInfoService.delete(wapperContactsDe2);
        }
        // 更新银行账号信息
        if (CollectionUtils.isNotEmpty(merchantInfo.getBankList())) {
            for (ServicerMerchantBankInfo bankInfo : merchantInfo.getBankList()) {
                if (StringUtils.isEmpty(bankInfo.getBankId())) {
                    // bankInfo.setBankId(IdGenerator.generateUUID());
                }
            }

            merchantInfo.getBankList().stream().forEach(bank -> {
                bank.setServicerId(merchantInfo.getServicerId()).setCompId(merchantInfo.getCompId())
                        .setDeleteFlag(ServicerVariable.DELETEFLAG_0);
            });
            // 先删后插（or更新）
            Wrapper<ServicerMerchantBankInfo> wapperBankDel = new EntityWrapper<>();
            wapperBankDel.eq(ServicerMerchantBankInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            wapperBankDel.eq(ServicerMerchantBankInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            wapperBankDel.eq(ServicerMerchantBankInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperBankDel.notIn(ServicerMerchantBankInfo.QueryFields.BANK_ID,
                    merchantInfo.getBankList().stream().map(ServicerMerchantBankInfo::getBankId)
                            .filter(detail -> StringUtils.isNotBlank(detail)).collect(Collectors.toList()));
            merchantBankInfoService.delete(wapperBankDel);

            // 先删后插（or更新）
            Wrapper<SupplyServicerMerchantBankInfo> wapperBankDe2 = new EntityWrapper<>();
            wapperBankDe2.eq(SupplyServicerMerchantBankInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            wapperBankDe2.eq(SupplyServicerMerchantBankInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            wapperBankDe2.eq(SupplyServicerMerchantBankInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperBankDe2.notIn(SupplyServicerMerchantBankInfo.QueryFields.BANK_ID,
                    merchantInfo.getBankList().stream().map(ServicerMerchantBankInfo::getBankId)
                            .filter(detail -> StringUtils.isNotBlank(detail)).collect(Collectors.toList()));
            supplyServicerMerchantBankInfoService.delete(wapperBankDe2);


            supplyServicerMerchantBankInfoService.insertOrUpdateBatch(getCopyServicerMerchantBankInfoList(merchantInfo.getBankList()));
            merchantBankInfoService.insertOrUpdateBatch(merchantInfo.getBankList());
        } else {
            // 先删后插（or更新）
            Wrapper<ServicerMerchantBankInfo> wapperBankDel = new EntityWrapper<>();
            wapperBankDel.eq(ServicerMerchantBankInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            wapperBankDel.eq(ServicerMerchantBankInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            wapperBankDel.eq(ServicerMerchantBankInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperBankDel.notIn(ServicerMerchantBankInfo.QueryFields.BANK_ID,
                    merchantInfo.getBankList().stream().map(ServicerMerchantBankInfo::getBankId)
                            .filter(detail -> StringUtils.isNotBlank(detail)).collect(Collectors.toList()));
            merchantBankInfoService.delete(wapperBankDel);

            // 先删后插（or更新）
            Wrapper<SupplyServicerMerchantBankInfo> wapperBankDe2 = new EntityWrapper<>();
            wapperBankDe2.eq(SupplyServicerMerchantBankInfo.QueryFields.COMP_ID, merchantInfo.getCompId());
            wapperBankDe2.eq(SupplyServicerMerchantBankInfo.QueryFields.SERVICER_ID, merchantInfo.getServicerId());
            wapperBankDe2.eq(SupplyServicerMerchantBankInfo.QueryFields.DELETE_FALG, ServicerVariable.DELETEFLAG_0);
            wapperBankDe2.notIn(SupplyServicerMerchantBankInfo.QueryFields.BANK_ID,
                    merchantInfo.getBankList().stream().map(ServicerMerchantBankInfo::getBankId)
                            .filter(detail -> StringUtils.isNotBlank(detail)).collect(Collectors.toList()));
            supplyServicerMerchantBankInfoService.delete(wapperBankDe2);
        }
        ServicerMerchantInfo servicerMerchantInfo = this.selectById(merchantInfo.getServicerId());
        if (null != servicerMerchantInfo.getPassFlag() && 1 == servicerMerchantInfo.getPassFlag()) {
            // 插入操作历史
            billOperateHisService.saveBillOperateHis("SERVICER-MERCHANT", merchantInfo.getServicerId(), "服务商信息",
                    billOperateHisService.getStaffAndName(), null, ServicerStatusEnum.WAIT_SUBMIT.getName(),
                    ServicerStatusEnum.WAIT_SUBMIT.getNameEn(), "");
        }

    }

    /**
     * 注册供应商账号（供应、油品、修船模块自己启用供应商时使用）
     *
     * @param merchantInfo
     * @return
     */
    private String registerServicerByWebService(ServicerMerchantInfo merchantInfo) throws ServicerException {
        // 不提供联系人的话，也不强制注册供应平台账号了
        if (merchantInfo == null || CollectionUtils.isEmpty(merchantInfo.getContactsList())) {
            return null;
        }
        if (registerWebServiceUrl.contains("121.199.3.172")) {// 生产环境
            return this.registerServicerByWebServiceForProd(merchantInfo);
        } else if (registerWebServiceUrl.contains("114.115.215.70") || registerWebServiceUrl.contains("localhost")
                || registerWebServiceUrl.contains("127.0.0.1")) {// 测试环境
            return this.registerServicerByWebServiceForTest(merchantInfo);
        } else {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR);
        }
    }

    private String registerServicerByWebServiceForProd(ServicerMerchantInfo merchantInfo) throws ServicerException {
        // 提示：注册供应平台账号，默认第一个联系人的手机号（估计以后得用统一社会信用代码作为登录id，或者是系统自动分配一个账号，强烈不建议用手机号）
        String vendorIdSupply = "";
        // 第一个联系人信息
        ServicerMerchantContactsInfo contactsInfo = null;
        // 联系人手机号（登录账号）
        String mobileNumber = null;
        // 服务商名称
        String servicerName = null;
        // 服务商联系人
        String linkman = null;
        List<ServicerMerchantContactsInfo> contactsList = merchantInfo.getContactsList();
        if (CollectionUtils.isNotEmpty(contactsList)) {
            contactsInfo = contactsList.get(0);
        } else {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR3);
        }
        mobileNumber = contactsInfo.getMobileNumber();
        linkman = contactsInfo.getLinkMan();
        if (StringUtils.isEmpty(mobileNumber) || StringUtils.isEmpty(linkman)) {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR3);
        }
        // TODO:验证供应商手机号是否在报价平台注册，如果已注册，则返回注册的公司信息，如果没注册，则返回空
        try {
            Object[] registerVendors = SupplyWebServiceClient.getData(registerWebServiceUrl, "validateVendorRegister",
                    mobileNumber);
            if (registerVendors != null && registerVendors.length > 0 && registerVendors[0] != null
                    && !"null".equalsIgnoreCase(registerVendors[0].toString())) {
                // 返回的是json格式的字符串
                String companyInfo = registerVendors[0].toString();
                // 如果已注册，则返回注册的公司信息
                if (StringUtils.isNotEmpty(companyInfo)) {
                    vendorIdSupply = JSONObject.parseObject(companyInfo).getString("comp_id");
                    merchantInfo.setServicerCompId(vendorIdSupply);
                    // 供应平台账号
                    merchantInfo.setServicerAccount(mobileNumber);
                    // 默认密码：y123456
                    merchantInfo.setServicerPassword("y123456");
                    return vendorIdSupply;
                }
            }
        } catch (Exception e) {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR);
        }

        if (StringUtils.isNotEmpty(merchantInfo.getServicerName())) {
            servicerName = merchantInfo.getServicerName();
        } else if (StringUtils.isNotEmpty(merchantInfo.getServicerEnName())) {
            servicerName = merchantInfo.getServicerEnName();
        } else {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR3);
        }

        // 根据公司ID获取公司详细信息
        CommonCompany commonCompany = commonCompanyService.selectById(merchantInfo.getCompId());
        // 船东公司ID
        String operCompId = commonCompany.getCustomCompId();
        // 船东公司名称
        String operCompName = commonCompany.getCompName();
        // 固定传1
        String vendorOpenTypeFlag = "1";
        // 调用供应系统的webService
        try {
            Object[] registerVendors = SupplyWebServiceClient.getData(registerWebServiceUrl, "registerVendor",
                    mobileNumber, servicerName, operCompId, linkman, operCompName, vendorOpenTypeFlag);

            if (registerVendors != null && registerVendors.length > 0) {
                vendorIdSupply = registerVendors[0].toString();
                if (StringUtils.isEmpty(vendorIdSupply)) {
                    throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR);
                }
                merchantInfo.setServicerCompId(vendorIdSupply);
                // 供应平台账号
                merchantInfo.setServicerAccount(mobileNumber);
                // 默认密码：y123456
                merchantInfo.setServicerPassword("y123456");
            } else {
                throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR);
            }
        } catch (Exception e) {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR);
        }

        return vendorIdSupply;
    }

    /**
     * 服务商待处理状态筛选
     *
     * @return
     */
    private List<String> getQueryStatusList(List<String> resourceIdList) {
        List<String> statusSet = new ArrayList<>();
        if (resourceIdList.contains(ServicerFeatureConstant.SERVICER_MERCHANT_INFO_ADD)
                || resourceIdList.contains(ServicerFeatureConstant.SERVICER_MERCHANT_INFO_EDIT)
                || resourceIdList.contains(ServicerFeatureConstant.SERVICER_MERCHANT_INFO_SUBMIT)) { // 新增/编辑/提交
            List<String> statusList = Lists.newArrayList(ServicerStatusEnum.WAIT_SUBMIT.getFlag(),
                    ServicerStatusEnum.REFUSED.getFlag());
            statusSet.addAll(statusList);
        }
        return statusSet;
    }

    private String registerServicerByWebServiceForTest(ServicerMerchantInfo merchantInfo) throws ServicerException {
        // 提示：注册供应平台账号，默认第一个联系人的手机号（估计以后得用统一社会信用代码作为登录id，或者是系统自动分配一个账号，强烈不建议用手机号）
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String timeStr = this.formatDate(new Date(), "yyyyMMddHHmmssSSS");
        String vendorIdSupply = "";
        // 默认密码：y123456
        String password = "y123456";
        // 默认公司编号
//		Integer maxCompNo = 5001;
        Integer maxCompNo = 6001;
        // 第一个联系人信息
        ServicerMerchantContactsInfo contactsInfo = null;
        // 联系人手机号（登录账号）
        String mobileNumber = null;
        // 服务商名称
        String servicerName = null;
        // 服务商联系人
        String linkman = null;
        List<ServicerMerchantContactsInfo> contactsList = merchantInfo.getContactsList();
        if (CollectionUtils.isNotEmpty(contactsList)) {
            contactsInfo = contactsList.get(0);
        } else {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR);
        }
        mobileNumber = contactsInfo.getMobileNumber();
        linkman = contactsInfo.getLinkMan();
        if (StringUtils.isNotEmpty(merchantInfo.getServicerName())) {
            servicerName = merchantInfo.getServicerName();
        } else if (StringUtils.isNotEmpty(merchantInfo.getServicerEnName())) {
            servicerName = merchantInfo.getServicerEnName();
        } else {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR);
        }

        // 根据公司ID获取公司详细信息
        CommonCompany commonCompany = commonCompanyService.selectById(merchantInfo.getCompId());
        // 船东公司ID
        // String operCompId = commonCompany.getCustomCompId();
        String maxCustomCompId = null;
        Wrapper<CommonCompany> companyParameterWrapper = new EntityWrapper<>();
        companyParameterWrapper.orderBy("custom_comp_id", false);
        List<CommonCompany> companyList = commonCompanyService.selectList(companyParameterWrapper);
        if (CollectionUtils.isNotEmpty(companyList)) {
            if (StringUtils.isNotEmpty(companyList.get(0).getCustomCompId())) {
                maxCustomCompId = companyList.get(0).getCustomCompId();
            }
        }

        String maxServicerCompId = null;
        Wrapper<ServicerMerchantInfo> merchantInfoWrapper = new EntityWrapper<>();
        merchantInfoWrapper.orderBy("servicer_comp_id", false);
        List<ServicerMerchantInfo> merchantInfoList = this.selectList(merchantInfoWrapper);
        if (CollectionUtils.isNotEmpty(merchantInfoList)) {
            if (StringUtils.isNotEmpty(merchantInfoList.get(0).getServicerCompId())) {
                maxServicerCompId = merchantInfoList.get(0).getServicerCompId();
            }
        }

        // 取最大值+1
        maxCompNo = this.maxCompNo(maxCustomCompId, maxServicerCompId, maxCompNo) + 1;

        // 船东公司名称
        String operCompName = commonCompany.getCompName();
        // 固定传1
        String vendorOpenTypeFlag = "1";
        // 调用供应系统的webService
        try {
            Object[] registerVendors = SupplyWebServiceClient.getData(registerWebServiceUrl, "registerVendor",
                    String.valueOf(maxCompNo), uuid, timeStr, mobileNumber, password, servicerName, operCompName,
                    linkman, vendorOpenTypeFlag, null);

            if (registerVendors != null && registerVendors.length > 0) {
                vendorIdSupply = registerVendors[0].toString();
                if (StringUtils.isEmpty(vendorIdSupply)) {
                    throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR);
                }
                merchantInfo.setServicerCompId(vendorIdSupply);
                // 供应平台账号
                merchantInfo.setServicerAccount(mobileNumber);
                merchantInfo.setServicerPassword(password);
            } else {
                throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR);
            }
        } catch (Exception e) {
            throw new ServicerException(ServicerExceptionEnum.SERVICER_REGISTER_ACCOUNT_ERROR);
        }

        return vendorIdSupply;
    }

    private String formatDate(Date date, String pattern) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat();
        format.applyPattern(pattern);
        return format.format(date);
    }

    private Integer maxCompNo(String s1, String s2, Integer defaultVaulue) {
        if (StringUtils.isEmpty(s1) && StringUtils.isEmpty(s2)) {
            return defaultVaulue;
        }
        if (StringUtils.isEmpty(s1)) {
            return Integer.valueOf(s2.substring(5, 9));
        }
        if (StringUtils.isEmpty(s2)) {
            return Integer.valueOf(s1.substring(5, 9));
        }
        if (Integer.valueOf(s1.substring(5, 9)) >= Integer.valueOf(s2.substring(5, 9))) {
            return Integer.valueOf(s1.substring(5, 9));
        } else {
            return Integer.valueOf(s2.substring(5, 9));
        }
    }

    @Override
    public String getServicerMerchantMailInfo(String servicerId) {
        String mailAddress = "";
        ServicerMerchantInfo servicerMerchantInfo = this.selectById(servicerId);
        if (null != servicerMerchantInfo && StringUtils.isNotEmpty(servicerMerchantInfo.getCommonEmailAddress())) {
            mailAddress = servicerMerchantInfo.getCommonEmailAddress() + ";";
        }
        List<CommonParameterCompany> companyBaseList = commonParameterCompanyService
                .selectList(new EntityWrapper<CommonParameterCompany>()
                        .eq(CommonParameterCompany.QueryFields.COMP_ID,
                                AuthSecurityUtils.getCurrentUserInfo().getCompId())
                        .eq(CommonParameterCompany.QueryFields.CONST_CODE, "PURCHASE_ENQUIRY_MAIL_CC_ADDRESS")
                        .setSqlSelect(
                                "parameter_id as parameterId,parameter_key as parameterKey, parameter_value as parameterValue, parameter_value_en parameterValueEn"));
        if (null != companyBaseList && companyBaseList.size() > 0) {
            mailAddress = mailAddress + companyBaseList.get(0).getParameterValue();
        }
        if (StringUtils.isNotEmpty(mailAddress) && mailAddress.split(";").length == 1) {
            mailAddress = mailAddress.replace(";", "");
        }
        return mailAddress;
    }

    /**
     * 修改是否启用
     */
    @Override
    public void updateEnabled(String id) {
        ServicerMerchantInfo info = this.selectById(id);
        info.setEnabled(info.getEnabled() == 1 ? 0 : 1);
        info.updateById();

        SupplyServicerMerchantInfo supplyServicerMerchantInfo = new SupplyServicerMerchantInfo();
        BeanUtils.copyProperties(info, supplyServicerMerchantInfo);
        supplyServicerMerchantInfoService.updateById(supplyServicerMerchantInfo);
    }


    public List<SupplyServicerMerchantContactsInfo> getCopyServicerMerchantContactsInfoList(List<ServicerMerchantContactsInfo> list) {
        List<SupplyServicerMerchantContactsInfo> supplyList = new ArrayList<SupplyServicerMerchantContactsInfo>();
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(servicerMerchantContacts -> {
                SupplyServicerMerchantContactsInfo supplyServicerMerchantContactsInfo = new SupplyServicerMerchantContactsInfo();
                BeanUtils.copyProperties(servicerMerchantContacts, supplyServicerMerchantContactsInfo);
                supplyList.add(supplyServicerMerchantContactsInfo);
            });
        }
        return supplyList;
    }

    public List<SupplyServicerMerchantBankInfo> getCopyServicerMerchantBankInfoList(List<ServicerMerchantBankInfo> list) {
        List<SupplyServicerMerchantBankInfo> supplyList = new ArrayList<SupplyServicerMerchantBankInfo>();
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(servicerMerchantBankInfo -> {
                SupplyServicerMerchantBankInfo supplyServicerMerchantBankInfo = new SupplyServicerMerchantBankInfo();
                BeanUtils.copyProperties(servicerMerchantBankInfo, supplyServicerMerchantBankInfo);
                supplyList.add(supplyServicerMerchantBankInfo);
            });
        }
        return supplyList;
    }


}
