package com.baichuanxin.openrestapi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baichuanxin.openrestapi.common.utils.DateUtil;
import com.baichuanxin.openrestapi.common.utils.FileHandleUtil;
import com.baichuanxin.openrestapi.common.utils.OnlineTaskUtil;
import com.baichuanxin.openrestapi.configs.OneTaskConfig;
import com.baichuanxin.openrestapi.dao.mapper.ChangeLegalPersonMapper;
import com.baichuanxin.openrestapi.dtos.AttachDto;
import com.baichuanxin.openrestapi.dtos.CertificateServiceDto;
import com.baichuanxin.openrestapi.dtos.ChangeLegalPersonDto;
import com.baichuanxin.openrestapi.dtos.FileDto;
import com.baichuanxin.openrestapi.entity.*;
import com.baichuanxin.openrestapi.service.NoticeService;
import com.baichuanxin.openrestapi.service.TaskInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *@Author duxiangyun
 *@Description 法人变更
 *@Date 2024/8/24
 */

@Slf4j
@Service
public class ChangeLegalPersonTaskInfoServiceImpl extends ServiceImpl<ChangeLegalPersonMapper,ChangeLegalPerson> implements TaskInfoService {

    @Autowired
    private OneTaskConfig oneTaskConfig;
    @Autowired
    private AttachTaskInfoServiceImpl attachTaskInfoService;
    @Autowired
    private ShareholderTaskInfoServiceImpl shareholderTaskInfoService;
    @Autowired
    private RegionCodeServiceImpl regionCodeService;
    @Autowired
    private NoticeServiceImpl noticeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveTaskInfo(Notice notice) {
        QueryWrapper<ChangeLegalPerson> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("taskId", notice.getTaskId());
        ChangeLegalPerson one = this.getOne(queryWrapper);
        if (one!=null){
          log.info("==数据已经存在:taskId:{}", notice.getTaskId());
            notice.setStatus(1);    //业务数据保存成功则修改办件通知表状态，修改为1 代表已收办件
            noticeService.updateNoticeOneByTaskId(notice);
          return false;
        }else {
            //获取业务数据
            Map<String, Object> formJson = notice.getFormJson();
            ChangeLegalPersonDto changeLegalPersonDto = JSON.parseObject(JSON.toJSONString(formJson), ChangeLegalPersonDto.class);
            ChangeLegalPerson changeLegalPerson = changeLegalPersonDto.convert(notice);
            //区域赋值
            RegionCode regionCode = regionCodeService.getRegionCode(changeLegalPersonDto.getItem_officePoliceAddress());
            changeLegalPerson.setItemOfficePoliceAddress(regionCode.getName());
            changeLegalPerson.setItemitemOfficePoliceAddressid(regionCode.getId());
            changeLegalPerson.setItemOfficePoliceidindex(regionCode.getIndexTree());
//            //编码转换成文字
//            changeLegalPerson.setItemNation(nationDicService.getValue(changeLegalPerson.getItemNation()));

            //保存业务数据到业务表
            boolean saveResult = this.save(changeLegalPerson);
            //保存其他业务数据
            boolean saveShare = shareholderTaskInfoService.saveOtherInfo(notice.getTaskId(),changeLegalPersonDto.getItem_shareholder(),changeLegalPerson.getId());
            //保存文件数据
            boolean saveFileDataResult = attachTaskInfoService.saveOtherInfo(notice,changeLegalPerson.getId());
            //保存文件到服务器
            List<AttachDto> attachList = notice.getAttachList();
            Map<String, List<AttachDto>> map = attachList.stream().collect(Collectors.groupingBy(AttachDto::getMaterialId));
            for (String key :map.keySet()){
                List<AttachDto> attachDtos = map.get(key);
                int i = 1 ;
                for (AttachDto attachDto : attachDtos) {
                    try {
                        FileHandleUtil.saveApplyFileHandle(StrUtil.join("",oneTaskConfig.getDownloadUrl(),attachDto.getAttachPath())
                                ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId(),i)
                                ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId(),i
                                        ,StrUtil.join(".",attachDto.getMaterialName(),attachDto.getAttachType())));
                        ++i;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }


//
//            for (AttachDto attachDto : attachList) {
//                try {
//                    FileHandleUtil.saveApplyFileHandle(StrUtil.join("",oneTaskConfig.getDownloadUrl(),attachDto.getAttachPath())
//                            ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId())
//                            ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId()
//                                    , StrUtil.join(".",attachDto.getMaterialName(),attachDto.getAttachType())));
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }





            if (saveFileDataResult&&saveResult&&saveShare){
                return true;
            }else {
                return false;
            }
        }
    }

    @Override
    public List<String> returnTaskResult(List<Notice> noticeList) {
        List<String> resultList = new ArrayList<>();

        //获取办件ID
        List<String>  taskIdList = new ArrayList<>();
        for (Notice notice : noticeList) {
            taskIdList.add(notice.getTaskId());
        }
        QueryWrapper<ChangeLegalPerson> queryWrapper  = new QueryWrapper<>();
        queryWrapper.in("taskId",taskIdList);
        queryWrapper.in("ITEM_AUDITSTATUS","0","1");
        List<ChangeLegalPerson> changeLegalPersonList = this.list(queryWrapper);
        for (ChangeLegalPerson changeLegalPerson : changeLegalPersonList) {
            Map<String,String> map = new HashMap<>();
            map.put("taskId",changeLegalPerson.getTaskId());
            map.put("userName","湖南省保安监管信息系统");
            map.put("eventName", OnlineTaskUtil.convertStatus(changeLegalPerson.getItemAuditStatus()));
            map.put("opinion",OnlineTaskUtil.convertStatus(OnlineTaskUtil.convertStatus(changeLegalPerson.getItemAuditStatus())));
            map.put("endTime", DateUtil.dateFormatter(changeLegalPerson.getItemOverTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("isdelivery",changeLegalPerson.getIsdelivery());
            log.info("发送审核结果");
            boolean b = OnlineTaskUtil.returnResult(JSON.toJSONString(map));
            log.info("发送结果物");
            if (changeLegalPerson.getItemAuditStatus().equals("0")){
                boolean result0 = this.sentResultFile(changeLegalPerson.getTaskId(), changeLegalPerson.getItemAcceptanceFile(), "0");
                if (b&&result0){
                    resultList.add(changeLegalPerson.getTaskId());
                }
            }else if (changeLegalPerson.getItemAuditStatus().equals("1")){
                boolean result=OnlineTaskUtil.returnResultFile(changeLegalPerson.getTaskId(),changeLegalPerson.getItemCompanyName(),
                        FileHandleUtil.fileHandle(
                                StrUtil.join("/",oneTaskConfig.getResultPackagePath(),
                                        StrUtil.join(".",changeLegalPerson.getTaskId(),"zip"))),
                        "2");
                if (b&&result){
                    resultList.add(changeLegalPerson.getTaskId());
                }
            }
        }
        return resultList;
    }
    public boolean sentResultFile(String taskID,String  fileListString,String needFeedBack) {
        List<FileDto> fileDtos = JSON.parseArray(fileListString, FileDto.class);
        boolean resultNoticeFile = false;
        for (FileDto fileDto : fileDtos) {
            resultNoticeFile = OnlineTaskUtil.returnResultFile(taskID
                    , fileDto.getName()
                    , FileHandleUtil.fileHandle(FileHandleUtil.strHandle(oneTaskConfig.getResultFilePath(), fileDto.getPath()))
                    , needFeedBack);
        }
        return resultNoticeFile ;
    }

    //电子证照相关查询
    /***
     *@Author duxiangyun
     *@Description   获取审核通过但未制作证书的数据===法人变更
     *@Date 2024/11/13
     */
    public List<ChangeLegalPerson> getUnGetEC(){
        QueryWrapper<ChangeLegalPerson> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ITEM_AUDITSTATUS","1");  //审核通过且获取信用代码的数据
        queryWrapper.eq("licenseStatus","0");
        queryWrapper.isNotNull("ITEM_USCC");
        List<ChangeLegalPerson> changeLegalPersonList = this.list(queryWrapper);
        return  changeLegalPersonList;
    }

    /***
     *@Author duxiangyun
     *@Description
     *@Date 2024/11/13
     */
    public  boolean updateStatusAndfile(String id,String status,String filePath){
        UpdateWrapper<ChangeLegalPerson> changeLegalPersonUpdateWrapper = new UpdateWrapper<>();
        changeLegalPersonUpdateWrapper.set("licenseStatus",status);
        changeLegalPersonUpdateWrapper.set("item_service_file",filePath);
        changeLegalPersonUpdateWrapper.eq("id",id);
        boolean updateStatus = this.update(changeLegalPersonUpdateWrapper);
        return updateStatus;
    }

    public  boolean updateLicenseStatus(String id,String status){
        UpdateWrapper<ChangeLegalPerson> changeWrapper = new UpdateWrapper<>();
        changeWrapper.eq("id",id);
        changeWrapper.set("licenseStatus",status);
        boolean updateStatus = this.update(changeWrapper);
        return updateStatus;
    }

    /***
     *@Author duxiangyun
     *@Description 接收用户回执后更新数据
     *@Date 2024/11/18
     */

    public boolean updateByFeedBack(String taskId,String filePath){
        UpdateWrapper<ChangeLegalPerson> changeLegalPersonUpdateWrapper =new UpdateWrapper<>();
        changeLegalPersonUpdateWrapper.eq("taskId",taskId);

        changeLegalPersonUpdateWrapper.set("item_notice_state","已签收");
        changeLegalPersonUpdateWrapper.set("item_reach_state","已签收");
        changeLegalPersonUpdateWrapper.set("item_service_state","已签收");
        changeLegalPersonUpdateWrapper.set("item_completion_state","已签收");
        changeLegalPersonUpdateWrapper.set("ITEM_ENTERPRISE_COMPLETION_FILE",filePath);
        changeLegalPersonUpdateWrapper.set("ITEM_ENTERPRISE_REACH_FILE",filePath);
        boolean status = this.update(changeLegalPersonUpdateWrapper);
        return status;
    }

}
