package com.jeeplus.business.workContractInfo.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.jeeplus.business.workContractInfo.domain.JyContractParticipant;
import com.jeeplus.business.workContractInfo.domain.JyWorkContractInfo;
import com.jeeplus.business.workContractInfo.mapper.JyContractParticipantMapper;
import com.jeeplus.business.workContractInfo.mapper.JyWorkContractInfoMapper;
import com.jeeplus.business.workContractInfo.service.dto.JyWorkContractInfoDto;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.dto.WorkAttachmentInfoDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class JyWorkContractService {

    @Resource
    private JyWorkContractInfoMapper jyWorkContractInfoMapper;

    @Resource
    private JyContractParticipantMapper jyContractParticipantMapper;

    @Resource
    private IFlowableApi flowTaskService;

    public String saveInfo(JyWorkContractInfoDto workContractInfoDto) throws Exception {
        if (StringUtils.isNotEmpty(workContractInfoDto.getId())) {
            JyWorkContractInfo info = jyWorkContractInfoMapper.selectById(workContractInfoDto.getId());
            if (info != null) {
                return update(workContractInfoDto);
            }
        }
        return add(workContractInfoDto);
    }

    /**
     * 合同信息列表
     * @param
     * @return
     */
    public IPage<JyWorkContractInfo> list(Page<JyWorkContractInfo> page, QueryWrapper<JyWorkContractInfo> queryWrapper, String primaryLinkman, String[] contractDates, String[] createDates, String[] contractAmounts,String name,String createById,String filedType,String no,List contractTypeList) {
        queryWrapper.eq("a.del_flag","0");
        if (contractDates != null && contractDates.length>0) {
            queryWrapper.between("a.contract_date", contractDates[0], contractDates[1]);
        }
        if (createDates != null && createDates.length > 0) {
            queryWrapper.between("a.create_time", createDates[0], createDates[1]);
        }
        if (contractAmounts != null) {
            if (StringUtils.isNotEmpty(contractAmounts[0])) {
                queryWrapper.ge("a.contract_amount", Double.parseDouble(contractAmounts[0]));
            }
            if (contractAmounts.length>1 && StringUtils.isNotEmpty(contractAmounts[1])) {
                queryWrapper.le("a.contract_amount", Double.parseDouble(contractAmounts[1]));
            }
        }
        if (StringUtils.isNotEmpty(no)){
            queryWrapper.like("a.no",no);
        }
        if (StringUtils.isNotEmpty(filedType)) {
            queryWrapper.eq("a.filed_type", filedType);
        }
        if (StringUtils.isNotEmpty(primaryLinkman)) {
            queryWrapper.like("a.primary_linkman", primaryLinkman);
        }
        if (StringUtils.isNotEmpty(createById)) {
            queryWrapper.eq("a.create_by_id", createById);
        }
        if (null != contractTypeList && contractTypeList.size()>0) {
            if(contractTypeList.size() == 1){
                queryWrapper.eq("a.contract_type_first", contractTypeList.get(0));
            }else {
                queryWrapper.like("a.contract_type", contractTypeList.get(1));
            }
        }
        IPage<JyWorkContractInfo> pageList = jyWorkContractInfoMapper.findPageList(page, queryWrapper);
        pageList.getRecords().stream().forEach(i -> {
            // 合同归档
            if (StringUtils.isNotBlank(i.getTaskFiledId()) && StringUtils.isNotBlank(i.getFiledType())) {
                if ("2".equals(i.getFiledType())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsFiled(flowTaskService.getTaskAuditUsers(i.getTaskFiledId()));  // 获取数据审核人
                }
            }
            //合同类型查询
            StringBuffer stringBuffer = new StringBuffer();
            String typeData="";
            if (StringUtils.isNotEmpty(i.getContractTypeFirst())){
                 typeData = jyWorkContractInfoMapper.findType(i.getContractTypeFirst());
            }
            if (StringUtils.isNotEmpty(i.getContractType())){
                    String[] split = i.getContractType().split(",");
                    for (int j = 0; j < split.length; j++) {
                        String type= jyWorkContractInfoMapper.findType2(split[j]);
                        stringBuffer.append(type+",");
                        typeData=stringBuffer.substring(0,stringBuffer.lastIndexOf(","));
                    }
            }
            i.setContractType(typeData);
        });
        return pageList;
    }

    /**
     * 合同新增
     */
    @Transactional(rollbackFor = Exception.class)
    public String add(JyWorkContractInfoDto workContractInfoDto) throws Exception{
        JyWorkContractInfo info = new JyWorkContractInfo();

        String currentToken = TokenProvider.getCurrentToken();
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(currentToken);
        //合同编号生成
        List<List<String>> contractTypes = new ArrayList<>();
        String newType="";
        contractTypes = workContractInfoDto.getContractTypes();
        String contractNo="";
        StringBuffer sb = new StringBuffer();
        for (List<String> contractType : contractTypes) {
            if (contractType.size()>0){
                switch (contractType.get(0)){
                    case "1": //环境监测
                        contractNo=SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), JyWorkContractInfoDto.BIZ_CODE4,TokenProvider.getCurrentToken());
                        break;
                    case "2": //环境影响评价
                        contractNo=SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), JyWorkContractInfoDto.BIZ_CODE3,TokenProvider.getCurrentToken());
                        break;
                    case "3": //水土保持
                        contractNo=SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), JyWorkContractInfoDto.BIZ_CODE2,TokenProvider.getCurrentToken());
                        break;
                    case "4": //其他
                        contractNo=SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), JyWorkContractInfoDto.BIZ_CODE1,TokenProvider.getCurrentToken());
                        break;
                    default:
                        return null;
                }
            }
            //判断合同类型是否有二级
            if (contractType.size()>1){
                sb.append(contractType.get(1)+",");
                newType=sb.substring(0,sb.lastIndexOf(","));
            }
        }

        //生成id
        String id = UUID.randomUUID().toString().replace("-", "");

        BeanUtils.copyProperties(workContractInfoDto, info);

        info.setId(id); //id
        info.setNo(contractNo); //合同编号
        info.setCreateById(userDTO.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        info.setPrimaryLinkman(workContractInfoDto.getPrimaryLinkman()); //主委托人
        info.setContractAmount(workContractInfoDto.getContractAmount()); //金额
        info.setPaymentDescribe(workContractInfoDto.getPaymentDescribe()); //付款摘要
        info.setEffectiveDate(workContractInfoDto.getEffectiveDate()); //开始日期
        info.setClosingDate(workContractInfoDto.getClosingDate()); //结束日期
        info.setContractDate(workContractInfoDto.getContractDate()); //签订日期
        info.setContractType(newType);//合同类型(小类)
        info.setContractTypeFirst(contractTypes.get(0).get(0));
        info.setName(workContractInfoDto.getContractName()); //合同名称
        info.setContractOpposite(workContractInfoDto.getContractOpposite()); //对方合同编号
        info.setDepartment(workContractInfoDto.getDepartment());//所属部门
        info.setContractSpecial(workContractInfoDto.getContractSpecial()); //合同特别条款
        info.setRemarks(workContractInfoDto.getRemarks()); //备注
        jyWorkContractInfoMapper.insert(info);
        //获取委托方并添加至委托方表中
        JyContractParticipant participant = new JyContractParticipant();
        if (workContractInfoDto.getCwWorkClientContactDTOList() != null){
            if (workContractInfoDto.getCwWorkClientContactDTOList().size()>0){
                workContractInfoDto.getCwWorkClientContactDTOList().forEach(cw->{
                    String parId = UUID.randomUUID().toString().replace("-", "");
                    participant.setId(parId);
                    participant.setContractInfoId(id);
                    participant.setCustomerName(cw.getName());
                    participant.setCustomerNo(cw.getNumber());
                    participant.setCreateById(userDTO.getId());
                    participant.setCreateTime(workContractInfoDto.getCreateTime());
                    participant.setUpdateById(userDTO.getId());
                    participant.setUpdateTime(new Date());
                    jyContractParticipantMapper.insert(participant);
                });
            }
        }
        List<WorkAttachmentInfo> list = workContractInfoDto.getWorkAttachmentList();
        if (CollectionUtil.isNotEmpty(list)) {
            saveFiles(list, userDTO, id);
        }
        return id;
    }

    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(JyWorkContractInfoDto workContractInfoDto) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        JyWorkContractInfo info = new JyWorkContractInfo();
        BeanUtils.copyProperties(workContractInfoDto, info);
//        info.setNo(serialNum);
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        jyWorkContractInfoMapper.updateById(info);
        List<WorkAttachmentInfo> list = workContractInfoDto.getWorkAttachmentList();
//        if (CollectionUtil.isNotEmpty(list)) {
//            updateFiles(list, userDTO, workContractInfoDto.getId());
//        }
        updateFiles(list, userDTO, workContractInfoDto.getId());
        return workContractInfoDto.getId();
    }

    /**
     * 合同登记删除
     */
    public String removeById(String id) {
        jyWorkContractInfoMapper.deleteById(id);
        // 附件删除
//        LambdaQueryWrapper<WorkAttachment> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(WorkAttachment::getAttachmentId, id);
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
        return "删除完成!";
    }

    /**
     * 合同查询
     */
    public JyWorkContractInfoDto findById(String id) {
        JyWorkContractInfoDto dto = new JyWorkContractInfoDto();
        JyWorkContractInfo info = jyWorkContractInfoMapper.findById(id);
        if (info != null) {
            BeanUtils.copyProperties(info, dto);
            // 查询附件信息
            List<WorkAttachmentInfo> dtos = jyWorkContractInfoMapper.findDtos(id);
            if (CollectionUtil.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : dtos) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            dto.setWorkAttachmentList(dtos);
            dto.setContractName(info.getName());
            dto.setId(id); //id
            dto.setNo(info.getNo()); //合同编号
            dto.setCreateTime(info.getCreateTime());
            dto.setUpdateTime(info.getUpdateTime());
            dto.setPrimaryLinkman(info.getPrimaryLinkman()); //主委托人
            dto.setContractAmount(info.getContractAmount()); //金额
            dto.setPaymentDescribe(info.getPaymentDescribe()); //付款摘要
            dto.setEffectiveDate(info.getEffectiveDate()); //开始日期
            dto.setClosingDate(info.getClosingDate()); //结束日期
            dto.setContractDate(info.getContractDate()); //签订日期
            dto.setTaskId(info.getTaskId());
            dto.setDepartment(info.getDepartment());
            //获取委托人列表
            List<JyContractParticipant> list = new ArrayList<>();
            List<JyContractParticipant> byInfoId = jyContractParticipantMapper.findByInfoId(id);
            if (byInfoId.size()>0){
                byInfoId.forEach(cw->{
                    JyContractParticipant jyContractParticipant = new JyContractParticipant();
                    jyContractParticipant.setName(cw.getCustomerName());
                    jyContractParticipant.setNumber(cw.getCustomerNo());
                    list.add(jyContractParticipant);
                });
                dto.setCwWorkClientContactDTOList(list);
            }
            //合同类型查询
            StringBuffer stringBuffer = new StringBuffer();
            String newType="";
            List<String> stringList = new ArrayList<>();
            ArrayList<List<String>> jyWorkContractInfos = new ArrayList<>();
            if (!info.getContractType().contains(",")){
//                String type= jyWorkContractInfoMapper.findType(info.getContractType());
//                info.setContractType(type);
                stringList.add(info.getContractTypeFirst());
                stringList.add(info.getContractType());
                jyWorkContractInfos.add(stringList);
            }else {
                String[] split = info.getContractType().split(",");
                Integer count=0;
                //将切割好的二级类型进行遍历,与一级类型一起存放到数组中,方便前端级联回显
                for (String s : split) {
//                    String type= jyWorkContractInfoMapper.findType2(s);
//                    stringBuffer.append(type+",");
//                    newType=stringBuffer.substring(0,stringBuffer.lastIndexOf(","));
//                    info.setContractType(newType);
//                    stringList.add(info.getContractType());
                    //创建一个集合副本,为了避免每次新增时会在stringList中进行追加,从而造成回显失败
                    List<String> newList = new ArrayList<>(stringList);
                    newList.add(info.getContractTypeFirst());
                    newList.add(s);
                    //将集合副本存入到集合中,在前端取值进行回显
                    jyWorkContractInfos.add(count++,newList);
                }

            }

            List<String> result = Arrays.asList(dto.getContractType().split(","));
            dto.setContractTypeList(result);

//            jyWorkContractInfos.add(stringList);
            dto.setContractTypes(jyWorkContractInfos);
        }

        return dto;
    }

    /**
     * 根据id修改status
     */
    public void updateStatusById(JyWorkContractInfoDto workContractInfoDto) {
        jyWorkContractInfoMapper.updateStatusById(workContractInfoDto.getId(), workContractInfoDto.getFiledType());
    }

    /**
     * 保存附件信息
     * @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("jyWorkContract");
            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 saveFilesNew(List<WorkAttachmentInfoDTO> list, UserDTO userDTO, String id,String attachmentFlag) {
        int j = 1;
        for (WorkAttachmentInfoDTO 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(attachmentFlag);
            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 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 = jyWorkContractInfoMapper.findList(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 = jyWorkContractInfoMapper.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("jyWorkContract");
                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++;
            }
        }
    }



    /**
     * 根据客户id查询信息
     * @param clientId
     * @return
     */
    public List<JyWorkContractInfoDto> getInfoByClientId(String clientId) {
        List<JyWorkContractInfoDto> infoList = jyWorkContractInfoMapper.getInfoByClientId(clientId);
        if (null != infoList && infoList.size()>0) {
            for (JyWorkContractInfoDto info: infoList) {
                // 查询附件信息
                List<WorkAttachmentInfo> dtos = jyWorkContractInfoMapper.findDtos(info.getId());
                if (CollectionUtil.isNotEmpty(dtos)) {
                    for (WorkAttachmentInfo i : dtos) {
                        i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                    }
                }
            }
        }
        return infoList;
    }

    /**
     * 归档送审
     * @param workContractInfoDto
     * @return
     */
    public String saveContract(JyWorkContractInfoDto workContractInfoDto) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        JyWorkContractInfo info = jyWorkContractInfoMapper.findById(workContractInfoDto.getId());
//        info.setNo(serialNum);
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        if (userDTO.getOfficeDTO().getName().equals("办公室")){
            info.setFiledNo(workContractInfoDto.getFiledNo());
        }
        jyWorkContractInfoMapper.updateContractById(info.getUpdateById(),info.getUpdateTime(),workContractInfoDto.getFiledType(),info.getFiledNo(),workContractInfoDto.getId());
        return workContractInfoDto.getId();
    }

    public String deleteById(String id) {
        jyWorkContractInfoMapper.deleteById(id);
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
        return "合同删除成功";
    }
}
