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.core.domain.entity.SysUser;
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.AddDsCrewOutCheckReq;
import com.ltgk.crew.domain.entity.DsBoatCrew;
import com.ltgk.crew.domain.entity.DsCrewOutCheck;
import com.ltgk.crew.mapper.DsCrewEnterCheckMapper;
import com.ltgk.crew.mapper.DsCrewOutCheckMapper;
import com.ltgk.crew.service.IDsBoatCrewService;
import com.ltgk.crew.service.IDsCrewOutCheckService;
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 DsCrewOutCheckServiceImpl extends ServiceImpl<DsCrewOutCheckMapper, DsCrewOutCheck> implements IDsCrewOutCheckService {

    @Resource
    private IDsBoatCrewService dsBoatCrewService;
    @Resource
    private DsCrewEnterCheckMapper dsCrewEnterCheckMapper;

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

    /**
     * 新增出港船员报备信息
     * -- 1. 不可重复提交
     * -- 2. 新增的船员不是系统中的船员时，先添加系统中船员的数据
     * -- 3. 校验此船员是否绑定其他渔船，如果绑定其他渔船，则不可进行提交
     * -- 4. 新增渔船与船员绑定信息
     * -- 5. 新增船员审核信息
     *
     * @param addDsCrewOutCheckReq:
     * @return boolean
     * @author Qi ChengBin
     * @date 2025/1/2 15:54
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addDsCrewOutCheck(AddDsCrewOutCheckReq addDsCrewOutCheckReq) {
        // 校验是否已经提交审核
        DsCrewOutCheck dbDsCrewOutCheck = this.lambdaQuery()
                .eq(DsCrewOutCheck::getOutPortId, addDsCrewOutCheckReq.getOutPortId())
                .eq(null != addDsCrewOutCheckReq.getCrewId(), DsCrewOutCheck::getCrewId, addDsCrewOutCheckReq.getCrewId())
                .eq(DsCrewOutCheck::getCrewName, addDsCrewOutCheckReq.getCrewName())
                .one();
        if (Objects.nonNull(dbDsCrewOutCheck)) {
            throw new RuntimeException("船员‘" + addDsCrewOutCheckReq.getCrewName() + "'，已经提交审核，请不要重复提交！");
        }

        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userName = user.getNickName();
        Date nowDate = new Date();
        addDsCrewOutCheckReq
                .setStatus(EnterOutPortStatus.UN_CONFIRM.getCode())
                .setCreateBy(userName)
                .setCreateAt(nowDate)
                .setUpdateBy(userName)
                .setUpdateAt(nowDate);
        DsCrewOutCheck dsCrewOutCheck = new DsCrewOutCheck();
        BeanUtils.copyBeanProp(dsCrewOutCheck, addDsCrewOutCheckReq);
        // 新增的船员不是本系统中船员时，新增系统中船员信息
        if (null == addDsCrewOutCheckReq.getCrewId()) {
            // 新增船员信息
            DsBoatCrew dsBoatCrew = new DsBoatCrew();
            BeanUtils.copyBeanProp(dsBoatCrew, addDsCrewOutCheckReq);

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

        // 回显渔船出港绑定的船员的数据
        List<String> crewIdList = this.lambdaQuery()
                .eq(DsCrewOutCheck::getOutPortId, dsCrewOutCheck.getOutPortId())
                .list()
                .stream()
                .map(DsCrewOutCheck::getCrewId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

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

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


        Map<String, Object> dsOutPortMap = new HashMap<>();
        dsOutPortMap.put("id", dsCrewOutCheck.getOutPortId());
        dsOutPortMap.put("crewIds", crewIds);
        // 根据渔船出港主键，修改渔船出港申报表中绑定的船员主键信息
        return baseMapper.updateDsOutPort(dsOutPortMap);
    }
}
