package com.jeeplus.business.project.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.assess.program.configuration.projectList.domain.*;
import com.jeeplus.assess.program.configuration.projectList.service.dto.ProgramReportNoDto;
import com.jeeplus.assess.program.configuration.projectList.service.dto.ProjectListDto;
import com.jeeplus.assess.workContract.domain.WorkContractInfo;
import com.jeeplus.assess.workContract.service.WorkContractService;
import com.jeeplus.assess.workContract.service.dto.WorkContractInfoDto;
import com.jeeplus.business.project.domain.JyProject;
import com.jeeplus.business.project.domain.JyProjectMembers;
import com.jeeplus.business.project.mapper.JyProjectMapper;
import com.jeeplus.business.project.mapper.JyProjectMemberMapper;
import com.jeeplus.business.project.service.dto.JyProjectDTO;
import com.jeeplus.business.workClientInfo.domain.JyWorkClientLinkman;
import com.jeeplus.business.workClientInfo.mapper.JyWorkClientInfoMapper;
import com.jeeplus.business.workClientInfo.mapper.JyWorkClientLinkmanMapper;
import com.jeeplus.business.workContractInfo.domain.JyWorkContractInfo;
import com.jeeplus.business.workContractInfo.mapper.JyWorkContractInfoMapper;
import com.jeeplus.business.workContractInfo.service.JyWorkContractService;
import com.jeeplus.business.workContractInfo.service.dto.JyWorkContractInfoDto;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.DictValue;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.mapper.DictValueMapper;
import com.jeeplus.sys.service.DictValueService;
import com.jeeplus.sys.service.dto.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class JyProjectService {

    @Autowired
    private JyProjectMapper jyProjectMapper;

    @Autowired
    private IFlowableApi flowTaskService;

    @Autowired
    private JyWorkContractInfoMapper jyWorkContractInfoMapper;

    @Autowired
    private JyWorkClientInfoMapper jyWorkClientInfoMapper;

    @Autowired
    private JyProjectMemberMapper jyProjectMemberMapper;


    @Autowired
    private JyWorkClientLinkmanMapper jyWorkClientLinkmanMapper;

    @Autowired
    private JyWorkContractService jyWorkContractService;

    @Autowired
    private DictValueMapper dictValueMapper;


    /**
     * 项目登记列表
     * @param page
     * @param info
     * @return
     */
    public IPage<JyProject> list(Page<JyProject> page, JyProject info) throws Exception {
        QueryWrapper<JyProject> wrapper = QueryWrapperGenerator.buildQueryCondition(info, JyProject.class);
        if (ObjectUtil.isNotEmpty(info) && StringUtils.isNotBlank(info.getCreateById())) {
            wrapper.eq("a.create_by_id", info.getCreateById());
        }
        wrapper.eq("a.del_flag", "0");
        //创建时间
        if (info.getCreateDates() != null && info.getCreateDates().length > 0) {
            wrapper.between("a.create_time", info.getCreateDates()[0], info.getCreateDates()[1]);
        }
        //一审状态
        if (StringUtils.isNotBlank(info.getFirstInstanceStatus())){
            wrapper.eq("a.first_instance_status", info.getFirstInstanceStatus());
        }
        //二审状态
        if (StringUtils.isNotBlank(info.getSecondInstanceStatus())){
            wrapper.eq("a.second_instance_status", info.getSecondInstanceStatus());
        }
        //三审状态
        if (StringUtils.isNotBlank(info.getThirdInstanceStatus())){
            wrapper.eq("a.third_instance_status", info.getThirdInstanceStatus());
        }
        //项目编号
        if (StringUtils.isNotBlank(info.getNo())){
            wrapper.like("a.no",info.getNo());
        }
        //项目名称
        if (StringUtils.isNotBlank(info.getName())){
            wrapper.like("a.name",info.getName());
        }
        //项目负责人
        if (StringUtils.isNotBlank(info.getProjectLeader())){
            wrapper.like("a.project_leader",info.getProjectLeader());
        }
        //合同名称
        if (StringUtils.isNotBlank(info.getContractName())){
            wrapper.like("a.contract_name",info.getContractName());
        }
        //委托方
        if (StringUtils.isNotBlank(info.getClientName())){
            wrapper.like("a.client_name",info.getClientName());
        }
        //登记状态
        if (StringUtils.isNotBlank(info.getStatus())){
            wrapper.eq("a.status", info.getStatus());
        }
        //报告签发
        if (StringUtils.isNotBlank(info.getReportIssuance())){
            wrapper.eq("a.report_issuance", info.getReportIssuance());
        }
        //外审
        if (StringUtils.isNotBlank(info.getOutIssuance())){
            wrapper.eq("a.out_issuance", info.getOutIssuance());
        }
        //报批签发
        if (StringUtils.isNotBlank(info.getReportSubmit())){
            wrapper.eq("a.report_submit", info.getReportSubmit());
        }
        //归档状态
        if (StringUtils.isNotBlank(info.getReviewStatus())){
            wrapper.eq("a.review_status", info.getReviewStatus());
        }
        IPage<JyProject> pageList = jyProjectMapper.findPageList(page, wrapper);
        pageList.getRecords().stream().forEach(item ->{
            // 项目登记
            if (StringUtils.isNotBlank(item.getTaskId()) && StringUtils.isNotBlank(item.getStatus())) {
                if ("2".equals(item.getStatus())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIds(flowTaskService.getTaskAuditUsers(item.getTaskId()));  // 获取数据审核人
                }
            }
            //合同名称
            if (StringUtils.isEmpty(item.getContractName())){
                item.setContractName("暂无合同");
            }
        });
        return pageList;
    }

    /**
     * 查询当前登录人所属项目组的项目
     * @return
     */
    public ResponseEntity<List<String>> getHaveProjectIds() {
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        return ResponseEntity.ok(jyProjectMapper.getHaveProjectIds(userDTO));
    }

    public IPage<JyWorkContractInfo> findContractPageList(JyWorkContractInfoDto dto, Page<JyWorkContractInfo> page) {
        IPage<JyWorkContractInfo> contractPageList = jyProjectMapper.findContractPageList(page, dto);
        contractPageList.getRecords().stream().forEach(i->{
        //合同类型查询
        StringBuffer stringBuffer = new StringBuffer();
        String newType="";
        if (StringUtils.isNotEmpty(i.getContractType())){
            if (!i.getContractType().contains(",")){
                String type= jyWorkContractInfoMapper.findType(i.getContractType());
                i.setContractType(type);
            }else {
                String[] split = i.getContractType().split(",");
                for (String s : split) {
                    String type= jyWorkContractInfoMapper.findType2(s);
                    stringBuffer.append(type+",");
                    newType=stringBuffer.substring(0,stringBuffer.lastIndexOf(","));
                    i.setContractType(newType);
                }
            }
        }
        //主委托方联系人信息查询
            List<JyWorkClientLinkman> jyWorkClientLinkmen=jyWorkClientInfoMapper.getByNameInfo(i.getLinkmanId());
            i.setLinkmanList(jyWorkClientLinkmen);
        });

        return contractPageList;
    }

    /**
     * 项目保存或修改
     * @param dto
     * @return
     * @throws Exception
     */
    public String save(JyProjectDTO  dto) throws Exception{
        if (StringUtils.isNotEmpty(dto.getId())) {
            return update(dto);
        }
        return add(dto);
    }


    public String add(JyProjectDTO dto) throws Exception{
        String currentToken = TokenProvider.getCurrentToken();
        JyProject jyProject = new JyProject();
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        // 保存项目管理列表信息
        BeanUtils.copyProperties(dto, jyProject);
        String projectNo = "";

        String id = UUID.randomUUID().toString().replace("-", "");
        //生成项目编号
        if (dto.getContractStatus().equals("0")){
            projectNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), JyProjectDTO.BIZ_CODE,currentToken);
        }else {
            JyWorkContractInfo byId = jyWorkContractInfoMapper.findById(dto.getContractId());
            Integer projectNum=jyProjectMapper.getProByContractId(dto.getContractId());
            Integer count=0;
            if (projectNum == 0){
                projectNo=byId.getNo()+"-0"+(count+1);
            }else {
                projectNo=byId.getNo()+"-0"+(projectNum+1);
            }
        }
        jyProject.setId(id);//生成主键id
        jyProject.setName(dto.getName());//项目名称
        if (dto.getContractStatus().equals("0")){
            jyProject.setContractName("");//合同名称
        }else {
            jyProject.setContractName(dto.getContractName());//合同名称
        }
        jyProject.setNo(projectNo); //项目编号
        jyProject.setContractId(dto.getContractId()); //合同编号
        List<JyWorkClientLinkman> clientList = dto.getClientList();
        for (JyWorkClientLinkman jyWorkClientLinkman : clientList) {
            jyProject.setClient(jyWorkClientLinkman.getId());//联系人id
            jyProject.setClientName(jyWorkClientLinkman.getName());//联系人姓名
        }
        jyProject.setProjectLeader(dto.getProjectLeader());//项目负责人
        jyProject.setProjectPlace(dto.getProjectPlace());//项目所在地
        jyProject.setStatus(dto.getStatus());
        jyProject.setDelFlag(0);
        jyProject.setContractStatus(dto.getContractStatus());//合同情况
        jyProject.setSpecial(dto.getSpecial());//特殊要求
        jyProject.setProjectOverview(dto.getProjectOverview());//工程概况
        jyProject.setBuildPlace(dto.getBuildPlace());//建设地点
        jyProjectMapper.insert(jyProject);
        //保存项目组成员


        List<String> strings = new ArrayList<>();
        strings.add(userDTO.getId());
        strings.add(dto.getProjectLeader());
        for (String string : strings) {
            JyProjectMembers jyProjectMembers = new JyProjectMembers();
            String memberId = UUID.randomUUID().toString().replace("-", "");
            jyProjectMembers.setId(memberId);
            jyProjectMembers.setCreateById(userDTO.getId());
            jyProjectMembers.setCreateTime(new Date());
            jyProjectMembers.setUpdateById(userDTO.getId());
            jyProjectMembers.setUpdateTime(new Date());
            jyProjectMembers.setProjectId(id);
            jyProjectMembers.setUserId(string);
            jyProjectMemberMapper.insert(jyProjectMembers);
        }


        // 保存附件信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            saveFiles(dto.getFiles(), userDTO, id);
        }
        return id;
    }

    public String update(JyProjectDTO dto) throws Exception{
        String currentToken = TokenProvider.getCurrentToken();
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        // 修改项目管理列表主表信息
        JyProject jyProject = new JyProject();
        BeanUtils.copyProperties(dto, jyProject);
        jyProject.setUpdateById(userDTO.getId());
        jyProject.setUpdateTime(new Date());
        jyProject.setDelFlag(0);
        jyProjectMapper.updateById(jyProject);
        // 修改附件信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            updateFiles(dto.getFiles(), userDTO, dto.getId());
        }
        return dto.getId();
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (WorkAttachmentInfo dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = jyProjectMapper.findFileList(id);
        if (CollectionUtil.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (WorkAttachmentInfo dto : list) {
            //判断是否存在
            Integer isExit = jyProjectMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                i.setCreateTime(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateTime(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(dto.getName().split("\\."));
                if (CollectionUtil.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("workcontract");
                i.setFileSize(dto.getSize());
                i.setSort(j);
                Map<String,String> map = new HashMap<>();
                String workAttachment = JSON.toJSONString((i));
                String userDTOInfo = JSON.toJSONString((userDTO));
                map.put("workAttachment",workAttachment);
                map.put("userDTO",userDTOInfo);
                SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
                j++;
            }
        }
    }

    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        for (WorkAttachmentInfo dto : list) {
            WorkAttachmentInfo i = new WorkAttachmentInfo();
            //包含了url、size、name
            i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateTime(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateTime(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            List<String> strings = Arrays.asList(dto.getName().split("\\."));
            if (CollectionUtil.isNotEmpty(strings)) {
                i.setType(strings.get(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("workcontract");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            Map<String,String> map = new HashMap<>();
            String workAttachment = JSON.toJSONString((i));
            String userDTOInfo = JSON.toJSONString((userDTO));
            map.put("workAttachment",workAttachment);
            map.put("userDTO",userDTOInfo);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
            j++;
        }
    }

    public JyProjectDTO findById(String id) {
        JyProjectDTO jyProjectDTO = new JyProjectDTO();
        // 查询主表信息
        JyProject info = jyProjectMapper.getById(id);
        //保存项目信息
        BeanUtils.copyProperties(info, jyProjectDTO);
        // 查询联系人列表
        ArrayList<JyWorkClientLinkman> jyWorkClientLinkmen = new ArrayList<>();
        JyWorkClientLinkman jyWorkClientLinkman = jyWorkClientLinkmanMapper.selectById(info.getClient());
        if (ObjectUtil.isNotEmpty(jyWorkClientLinkman)){
            jyWorkClientLinkmen.add(jyWorkClientLinkman);
            jyProjectDTO.setClientList(jyWorkClientLinkmen);
        }
        // 查询成员列表
        LambdaQueryWrapper<JyProjectMembers> memberWrapper = new LambdaQueryWrapper<>();
        memberWrapper.eq(JyProjectMembers::getProjectId, id);
        memberWrapper.eq(JyProjectMembers::getDelFlag, 0);
        List<JyProjectMembers> members = jyProjectMemberMapper.selectList(memberWrapper);
        if (CollectionUtils.isNotEmpty(members)) {
            members.stream().forEach(member -> {
                if (StringUtils.isNotBlank(member.getUserId())) {
                    UserDTO byId = SpringUtil.getBean ( IUserApi.class ).getById(member.getUserId());
                    if (ObjectUtil.isNotEmpty(byId)) {
                        member.setName(byId.getName());
                    }
                }
            });
            jyProjectDTO.setProjectMembers(members);
        }
        //合同类型查询
        String type="";
        if (!info.getContractType().contains(",")){
            jyProjectDTO.setContractType(info.getContractType());
        }else {
            String[] split = info.getContractType().split(",");
            for (String s : split) {
                DictValue dictValue = dictValueMapper.selectById(s);
                type=dictValue.getLabel()+",";
                jyProjectDTO.setContractType(type);
            }
        }


        // 查询附件信息
        List<WorkAttachmentInfo> files = jyWorkContractInfoMapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            for (WorkAttachmentInfo i : files) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            jyProjectDTO.setFiles(files);
        }
        return jyProjectDTO;
    }


    /**
     * 根据id修改status
     */
    public void updateStatusById(JyProjectDTO jyProjectDTO) {
        jyProjectMapper.updateStatusById(jyProjectDTO.getId(), jyProjectDTO.getStatus());
    }


    public String deleteById(String id) {
        jyProjectMapper.deleteById(id);
        jyProjectMemberMapper.deleteByInfoId(id);
        // 附件删除
//        LambdaQueryWrapper<WorkAttachmentInfo> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(WorkAttachmentInfo::getAttachmentId, id);
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
        return "删除项目成功";
    }


}
