package org.dromara.payment.worker.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.enums.BusRole;
import org.dromara.common.core.exception.base.BaseException;
import org.dromara.common.core.service.BaseService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.FileUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.payment.api.worker.RemoteUserWokerService;
import org.dromara.payment.api.worker.domain.RemoteUserWorkerZipVo;
import org.dromara.payment.channel.domain.BusChannel;
import org.dromara.payment.channel.mapper.BusChannelMapper;
import org.dromara.payment.common.domain.CommonSelConditionEntity;
import org.dromara.payment.merchant.domain.bo.BusMerchantBo;
import org.dromara.payment.merchant.domain.vo.BusMerchantVo;
import org.dromara.payment.merchant.domain.vo.BusOperAndAgentAndMer;
import org.dromara.payment.merchant.mapper.BusMerchantMapper;
import org.dromara.payment.sys.domain.vo.SysSydVo;
import org.dromara.payment.sys.mapper.SysSydMapper;
import org.dromara.payment.taxRecords.service.impl.AsyncTaxRecordsService;
import org.dromara.payment.worker.domain.UserWorker;
import org.dromara.payment.worker.domain.UserWorkerAccount;
import org.dromara.payment.worker.domain.bo.UserWokerOperBo;
import org.dromara.payment.worker.domain.bo.UserWorkerAccountBo;
import org.dromara.payment.worker.domain.bo.UserWorkerBo;
import org.dromara.payment.worker.domain.vo.*;
import org.dromara.payment.worker.mapper.UserWorkerAccountMapper;
import org.dromara.payment.worker.mapper.UserWorkerMapper;
import org.dromara.payment.worker.service.IIdCardAndOtherService;
import org.dromara.settlement.api.RemoteAccountService;
import org.dromara.settlement.api.domain.Account;
import org.dromara.settlement.api.domain.Result;
import org.dromara.system.api.RemoteDictService;
import org.dromara.system.api.domain.vo.RemoteDictDataVo;
import org.springframework.stereotype.Service;
import org.dromara.payment.worker.domain.bo.UserWorkerBusinessBo;
import org.dromara.payment.worker.domain.UserWorkerBusiness;
import org.dromara.payment.worker.mapper.UserWorkerBusinessMapper;
import org.dromara.payment.worker.service.IUserWorkerBusinessService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用工签约查询Service业务层处理
 *
 * @author LionLi
 * @date 2024-04-26
 */
@RequiredArgsConstructor
@Service
public class UserWorkerBusinessServiceImpl extends BaseService implements IUserWorkerBusinessService {

    private final UserWorkerBusinessMapper baseMapper;


    @DubboReference
    private RemoteDictService remoteDictService;

    @Resource
    private BusMerchantMapper busMerchantMapper;

    @Resource
    private UserWorkerMapper  userWorkerMapper;

    @Resource
    private SysSydMapper sysSydMapper;

    @Resource
    private UserWorkerAccountMapper userWorkerAccountMapper;


    @DubboReference
    private RemoteAccountService accountService;

    @DubboReference
    private RemoteUserWokerService remoteUserWokerService;


    @Resource(name="tencentIdCardAndOtherServiceImpl")
    public IIdCardAndOtherService tencentIdCardAndOtherService;



    @Resource
    public AsyncTaxRecordsService asyncTaxRecordsService;


    @Override
    public TableDataInfo<UserWorkerBusinessVo> selUserWorkByMerServInfo(PageQuery pageQuery, Long sydId, Long merId, Integer busType) {
        Page<UserWorkerBusinessVo> result = baseMapper.selUserWorkByMerServInfo(pageQuery.build(),merId,sydId,null,busType);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用工签约查询
     */
    @Override
    public UserWorkerBusinessVo queryById(Long id){
        return baseMapper.selUserWorkDetail(id);
    }

    /**
     * 查询用工签约查询列表
     */
    @Override
    public TableDataInfo<UserWorkerBusinessVo> queryPageList(CommonSelConditionEntity bo, PageQuery pageQuery) {
        QueryWrapper lqw = new QueryWrapper<>();
        lqw.between(bo.getStartTime() != null,"t.create_time",bo.getStartTime(),bo.getEndTime());
        lqw.eq(bo.getSignStatus() != null, "t.sign_status", bo.getSignStatus());
        lqw.like(StringUtils.isNotEmpty(bo.getWorkPhone()),"t.v_phone",bo.getWorkPhone());
        lqw.like(StringUtils.isNotEmpty(bo.getWorkName()),"t1.name",bo.getWorkName());
        lqw.eq(StringUtils.isNotEmpty(bo.getBusMerName()), "t2.name", bo.getBusMerName());
        lqw.like(StringUtils.isNotEmpty(bo.getWorkIdCard()),"t1.card_id",bo.getWorkIdCard());
        lqw.eq(bo.getSydId() != null ,"t.syd_id",bo.getSydId());
        lqw.eq(bo.getBusType() != null,"t.bus_type",bo.getBusType());
        int busRole = LoginHelper.getLoginUser().getBusRole();
        if(busRole == BusRole.MERCHANT.getId()){
            lqw.eq("t.mer_id",LoginHelper.getBusId());
        }else if(busRole == BusRole.AGENT.getId()){
            lqw.likeRight("t.channel_no",LoginHelper.getNo());
        }else if(busRole == BusRole.OPERATOR.getId()){
            lqw.eq("op_id",LoginHelper.getBusId());
        }else if(busRole == BusRole.SERVICE.getId()){
            lqw.eq("t.syd_id",LoginHelper.getBusId());
        }
        lqw.orderByDesc("t.create_time");
        Page<UserWorkerBusinessVo> result = baseMapper.selUserWorkSignLists(pageQuery.build(),lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用工签约查询列表
     */
    @Override
    public List<UserWorkerBusinessVo> queryList(CommonSelConditionEntity bo) {
        QueryWrapper lqw = new QueryWrapper<>();

        lqw.between(bo.getStartTime() != null,"t.create_time",bo.getStartTime(),bo.getEndTime());
        lqw.eq(bo.getSignStatus() != null, "t.sign_status", bo.getSignStatus());
        lqw.like(StringUtils.isNotEmpty(bo.getWorkPhone()),"t.v_phone",bo.getWorkPhone());
        lqw.like(StringUtils.isNotEmpty(bo.getWorkName()),"t1.name",bo.getWorkName());
        lqw.eq(StringUtils.isNotEmpty(bo.getBusMerName()), "t2.name", bo.getBusMerName());
        lqw.like(StringUtils.isNotEmpty(bo.getWorkIdCard()),"t1.card_id",bo.getWorkIdCard());
        lqw.eq(bo.getBusType() != null,"t.bus_type",bo.getBusType());
        lqw.eq(bo.getSydId() != null ,"t.syd_id",bo.getSydId());
        int busRole = LoginHelper.getLoginUser().getBusRole();
        if(busRole == BusRole.MERCHANT.getId()){
            lqw.eq("t.mer_id",LoginHelper.getBusId());
        }else if(busRole == BusRole.AGENT.getId()){
            lqw.likeRight("t.channel_no",LoginHelper.getNo());
        }else if(busRole == BusRole.OPERATOR.getId()){
            lqw.eq("op_id",LoginHelper.getBusId());
        }else if(busRole == BusRole.SERVICE.getId()){
            lqw.eq(bo.getSydId() != null ,"t.syd_id",LoginHelper.getBusId());
        }
        lqw.orderByDesc("t.create_time");

        return baseMapper.selUserWorkSignLists(lqw);
    }

    private QueryWrapper<UserWorkerBusiness> buildQueryWrapper(UserWorkerBusinessBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<UserWorkerBusiness> lqw = new QueryWrapper<>();
        lqw.eq(bo.getWorkId() != null, "work_id", bo.getWorkId());
        lqw.eq(bo.getSydId() != null, "syd_id", bo.getSydId());
        lqw.eq(StringUtils.isNotBlank(bo.getSydNo()), "syd_no", bo.getSydNo());
        lqw.eq(bo.getBusType() != null, "bus_type", bo.getBusType());
        lqw.eq(StringUtils.isNotBlank(bo.getOpNo()), "op_no", bo.getOpNo());
        lqw.eq(bo.getOpId() != null, "op_id", bo.getOpId());
        lqw.eq(bo.getChannelId() != null, "channel_id", bo.getChannelId());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelNo()), "channel_no", bo.getChannelNo());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelCode()), "channel_code", bo.getChannelCode());
        lqw.eq(bo.getMerId() != null, "mer_id", bo.getMerId());
        lqw.eq(StringUtils.isNotBlank(bo.getMerNo()), "mer_no", bo.getMerNo());
        lqw.eq(StringUtils.isNotBlank(bo.getNo()), "no", bo.getNo());
        lqw.eq(bo.getSignStatus() != null, "sign_status", bo.getSignStatus());
        lqw.eq(bo.getSignTime() != null, "sign_time", bo.getSignTime());
        lqw.eq(StringUtils.isNotBlank(bo.getSignFileUrl()), "sign_file_url", bo.getSignFileUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getSignPic()), "sign_pic", bo.getSignPic());
        lqw.eq(StringUtils.isNotBlank(bo.getMoneyYearDate()), "money_year_date", bo.getMoneyYearDate());
        lqw.eq(bo.getMoneyYear() != null, "money_year", bo.getMoneyYear());
        lqw.eq(StringUtils.isNotBlank(bo.getVPhone()), "v_phone", bo.getVPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getSignNo()), "sign_no", bo.getSignNo());
        lqw.eq(StringUtils.isNotBlank(bo.getSignUrl()), "sign_url", bo.getSignUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getWebUrl()), "web_url", bo.getWebUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getOssid()), "ossid", bo.getOssid());
        return lqw;
    }

    /**
     * 新增用工签约查询
     */
    @Override
    public Boolean insertByBo(UserWorkerBusinessBo bo) {
        UserWorkerBusiness add = MapstructUtils.convert(bo, UserWorkerBusiness.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用工签约查询
     */
    @Override
    public Boolean updateByBo(UserWorkerBusinessBo bo) {
        UserWorkerBusiness update = MapstructUtils.convert(bo, UserWorkerBusiness.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UserWorkerBusiness entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用工签约查询
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /***
     * 用工签约导入
     * @param file
     * @busType 业务类型
     * @sydId 服务商编码
     * @return
     */
    @Override
    public ImportResultVo upload(MultipartFile file, Integer busType, Long sydId,String sydNo,String code,Long merId,String merNo) throws Exception {

        ImportResultVo  vo = new ImportResultVo();

        if(file == null || file.isEmpty()){
            this.invalidationParamsException("不能上传空文件");
        }

        if(busType == null){
            this.invalidationParamsException("业务类型不能为空");
        }

        if(sydId == null){
            this.invalidationParamsException("服务商id不能为空");
        }

        if(StringUtils.isEmpty(sydNo)){
            this.invalidationParamsException("服务商编码不能为空");
        }

        if(StringUtils.isEmpty(code)){
            this.invalidationParamsException("域名不能为空");
        }

        Integer busRole = LoginHelper.getBusRole();
        if(busRole == BusRole.MERCHANT.getId()){
            merId = LoginHelper.getBusId();
            merNo = LoginHelper.getNo();
        }else{
            if(merId == null){
                this.invalidationParamsException("企业ID不能为空");
            }

            if(StringUtils.isEmpty(merNo)){
                this.invalidationParamsException("企业编码不能为空");
            }

        }

        try{
            BusMerchantBo bo1 = new BusMerchantBo();
            bo1.setNo(merNo);
            BusOperAndAgentAndMer busOperAndAgentAndMer = this.busMerchantMapper.selOpAndAgentInfosByMerInfo(bo1);
            ExcelListener listener =  new  ExcelListener();
            EasyExcel.read(file.getInputStream(), UploadExcelItem.class,listener).headRowNumber(3).sheet().doRead();
            List<UploadExcelItem> excelList = listener.getList();
            List<UserWorkerBusiness> passlist = new ArrayList<>();
            List<UserWorker> userWorkerList = new ArrayList<>();
            List<UploadExcelItem> nopassList = new ArrayList<>();
            for(UploadExcelItem item :excelList){

                if(!PhoneUtil.isPhone(item.getPhone())){
                    item.setErrorMsg("手机号校验不通过");
                    nopassList.add(item);
                    continue;
                }
                if(!IdcardUtil.isValidCard(item.getIdCard())){
                    item.setErrorMsg("身份证号校验不通过");
                    nopassList.add(item);
                    continue;
                }
                UserWorkerBusinessVo  userWorker = this.baseMapper.selUserWorkByIdCard(LoginHelper.getBusId(),item.getIdCard(),busType,sydId);
                if(userWorker != null){
                    if(!item.getName().equals(userWorker.getWorkName())){
                        item.setErrorMsg("导入信息与系统已有信息不一致");
                        nopassList.add(item);
                        continue;
                    }

                    if(userWorker.getPhone() != null && !item.getPhone().equals(userWorker.getPhone()) ){
                        item.setErrorMsg("导入信息与系统已有信息不一致");
                        nopassList.add(item);
                        continue;
                    }

                    if(userWorker.getPhone()  != null){
                        item.setErrorMsg("导入用工信息已经存在！");
                        nopassList.add(item);
                        continue;
                    }



                }else{
                    try{
                        this.tencentIdCardAndOtherService.cardId2(item.getName(),item.getIdCard(),code);
                    }catch(BaseException e ){
                        item.setErrorMsg("身份证校验不通过,"+e.getMessage());
                        nopassList.add(item);
                        continue;
                    }
                }

                if(userWorker != null){
                    UserWorkerBusiness userWorkerBusinessBo = new UserWorkerBusiness();
                    userWorkerBusinessBo.setWorkId(userWorker.getWorkId());
                    userWorkerBusinessBo.setCreateBy(LoginHelper.getUserId());
                    userWorkerBusinessBo.setCreateTime(new Date());
                    userWorkerBusinessBo.setBusType(busType);
                    userWorkerBusinessBo.setSydId(sydId);
                    userWorkerBusinessBo.setSydNo(sydNo);
                    userWorkerBusinessBo.setMerId(merId);
                    userWorkerBusinessBo.setMerNo(merNo);
                    userWorkerBusinessBo.setChannelId(busOperAndAgentAndMer.getChannelId());
                    userWorkerBusinessBo.setChannelNo(busOperAndAgentAndMer.getChannelNo());
                    userWorkerBusinessBo.setOpId(busOperAndAgentAndMer.getOpId());
                    userWorkerBusinessBo.setOpNo(busOperAndAgentAndMer.getOpNo());
                    userWorkerBusinessBo.setSignStatus(0);
                    userWorkerBusinessBo.setVPhone(item.getPhone());
                    passlist.add(userWorkerBusinessBo);
                }else{
                    long id = IdUtil.getSnowflakeNextId();
                    UserWorker userWorkerBo = new UserWorker();
                    userWorkerBo.setId(id);
                    userWorkerBo.setName(item.getName());
                    userWorkerBo.setCardId(item.getIdCard());
                    userWorkerBo.setCreateBy(LoginHelper.getUserId());
                    userWorkerBo.setStatus(2);
                    userWorkerBo.setCreateTime(new Date());
                    userWorkerList.add(userWorkerBo);
                    UserWorkerBusiness userWorkerBusiness = new UserWorkerBusiness();
                    userWorkerBusiness.setWorkId(id);
                    userWorkerBusiness.setChannelId(busOperAndAgentAndMer.getChannelId());
                    userWorkerBusiness.setChannelNo(busOperAndAgentAndMer.getChannelNo());
                    userWorkerBusiness.setOpId(busOperAndAgentAndMer.getOpId());
                    userWorkerBusiness.setOpNo(busOperAndAgentAndMer.getOpNo());
                    userWorkerBusiness.setCreateBy(LoginHelper.getUserId());
                    userWorkerBusiness.setSydId(sydId);
                    userWorkerBusiness.setSydNo(sydNo);
                    userWorkerBusiness.setMerId(merId);
                    userWorkerBusiness.setMerNo(merNo);
                    userWorkerBusiness.setCreateTime(new Date());
                    userWorkerBusiness.setBusType(busType);
                    userWorkerBusiness.setSignStatus(0);
                    userWorkerBusiness.setVPhone(item.getPhone());
                    passlist.add(userWorkerBusiness);
                }
            }

            vo.setCnt(excelList.size());
            vo.setFailCnt(nopassList.size());
            vo.setSuccessCnt(passlist.size());

            if(!nopassList.isEmpty()){
                String uuid = UUID.fastUUID().toString();
                vo.setDownId(uuid);
                RedisUtils.setCacheObject(GlobalConstants.USERWORK_SIGN_ERROR_KEY+uuid,nopassList, Duration.ofDays(15));
            }

            if(!passlist.isEmpty()){
                this.isSign(passlist,sydId,busType);
                this.baseMapper.insertBatch(passlist);
            }
            if(!userWorkerList.isEmpty()){
                this.userWorkerMapper.insertBatch(userWorkerList);
            }

        }catch (Exception  e){
            e.printStackTrace();
            throw e ;
        }

        return vo;
    }

    @Override
    public List<UploadExcelItem> selErrorList(String uuid) {
        if(StringUtils.isEmpty(uuid)){
            return new ArrayList<>();
        }
        List<UploadExcelItem>  list =  RedisUtils.getCacheObject(GlobalConstants.USERWORK_SIGN_ERROR_KEY+uuid);
        if(list == null){
            return new ArrayList<>();
        }
        return list;
    }

    @Override
    public UserWorkerVo selMemberInfo(UserWorkerBusinessBo bo) {
        if(bo.getId() == null){
            this.invalidationParamsException("用工签约ID不能为空");
        }
        UserWorkerVo vo = this.baseMapper.selMemberInfo(bo);
        return vo;
    }





    /***
     * 添加用戶-运营商
     * @param bo
     * @return
     */
    @Override
    @Transactional
    public Boolean addUserWorkdBz(UserWokerOperBo bo) throws Exception{

        if(!PhoneUtil.isPhone(bo.getPhone())){
            this.invalidationParamsException("手机号校验不通过");
        }
        if(!IdcardUtil.isValidCard(bo.getIdCard())){
            this.invalidationParamsException("身份证校验不通过");
        }
        UserWorkerBusinessVo  userWorker = this.baseMapper.selUserWorkByIdCard(bo.getMerId(),bo.getIdCard(),bo.getBusType(),bo.getSydId());
        if(userWorker != null){
            if(!bo.getWorkName().equals(userWorker.getWorkName())){
                this.invalidationParamsException("添加信息与系统已有信息不一致");
            }

            if(userWorker.getPhone() != null && !bo.getPhone().equals(userWorker.getPhone())){
                this.invalidationParamsException("添加信息与系统已有信息不一致");
            }

            if(userWorker.getPhone() != null){
                this.invalidationParamsException("添加信息已经存在");
            }

        }else{
            try{
                this.tencentIdCardAndOtherService.cardId2(bo.getWorkName(),bo.getIdCard(),bo.getCode());
            }catch(BaseException e ){
                this.invalidationParamsException("身份证校验不通过,"+e.getMessage());
                throw e;
            }
        }

        try{
            this.tencentIdCardAndOtherService.bankCard3(bo.getBackCard(),bo.getWorkName(),bo.getIdCard(),bo.getCode());
        }catch(BaseException e ){
            this.invalidationParamsException("银行卡校验不通过,"+e.getMessage());
            throw e;
        }


        BusMerchantBo bo1 = new BusMerchantBo();
        bo1.setId(bo.getMerId());
        BusOperAndAgentAndMer busOperAndAgentAndMer = this.busMerchantMapper.selOpAndAgentInfosByMerInfo(bo1);
        if(userWorker != null){
            UserWorkerBusiness userWorkerBusinessBo = new UserWorkerBusiness();
            userWorkerBusinessBo.setWorkId(userWorker.getWorkId());
            bo.setWork_id(userWorker.getWorkId());
            userWorkerBusinessBo.setCreateBy(LoginHelper.getUserId());
            userWorkerBusinessBo.setCreateTime(new Date());
            userWorkerBusinessBo.setBusType(bo.getBusType());
            userWorkerBusinessBo.setSydId(bo.getSydId());
            userWorkerBusinessBo.setSydNo(bo.getSydNo());
            userWorkerBusinessBo.setMerNo(bo.getMerNo());
            userWorkerBusinessBo.setMerId(bo.getMerId());
            userWorkerBusinessBo.setChannelId(busOperAndAgentAndMer.getChannelId());
            userWorkerBusinessBo.setChannelNo(busOperAndAgentAndMer.getChannelNo());
            userWorkerBusinessBo.setOpId(busOperAndAgentAndMer.getOpId());
            userWorkerBusinessBo.setOpNo(busOperAndAgentAndMer.getOpNo());
            userWorkerBusinessBo.setSignStatus(0);
            userWorkerBusinessBo.setVPhone(bo.getPhone());
            this.baseMapper.insert(userWorkerBusinessBo);

            UserWorker userWorkerBo = new UserWorker();
            boolean updateStatus = false;
            if(StringUtils.isNotEmpty(bo.getCardPositive())){
                userWorkerBo.setCardPositive(bo.getCardPositive());
                updateStatus = true;
            }
            if(StringUtils.isNotEmpty(bo.getCardBack())){
                userWorkerBo.setCardBack(bo.getCardBack());
                updateStatus = true;
            }

            if(StringUtils.isNotEmpty(bo.getFacePic())){
                userWorkerBo.setPhotoPath(bo.getFacePic());
                updateStatus = true;
            }

            if(updateStatus){
                userWorkerBo.setId(userWorker.getWorkId());
                this.userWorkerMapper.updateById(userWorkerBo);
            }

        }else{

            long id = IdUtil.getSnowflakeNextId();
            bo.setWork_id(id);
            UserWorker userWorkerBo = new UserWorker();
            userWorkerBo.setId(id);
            userWorkerBo.setName(bo.getWorkName());
            userWorkerBo.setCardId(bo.getIdCard());
            userWorkerBo.setCreateBy(LoginHelper.getUserId());
            userWorkerBo.setStatus(2);
            userWorkerBo.setCardPositive(bo.getCardPositive());
            userWorkerBo.setCardBack(bo.getCardBack());
            userWorkerBo.setPhotoPath(bo.getFacePic());
            userWorkerBo.setCreateTime(new Date());
            this.userWorkerMapper.insert(userWorkerBo);
            UserWorkerBusiness userWorkerBusiness = new UserWorkerBusiness();
            userWorkerBusiness.setWorkId(id);
            userWorkerBusiness.setChannelId(busOperAndAgentAndMer.getChannelId());
            userWorkerBusiness.setChannelNo(busOperAndAgentAndMer.getChannelNo());
            userWorkerBusiness.setOpId(busOperAndAgentAndMer.getOpId());
            userWorkerBusiness.setOpNo(busOperAndAgentAndMer.getOpNo());
            userWorkerBusiness.setCreateBy(LoginHelper.getUserId());
            userWorkerBusiness.setSydId(bo.getSydId());
            userWorkerBusiness.setSydNo(bo.getSydNo());
            userWorkerBusiness.setMerNo(bo.getMerNo());
            userWorkerBusiness.setMerId(bo.getMerId());
            userWorkerBusiness.setCreateTime(new Date());
            userWorkerBusiness.setBusType(bo.getBusType());
            userWorkerBusiness.setSignStatus(0);
            userWorkerBusiness.setVPhone(bo.getPhone());
            this.baseMapper.insert(userWorkerBusiness);
        }
        dwUserWorkBank(bo);
        return true;
    }

    @Override
    public Boolean operAddUserWorkSel(Long merId,Long sydId,Integer busType,String workIds) {

        if(merId == null){
            this.invalidationParamsException("企业ID不能为空");
        }

        if(sydId == null){
            this.invalidationParamsException("服务商ID不能为空");
        }

        if(busType == null){
            this.invalidationParamsException("业务类型ID不能为空");
        }

        if(StringUtils.isEmpty(workIds)){
            this.invalidationParamsException("用工ID不能为空");
        }

        {
            BusMerchantBo bo1 = new BusMerchantBo();
            bo1.setId(merId);
            BusOperAndAgentAndMer busOperAndAgentAndMer = this.busMerchantMapper.selOpAndAgentInfosByMerInfo(bo1);
            SysSydVo sysSydVo = this.sysSydMapper.selectVoById(sydId);
            Date d = new Date();
            Long userId = LoginHelper.getUserId();
            List<UserWorkerBusinessVo>  list = this.baseMapper.selUserWorkByMerServInfo(merId,sydId,workIds,busType);
            List<UserWorkerBusiness> li = new ArrayList();
            for (UserWorkerBusinessVo vo :list){
                UserWorkerBusiness bo = new UserWorkerBusiness();
                bo.setWorkId(vo.getWorkId());
                bo.setVPhone(vo.getvPhoneNoHide());
                bo.setSydId(sydId);
                bo.setSydNo(sysSydVo.getNo());
                bo.setOpNo(busOperAndAgentAndMer.getOpNo());
                bo.setOpId(busOperAndAgentAndMer.getOpId());
                bo.setChannelId(busOperAndAgentAndMer.getChannelId());
                bo.setChannelNo(busOperAndAgentAndMer.getChannelNo());
                bo.setMerId(merId);
                bo.setMerNo(busOperAndAgentAndMer.getMerNo());
                bo.setBusType(busType);
                bo.setCreateTime(d);
                bo.setSignStatus(0);
                bo.setCreateBy(userId);
                li.add(bo);
            }
            this.baseMapper.insertBatch(li);
            return true;
        }
    }

    @Override
    public Boolean operAddUserWorkAll(Long merId, Long sydId, Integer busType) {
        BusMerchantBo bo1 = new BusMerchantBo();
        bo1.setId(merId);
        BusOperAndAgentAndMer busOperAndAgentAndMer = this.busMerchantMapper.selOpAndAgentInfosByMerInfo(bo1);
        SysSydVo sysSydVo = this.sysSydMapper.selectVoById(sydId);

        Date d = new Date();
        Long userId = LoginHelper.getUserId();
        List<UserWorkerBusinessVo>  list = this.baseMapper.selUserWorkByMerServInfo(merId,sydId,null,busType);
        List<UserWorkerBusiness> li = new ArrayList();
        for (UserWorkerBusinessVo vo :list){
            UserWorkerBusiness bo = new UserWorkerBusiness();
            bo.setWorkId(vo.getWorkId());
            bo.setVPhone(vo.getvPhoneNoHide());
            bo.setSydId(sydId);
            bo.setSydNo(sysSydVo.getNo());
            bo.setOpNo(busOperAndAgentAndMer.getOpNo());
            bo.setOpId(busOperAndAgentAndMer.getOpId());
            bo.setChannelId(busOperAndAgentAndMer.getChannelId());
            bo.setChannelNo(busOperAndAgentAndMer.getChannelNo());
            bo.setMerId(merId);
            bo.setMerNo(busOperAndAgentAndMer.getMerNo());
            bo.setBusType(busType);
            bo.setCreateTime(d);
            bo.setSignStatus(0);
            bo.setCreateBy(userId);
            li.add(bo);
        }
        this.baseMapper.insertBatch(li);
        return true;
    }

    private void isSign(List<UserWorkerBusiness> list,Long sydId,Integer busType){


        Map paraMap = new HashMap();
        paraMap.put("workIds",list);
        paraMap.put("sydId",sydId);
        paraMap.put("busType",busType);

        List<UserWorkerBusinessVo> signList = this.baseMapper.selUserWorkBizByWorkIdSydIdBusType(paraMap);
        if(signList != null && !signList.isEmpty()){
            Map<Long,UserWorkerBusinessVo> resultMap =   signList.stream().collect(Collectors.toMap(UserWorkerBusinessVo::getWorkId, userWorkerBusinessVo -> userWorkerBusinessVo));
            for(UserWorkerBusiness vo : list){
                UserWorkerBusinessVo uwbvo =  resultMap.get(vo.getWorkId());
                if(uwbvo != null){
                    vo.setSignStatus(1);
                    vo.setNo(uwbvo.getNo());
                    vo.setSignFileUrl(uwbvo.getSignFileUrl());
                }
            }
        }
    }

    /***
     *
     * 用工银行账号处理
     * @param bo
     *
     */
    private void dwUserWorkBank(UserWokerOperBo bo) {

        String chnnalName = this.baseMapper.selSydDefaultChannel(bo.getSydId());
        if(StringUtils.isEmpty(chnnalName)){
           List<RemoteDictDataVo>  dictDataList =  this.remoteDictService.selectDictDataByType("pay_channel");
           if(dictDataList != null && !dictDataList.isEmpty()){
                chnnalName = dictDataList.get(0).getDictLabel();
           }
        }

        if(StringUtils.isNotEmpty(chnnalName)){
            UserWokerOperBo bno = new UserWokerOperBo();
            bno.setWork_id(bo.getWork_id());
            bno.setChannelName(chnnalName);
            bno.setBackCard(bo.getBackCard());
            List<UserWorkerAccountVo>  accountVo = this.userWorkerAccountMapper.selctBankInfoByUidChannelBankNo(bno);
            boolean isDefault = false;
            boolean cz = false;
            UserWorkerAccountVo  selVo = null;
            if(accountVo != null && !accountVo.isEmpty()){
                for(UserWorkerAccountVo vo :accountVo){
                    if(vo.getIsDefault() == 1){
                        isDefault = true;
                    }
                    if(vo.getBankCard().equals(bo.getBackCard())){
                        cz = true;
                        selVo = vo;
                    }
                }
            }
            if(cz && StringUtils.isNotEmpty(bo.getBankPic())){
                UserWorkerAccount  uwab = new UserWorkerAccount();
                uwab.setId(selVo.getId());
                uwab.setStatus(1);
                uwab.setBankCardPic(bo.getBankPic());
                this.userWorkerAccountMapper.updateById(uwab);
            }else if(!cz){
                //先生成账号
                Account bankAcc = new Account();
                bankAcc.setType((short)2);//2:真实个人账户
                bankAcc.setBankCard(bo.getBackCard());
                bankAcc.setBankType(bo.getKhh());
                bankAcc.setUnitId(0L);
                bankAcc.setName(bo.getWorkName());
                Result<Account> result = this.accountService.addAccount(bankAcc);
                Integer accountId = result.getRtnData().getId();
                if(accountId == null){
                    this.invalidationParamsException("创建账号失败!");
                }

                //添加银行卡
                UserWorkerAccount  uwab = new UserWorkerAccount();
                uwab.setWorkId(bo.getWork_id());
                uwab.setAccId(Long.valueOf(accountId));
                uwab.setBankCard(bo.getBackCard());
                uwab.setPassage(chnnalName);
                uwab.setBankCardPic(bo.getBankPic());
                uwab.setBankType(bo.getKhh());
                uwab.setCreateTime(new Date());
                uwab.setCreateBy(LoginHelper.getUserId());
                if(!isDefault){
                    uwab.setIsDefault(1L);
                }else{
                    uwab.setIsDefault(0L);
                }
                this.userWorkerAccountMapper.insert(uwab);
            }
        }

    }


    /****
     * 运营商 - 信息修改
     * @param uwb
     * @return
     */
    @Override
    @Transactional
    public Boolean  updateUserWorkInfo(UserWorkerBo uwb){

        if(uwb.getId() == null){
            this.invalidationParamsException("用户ID不能为空");
        }
        if(uwb.getMerId() == null){
            this.invalidationParamsException("企业ID不能为空");
        }
        this.baseMapper.updateUserWorkByCardId(uwb);
        UserWorkerBusinessBo  uwbb = new UserWorkerBusinessBo();
        uwbb.setWorkId(uwb.getId());
        uwbb.setMerId(uwb.getMerId());
        uwbb.setVPhone(uwb.getPhone());
        this.baseMapper.updateUserWorkBisByWorkId(uwbb);
        return true;
    }



    @Override
    public UserWorkerNoHideVo selMemberInfoNySignId(UserWorkerBusinessBo bo ){
        if(bo.getId() == null){
            this.invalidationParamsException("签约ID不能为空");
        }
        UserWorkerVo vo = this.baseMapper.selMemberInfo(bo);
        UserWorkerNoHideVo noHideVo = BeanUtil.copyProperties(vo, UserWorkerNoHideVo.class);
        noHideVo.setCardIdNoHide(vo.getCardIdNoHide());
        noHideVo.setPhoneNoHide(vo.getPhoneNoHide());
        return noHideVo;
    }


    /***
     * 单个导出用工的身份证信息
     * @param workId
     * @param response
     */
    @Override
    public void exportCardImg(Long workId, HttpServletResponse response)throws Exception {

        if(workId == null){
            this.invalidationParamsException("用工ID不能为空");
        }

        UserWorker uw = this.userWorkerMapper.selectById(workId);

        if(uw == null){
            this.invalidationParamsException("参数无效");
        }

        if(StringUtils.isEmpty(uw.getCardPositive()) && StringUtils.isEmpty(uw.getCardBack())){
            this.invalidationParamsException("此会员未上传身份证图片");
        }

        RemoteUserWorkerZipVo vo = new RemoteUserWorkerZipVo();
        vo.setWorkName(uw.getName());
        vo.setWorkId(uw.getId());
        vo.setCardPositive(uw.getCardPositive());
        vo.setCardBack(uw.getCardBack());
        byte[] imgByte = this.remoteUserWokerService.downLoadSigleSfzZip(vo);response.reset();
        //response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
//        response.setHeader("Content-Disposition", "attachment; filename=\""+uw.getName()+"身份证信息.zip\"");
        response.addHeader("Content-Length", "" + imgByte.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        FileUtils.setAttachmentResponseHeader(response,uw.getName()+"身份证信息.zip");
        IoUtil.write(response.getOutputStream(), false, imgByte);

    }


    /***
     * 批量导出用工者身份证信息
     * @param workIds
     */
    @Override
    public void exportMutiCardImg(String workIds) throws Exception{

        if(StringUtils.isEmpty(workIds)){
            this.invalidationParamsException("请输入用工者ID");
        }

        Long userId = LoginHelper.getUserId();
        String[] wids = workIds.split(",");
        List list = new ArrayList();
        for(String s : wids){
            list.add(Long.valueOf(s));
        }
        try{
            this.asyncTaxRecordsService.createSfzZipByUserInfos(list,userId,1);
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

}




/***
 * 解析Excel监听器
 */
class ExcelListener extends AnalysisEventListener<UploadExcelItem> {

    private List<UploadExcelItem> list = new ArrayList<>();

    private Map<String,String > idCardMap = new HashMap<>();

    private Map<String,String > phoneMap = new HashMap<>();
    @Override
    public void invoke(UploadExcelItem importResultVo, AnalysisContext analysisContext) {


        int rowIndex = analysisContext.readRowHolder().getRowIndex()+1;

        if(rowIndex > 503){
            throw new BaseException("导入上限为500条");

        }

        if(StringUtils.isEmpty(importResultVo.getName())){
            throw new BaseException("第"+rowIndex+"行姓名不能为空");
        }

        if(StringUtils.isEmpty(importResultVo.getIdCard())){
            throw new BaseException("第"+rowIndex+"行身份证不能为空");
        }

        if(StringUtils.isEmpty(importResultVo.getPhone())){
            throw new BaseException("第"+rowIndex+"行手机号不能为空");
        }

        importResultVo.setIdCard(importResultVo.getIdCard().trim());
        Object obj  = idCardMap.get(importResultVo.getIdCard());
        if(obj == null){
            idCardMap.put(importResultVo.getIdCard(), "");
        }else{
            throw new BaseException("第"+rowIndex+"行身份证["+importResultVo.getIdCard()+"]已存在");
        }
        importResultVo.setPhone(importResultVo.getPhone().trim());
        Object phoneObj = phoneMap.get(importResultVo.getPhone());
        if(phoneObj == null){
            phoneMap.put(importResultVo.getPhone(), "");
        }else{
            throw new BaseException("第"+rowIndex+"行手机号["+importResultVo.getPhone()+"]已存在");
        }
        this.list.add(importResultVo);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }


    public List<UploadExcelItem> getList() {
        return this.list;
    }
}
