package com.ltgk.crew.service.impl;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ltgk.common.constant.Constants;
import com.ltgk.common.enums.EnterOutPortStatus;
import com.ltgk.common.utils.SecurityUtils;
import com.ltgk.common.utils.bean.BeanUtils;
import com.ltgk.crew.domain.dto.AddDsCrewCheckAndBindBoatReq;
import com.ltgk.crew.domain.dto.AddDsCrewEnterCheckReq;
import com.ltgk.crew.domain.entity.DsBoatCrew;
import com.ltgk.crew.domain.entity.DsCrewEnterCheck;
import com.ltgk.crew.mapper.DsCrewEnterCheckMapper;
import com.ltgk.crew.service.IDsBoatCrewService;
import com.ltgk.crew.service.IDsCrewEnterCheckService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 进港船员报备信息Service业务层处理
 *
 * @author Qi ChengBin
 * @date 2024-12-07
 */
@Service
public class DsCrewEnterCheckServiceImpl extends ServiceImpl<DsCrewEnterCheckMapper, DsCrewEnterCheck> implements IDsCrewEnterCheckService {
    @Resource
    private IDsBoatCrewService dsBoatCrewService;

    @Override
    public String getCrewIds(String enterPortId) {
        LambdaQueryWrapper<DsCrewEnterCheck> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DsCrewEnterCheck::getEnterPortId, enterPortId);
        List<DsCrewEnterCheck> list = this.list(lqw);
        return list.stream().map(DsCrewEnterCheck::getCrewId).map(String::valueOf).collect(Collectors.joining(","));
    }

    /**
     * 新增进港船员报备信息
     * -- 1. 不可重复提交
     * -- 2. 新增的船员不是系统中的船员时，先添加系统中船员的数据
     * -- 3. 校验此船员是否绑定其他渔船，如果绑定其他渔船，则不可进行提交
     * -- 4. 新增渔船与船员绑定信息
     * -- 5. 新增船员审核信息
     *
     * @param addDsCrewEnterCheckReq: 新增进港船员报备信息数据传输对象
     * @return boolean
     * @author Qi ChengBin
     * @date 2025/1/2 14:06
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addDsCrewEnterCheck(AddDsCrewEnterCheckReq addDsCrewEnterCheckReq) {
        // 校验此船员是否已经提交审核
        DsCrewEnterCheck dbDsCrewEnterCheck = this.lambdaQuery()
                .eq(DsCrewEnterCheck::getEnterPortId, addDsCrewEnterCheckReq.getEnterPortId())
                .eq(null != addDsCrewEnterCheckReq.getCrewId(), DsCrewEnterCheck::getCrewId, addDsCrewEnterCheckReq.getCrewId())
                .eq(DsCrewEnterCheck::getCrewName, addDsCrewEnterCheckReq.getCrewName())
                .one();
        if (Objects.nonNull(dbDsCrewEnterCheck)) {
            throw new RuntimeException("船员‘" + addDsCrewEnterCheckReq.getCrewName() + "‘，已经提交审核，请不要重复提交！");
        }
        String userName = SecurityUtils.getLoginUser().getUser().getNickName();
        Date nowDate = new Date();
        addDsCrewEnterCheckReq
                .setStatus(EnterOutPortStatus.UN_CONFIRM.getCode())
                .setCreateBy(userName)
                .setCreateAt(nowDate)
                .setUpdateBy(userName)
                .setUpdateAt(nowDate);
        DsCrewEnterCheck dsCrewEnterCheck = new DsCrewEnterCheck();
        BeanUtils.copyBeanProp(dsCrewEnterCheck, addDsCrewEnterCheckReq);
        // 新增的船员不是本系统中船员时，新增系统中船员信息
        if (null == addDsCrewEnterCheckReq.getCrewId()) {
            // 新增船员信息
            DsBoatCrew dsBoatCrew = new DsBoatCrew();
            BeanUtils.copyBeanProp(dsBoatCrew, addDsCrewEnterCheckReq);

            dsBoatCrew
                    .setCertificateCode(addDsCrewEnterCheckReq.getCertificateNumber())
                    .setDelFlag(Constants.FLAG_FALSE)
                    .setBoatDutyName(addDsCrewEnterCheckReq.getPosition())
                    .setIdCardNo(addDsCrewEnterCheckReq.getIdCard())
                    .setPhone(addDsCrewEnterCheckReq.getTel())
                    .setCrewNamePy(PinyinUtil.getPinyin(addDsCrewEnterCheckReq.getCrewName(), " "))
                    // 性别 1男 2女  工具返回的 男的为1 女的为0
                    .setSex(1 == IdcardUtil.getGenderByIdCard(addDsCrewEnterCheckReq.getIdCard()) ? "1" : "2")
                    .setBirthday(IdcardUtil.getBirthDate(addDsCrewEnterCheckReq.getIdCard()))
                    .setAge(IdcardUtil.getAgeByIdCard(addDsCrewEnterCheckReq.getIdCard()));
            dsBoatCrewService.save(dsBoatCrew);
            dsCrewEnterCheck.setCrewId(dsBoatCrew.getId());
        }
//        // 校验是否在其他渔船上绑定           根据与移动端对接，亚超那边说先不考虑这种情况，可随意绑定船员
//        AddDsCrewCheckAndBindBoatReq dsBoatBindCrewByCrewId = baseMapper.getDsBoatBindCrewByCrewId(dsCrewEnterCheck.getCrewId());
//        if (Objects.nonNull(dsBoatBindCrewByCrewId)
//                && (!Objects.equals(addDsCrewEnterCheckReq.getDsBoatBindCrew().getBoatName1(), dsBoatBindCrewByCrewId.getBoatName1())
//                || !Objects.equals(addDsCrewEnterCheckReq.getDsBoatBindCrew().getBoatName1(), dsBoatBindCrewByCrewId.getBoatName2()))) {
//            // TODO: 此处暂时是拒绝的状态,后期讨论这边的处理方式
//            throw new RuntimeException("该船员已经绑定在其他渔船上，不能进行添加");
//        }
        if (!this.save(dsCrewEnterCheck)) {
            return false;
        }
        AddDsCrewCheckAndBindBoatReq addDsCrewCheckAndBindBoatReq = addDsCrewEnterCheckReq.getDsBoatBindCrew();
        addDsCrewCheckAndBindBoatReq
                .setCrewId(String.valueOf(dsCrewEnterCheck.getCrewId()))
                .setCrewName(addDsCrewEnterCheckReq.getCrewName())
                .setCrewIdcard(addDsCrewEnterCheckReq.getIdCard())
                .setBindTime(new Date())
                .setCrewPhone(addDsCrewEnterCheckReq.getTel())
                .setCrewPosition(addDsCrewEnterCheckReq.getPosition())
                .setDelFlag(Constants.FLAG_FALSE)
                .setCreateBy(userName)
                .setCreateAt(nowDate)
                .setUpdateBy(userName)
                .setUpdateAt(nowDate);
        // 组装渔船绑定船员信息
        if (!baseMapper.saveBoatBindCrew(addDsCrewCheckAndBindBoatReq)) {
            return false;
        }
        // 回显渔船进港绑定的船员的数据
        List<String> crewIdList = this.lambdaQuery()
                .eq(DsCrewEnterCheck::getEnterPortId, dsCrewEnterCheck.getEnterPortId())
                .list()
                .stream()
                .map(DsCrewEnterCheck::getCrewId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 添加当前 dsCrewEnterCheck 的 crewId，并确保不重复
        String currentCrewId = dsCrewEnterCheck.getCrewId();
        if (currentCrewId != null && !crewIdList.contains(currentCrewId)) {
            crewIdList.add(currentCrewId);
        }

        // 拼接成逗号分隔的字符串
        String crewIds = String.join(",", crewIdList);


        Map<String, Object> dsEnterPortMap = new HashMap<>();
        dsEnterPortMap.put("id", dsCrewEnterCheck.getEnterPortId());
        dsEnterPortMap.put("crewIds", crewIds);
        // 回显渔船进港提报表中绑定的船员的信息
        return baseMapper.updateDsEnterPort(dsEnterPortMap);
    }
}
