package com.bonus.material.purchase.service.impl;

import java.util.List;
import java.util.Objects;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.ah.sbd.SmsTool;
import com.ah.sbd.utils.param.BatchSmsByContentParam;
import com.ah.sbd.utils.param.SmsParam;
import com.bonus.common.biz.constant.BmConfigItems;
import com.bonus.common.biz.enums.PurchaseTaskStatusEnum;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.utils.sms.SmsUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.countersign.domain.SignProcessVo;
import com.bonus.material.countersign.mapper.SignProcessMapper;
import com.bonus.material.part.mapper.PartCheckMapper;
import com.bonus.material.purchase.domain.PurchaseSignRecord;
import com.bonus.material.purchase.domain.dto.PurchaseNoticePersonDto;
import com.bonus.material.task.domain.TmTask;
import com.bonus.material.task.mapper.TmTaskMapper;
import org.springframework.stereotype.Service;
import com.bonus.material.purchase.mapper.PurchaseNoticePersonMapper;
import com.bonus.material.purchase.domain.PurchaseNoticePerson;
import com.bonus.material.purchase.service.IPurchaseNoticePersonService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 新购短信通知人员Service业务层处理
 * 
 * @author xsheng
 * @date 2024-10-16
 */
@Service
public class PurchaseNoticePersonServiceImpl implements IPurchaseNoticePersonService {

    @Resource
    private PurchaseNoticePersonMapper purchaseNoticePersonMapper;

    @Resource
    private TmTaskMapper tmTaskMapper;

    @Resource
    private PurchaseCheckDetailsServiceImpl purchaseCheckDetailsService;

    @Resource
    private PartCheckMapper partCheckMapper;

    @Resource
    private SignProcessMapper signProcessMapper;

    /**
     * 查询新购短信通知人员
     * 
     * @param id 新购短信通知人员主键
     * @return 新购短信通知人员
     */
    @Override
    public PurchaseNoticePerson selectPurchaseNoticePersonById(Long id) {
        return purchaseNoticePersonMapper.selectPurchaseNoticePersonById(id);
    }

    /**
     * 查询新购短信通知人员列表
     * 
     * @param purchaseNoticePerson 新购短信通知人员
     * @return 新购短信通知人员
     */
    @Override
    public List<PurchaseNoticePerson> selectPurchaseNoticePersonList(PurchaseNoticePerson purchaseNoticePerson) {
        List<PurchaseNoticePerson> list = purchaseNoticePersonMapper.selectPurchaseNoticePersonList(purchaseNoticePerson);
        list.removeIf(Objects::isNull);
        list.forEach(item -> {
            if (null != item.getTelphone() && 11 < item.getTelphone().length()) {
                item.setTelphone(Sm4Utils.decrypt(item.getTelphone()));
            }
        });
        return list;
    }

    /**
     * 查询等待选择的新购短信通知人员列表
     *
     * @return 等待选择的新购短信通知人员列表
     */
    @Override
    public List<PurchaseNoticePerson> getUnSelectedUserList(PurchaseNoticePerson purchaseNoticePerson) {
        List<PurchaseNoticePerson> userList = purchaseNoticePersonMapper.getUnSelectedUserList(purchaseNoticePerson);
        for (PurchaseNoticePerson user : userList) {
            if (null != user.getTelphone() && 11 < user.getTelphone().length()) {
                user.setTelphone(Sm4Utils.decrypt(user.getTelphone()));
            }
        }
        return userList;
    }

    @Override
    @Transactional
    public AjaxResult batchSendSms(PurchaseNoticePersonDto purchaseNoticePersonDto) {
        for (int i = 0; i < purchaseNoticePersonDto.getPhoneNumbers().size(); i++) {
            String phoneNumber = purchaseNoticePersonDto.getPhoneNumbers().get(i);
            if (phoneNumber != null && phoneNumber.length() != 11) {
                String decrypted = Sm4Utils.decrypt(phoneNumber);
                purchaseNoticePersonDto.getPhoneNumbers().set(i, decrypted);
            }
        }
//        String splitPhoneNumber = String.join(",", purchaseNoticePersonDto.getPhoneNumbers());
        List<String> mobileList = purchaseNoticePersonDto.getPhoneNumbers();
        try {
            // 省公司短信发送
            JSONObject sendResult = SmsTool.sendSms(new BatchSmsByContentParam(mobileList, purchaseNoticePersonDto.getContent()), BmConfigItems.ANHUI_COMPANY_SMS_KEY);
            //String sendResult = SmsUtils.smsToken(splitPhoneNumber, purchaseNoticePersonDto.getContent(),"");
            if (sendResult != null) {
                // 发送短信后修改任务状态
                if (purchaseNoticePersonDto.getIsPartFlag() != null && purchaseNoticePersonDto.getIsPartFlag() == 0) {
                    tmTaskMapper.updateTmTask(new TmTask()
                            .setTaskId(purchaseNoticePersonDto.getTaskId())
                            .setTaskType(TmTaskTypeEnum.TM_TASK_PART_TYPE.getTaskTypeId())
                            .setTaskStatus(PurchaseTaskStatusEnum.TO_CHECK.getStatus())
                    );
                    // 修改配件采购明细的任务状态
                    partCheckMapper.batchUpdateDetailsTaskStatus(purchaseNoticePersonDto.getTaskId(), PurchaseTaskStatusEnum.TO_CHECK.getStatus(), "");
                } else {
                    tmTaskMapper.updateTmTask(new TmTask()
                            .setTaskId(purchaseNoticePersonDto.getTaskId())
                            .setTaskType(TmTaskTypeEnum.TM_TASK_PURCHASE.getTaskTypeId())
                            .setTaskStatus(PurchaseTaskStatusEnum.TASK_IN_PROGRESS.getStatus())
                    );
                    // 修改采购明细的任务状态
                    purchaseCheckDetailsService.batchUpdateDetailsTaskStatus(purchaseNoticePersonDto.getTaskId(), PurchaseTaskStatusEnum.TO_CHECK.getStatus(), "");
                }
                // 发送验收通知，供应科默认验收通过，将数据存入验收记录表
                List<SignProcessVo> signProcessVoList = signProcessMapper.getList(new SignProcessVo());
                Long loginUserDeptId = null;
                if (CollectionUtil.isNotEmpty(signProcessVoList)) {
                    for (SignProcessVo signProcessVo : signProcessVoList) {
                        if ("供应科".equals(signProcessVo.getOrgName())) {
                            loginUserDeptId = signProcessVo.getOrgId();
                        }
                    }
                }
                PurchaseSignRecord purchaseSignRecord = new PurchaseSignRecord();
                purchaseSignRecord.setTaskId(purchaseNoticePersonDto.getTaskId());
                purchaseSignRecord.setUserId(SecurityUtils.getLoginUser().getUserid());
                purchaseSignRecord.setOrgId(loginUserDeptId);
                // 审核通过
                purchaseSignRecord.setAuditStatus("1");
                purchaseSignRecord.setCreateTime(DateUtils.getNowDate());
                int addPurchaseSignResult = signProcessMapper.insertPurchaseSignRecord(purchaseSignRecord);
                if (addPurchaseSignResult < 1) {
                    return AjaxResult.error("插入验收通知表数据失败");
                }
                return AjaxResult.success("短信发送成功:" + sendResult);
            } else {
                return AjaxResult.error("短信发送失败,发送结果为空");
            }
        } catch (Exception e) {
            // 抛出异常，执行事务回滚
            throw new RuntimeException("短信发送异常:" + e.getMessage());
        }
    }

    /**
     * 新增新购短信通知人员
     * 
     * @param purchaseNoticePerson 新购短信通知人员
     * @return 结果
     */
    @Override
    public int insertPurchaseNoticePerson(PurchaseNoticePerson purchaseNoticePerson) {
        purchaseNoticePerson.setCreateTime(DateUtils.getNowDate());
        try {
            return purchaseNoticePersonMapper.insertPurchaseNoticePerson(purchaseNoticePerson);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 批量新增新购短信通知人员
     *
     * @param purchaseNoticePersonList 新购短信通知人员集合
     * @return 结果
     */
    @Override
    public int insertBatchPurchaseNoticePerson(List<PurchaseNoticePerson> purchaseNoticePersonList) {
        try {
            return purchaseNoticePersonMapper.insertBatchPurchaseNoticePerson(purchaseNoticePersonList);
        } catch (Exception e) {
            throw new RuntimeException("批量新增执行SQL错误:" + e.getMessage());
        }
    }

    /**
     * 修改新购短信通知人员
     * 
     * @param purchaseNoticePerson 新购短信通知人员
     * @return 结果
     */
    @Override
    public int updatePurchaseNoticePerson(PurchaseNoticePerson purchaseNoticePerson) {
        purchaseNoticePerson.setUpdateTime(DateUtils.getNowDate());
        try {
            return purchaseNoticePersonMapper.updatePurchaseNoticePerson(purchaseNoticePerson);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 批量删除新购短信通知人员
     * 
     * @param ids 需要删除的新购短信通知人员主键
     * @return 结果
     */
    @Override
    public int deletePurchaseNoticePersonByIds(Long[] ids) {
        return purchaseNoticePersonMapper.deletePurchaseNoticePersonByIds(ids);
    }

    /**
     * 删除新购短信通知人员信息
     * 
     * @param id 新购短信通知人员主键
     * @return 结果
     */
    @Override
    public int deletePurchaseNoticePersonById(Long id) {
        return purchaseNoticePersonMapper.deletePurchaseNoticePersonById(id);
    }
}
