package com.sunxung.factoring.service.businessmanagement.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.ConstantConversionUtil;
import com.sunxung.factoring.component.util.StringUtil;
import com.sunxung.factoring.component.util.ThreadLocalUtil;
import com.sunxung.factoring.dict.impl.BusinessStageDict;
import com.sunxung.factoring.entity.businessmanagement.BusinessBasicInfo;
import com.sunxung.factoring.entity.businessmanagement.BusinessSupplierInfo;
import com.sunxung.factoring.entity.businessmanagement.vo.BusinessBasicInfoResultVo;
import com.sunxung.factoring.entity.customerinformation.Customer;
import com.sunxung.factoring.entity.project.vo.BusinessProcessingTaskVo;
import com.sunxung.factoring.entity.project.vo.SearchBusinessProcessingTask;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.entity.sys.*;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.entity.vo.ConditionVo;
import com.sunxung.factoring.mapper.businessManagement.BusinessBasicInfoMapper;
import com.sunxung.factoring.mapper.customerinformation.CustomerMapper;
import com.sunxung.factoring.service.businessmanagement.BusinessBasicInfoService;
import com.sunxung.factoring.service.businessmanagement.BusinessSupplierInfoService;
import com.sunxung.factoring.service.customerinformation.CustomerService;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.OrgService;
import com.sunxung.factoring.service.sys.PermissionService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Description : 业务基础信息service实现类
 * @Author : L.Jia
 * @Date: 2021-09-10 16:23
 */
@Service
public class BusinessBasicInfoServiceImpl extends ServiceImpl<BusinessBasicInfoMapper, BusinessBasicInfo>
        implements BusinessBasicInfoService {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private PlatformService platformService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrgService orgService;

    @Autowired
    private PermissionService permissionService;

    @Resource
    private CustomerMapper customerMapper;

    @Autowired
    private BusinessSupplierInfoService businessSupplierInfoService;

    @Autowired
    private DictionaryService dictService;

    @Autowired
    private SalesContractService salesContractService;


    @Override
    public BusinessBasicInfo get(Long id) {
        BusinessBasicInfo businessBasicInfo = baseMapper.selectById(id);
        return businessBasicInfo;
    }

    @Override
    public BusinessBasicInfo getByBusinessNumber(String businessNumber) {
        BusinessBasicInfo businessBasicInfo = baseMapper.selectOne(new QueryWrapper<BusinessBasicInfo>().eq("business_number", businessNumber));
        if (businessBasicInfo != null && businessBasicInfo.getEnterpriseCustomerInfoId() != null) {
            Customer customer = customerService.getById(businessBasicInfo.getEnterpriseCustomerInfoId());
            if (customer.getPhoneNumber() == null || "null".equals(customer.getPhoneNumber()) || "".equals(customer.getPhoneNumber())) {
                customer.setPhoneNumber("/");
            }
            businessBasicInfo.setCustomer(customer);
        }
        if (businessBasicInfo != null && businessBasicInfo.getTradingPlatformId() != null) {
            Platform platform = platformService.getById(businessBasicInfo.getTradingPlatformId());
            businessBasicInfo.setPlatform(platform);
        }
        return businessBasicInfo;
    }

    @Override
    public Page<BusinessBasicInfo> getBusinessList(ConditionVo conditionVo) {
//        获取当前用户
        User user = ThreadLocalUtil.getUser();
//        部门
        List<Long> orgIdList = user.getOrgIdList();
//        判断是否是供应商
        Boolean supplier = false;
        for (Long id : orgIdList) {
            if (id.equals(orgService.getByCode("supplier").getId())) {
                supplier = true;
            }
        }
        //如果是供应商  只让看见自己的业务
        if (supplier) {
            Customer customer = customerService.getOne(new QueryWrapper<Customer>().eq("enterprise_name", user.getName()).eq("supplier", true));
            List<BusinessSupplierInfo> businessSupplierInfos = businessSupplierInfoService.list(
                    new QueryWrapper<BusinessSupplierInfo>().eq("supplier_id", customer.getId()));
            Set businessBasicIds = new HashSet<>();
            for (BusinessSupplierInfo businessSupplierInfo : businessSupplierInfos) {
                businessBasicIds.add(businessSupplierInfo.getBusinessBasicInfoId());
            }
            Page<BusinessBasicInfo> page = PageHelper.startPage(conditionVo.getPage(), conditionVo.getRows());
            list(new QueryWrapper<BusinessBasicInfo>().in("id", businessBasicIds).orderByDesc(
                    "gmt_create"));
            return page;
        } else {
            List<Long> pers = permissionService.getPermissionIdByUserId(ThreadLocalUtil.getUserId());
            Permission per = permissionService.getByEname(ConstantConversionUtil.VIEW_ALL_BUSINESS);
            List<Long> userIds = findUserIds();
            Map map = new HashMap<>();
            String condition = conditionVo.getCondition();
            List<Customer> customers = new ArrayList<>();
            if (StringUtil.isNotEmpty(condition)) {
                customers = customerMapper.selectList(
                        new QueryWrapper<Customer>().like("enterprise_name", condition)
                );
            }
            List customerIds = new ArrayList();
            for (Customer customer : customers) {
                customerIds.add(customer.getId());
            }
            map.put("status", conditionVo.getStatus());
            map.put("condition", conditionVo.getCondition());
            map.put("startDate", conditionVo.getBeginTime());
            map.put("endDate", conditionVo.getEndTime());
            map.put("ids", userIds);
            map.put("customerIds", customerIds);
            if (per == null) {
                throw new ValidatorException(CodeUtil.FAIL, "数据可见-查看全员权限不能为空");
            }
            if (pers.contains(per.getId())
                    || ThreadLocalUtil.getUser().getLoginName().equals(ConstantConversionUtil.ADMINISTORIES)) {
                Page<BusinessBasicInfo> page = PageHelper.startPage(conditionVo.getPage(), conditionVo.getRows());
                baseMapper.selectBusinesAdmin(map);
                return page;
            } else {
                Page<BusinessBasicInfo> page = PageHelper.startPage(conditionVo.getPage(), conditionVo.getRows());
                baseMapper.getBusinessList(map);
                return page;
            }
        }
    }

    @Override
    public List<Long> findUserIds() {
        Long currentUserId = ThreadLocalUtil.getUserId();
        List<UserOrgRel> userOrgRelList = userService.findOrgRelByUserId(currentUserId);
        List<Long> userIdList = new ArrayList<>();
        for (UserOrgRel userOrgRel : userOrgRelList) {
            Org org = orgService.get(userOrgRel.getOrgId());
            if (org != null && org.getDeptNo().equals(ConstantConversionUtil.dept_no)) {
                break;
            } else {
                if (userOrgRel.isUserIdentity()) {
                    // 如果是部门负责人，获取部门下所有人员Id
                    List<Long> userIds = userService.findUserIdByOrgId(userOrgRel.getOrgId());
                    userIdList.addAll(userIds);
                } else {
                    userIdList.add(currentUserId);
                }
            }
        }
        return userIdList;
    }

    @Override
    public List<BusinessBasicInfoResultVo> getBusinessListByPurchaserId(Long customerId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("enterprise_customer_info_id", customerId);
        //选择买家对应未结束的业务
        List<BusinessBasicInfo> businessBasicInfoList = baseMapper.selectList(queryWrapper);
        List<BusinessBasicInfoResultVo> resultList = new ArrayList<>();
        for (BusinessBasicInfo businessBasicInfo : businessBasicInfoList) {
            BusinessBasicInfoResultVo obj = new BusinessBasicInfoResultVo();
            obj.setBusinessNumber(businessBasicInfo.getBusinessNumber());
            obj.setBusinessName(businessBasicInfo.getName());
            resultList.add(obj);
        }
        return resultList;
    }

    @Override
    public List<BusinessBasicInfo> getBusinessListByCustomer(Long userId, Long customerId) {
        return baseMapper.getBusinessListByCustomer(userId, customerId);
    }

    @Override
    public List<BusinessBasicInfo> getBusinessListByCustomerInvoice(Long userId, Long customerId) {
        return baseMapper.getBusinessListByCustomerInvoice(userId, customerId);
    }

    @Override
    public List<BusinessProcessingTaskVo> findMyCompletedList(SearchBusinessProcessingTask search) {
        List<BusinessProcessingTaskVo> rows = baseMapper.findMyCompletedList(search);
        rows.forEach(r->{
            List<BusinessSupplierInfo> supplierInfos = businessSupplierInfoService.lambdaQuery().eq(BusinessSupplierInfo::getBusinessBasicInfoId, r.getId()).list();
            String suppliersName = supplierInfos.stream().map(supplierInfo -> supplierInfo.getSupplierName()).collect(Collectors.joining(","));
            r.setSupplierName(suppliersName);
            if(StringUtil.isNotEmpty(r.getMode())){
                if(r.getMode().equals("1")){
                    r.setMode("保函");
                }else if (r.getMode().equals("0")) {
                    r.setMode("保证金");
                }
            }
            BusinessBasicInfo businessBasicInfo = get(r.getId());
            Dictionary status = dictService.get(businessBasicInfo.getStatusDic());
            Dictionary stage = dictService.get(businessBasicInfo.getStage());
            r.setStage(stage);
            r.setStatus(status);
            if(stage.getCode().equals(BusinessStageDict.ChildEnum.CREATE.getCode()) || stage.getCode().equals(BusinessStageDict.ChildEnum.GUARANTEE_MODE.getCode())
                    || stage.getCode().equals(BusinessStageDict.ChildEnum.AWARD.getCode()) || stage.getCode().equals(BusinessStageDict.ChildEnum.REFUND_DEPOSIT.getCode())){
                r.setExecutor(userService.get(businessBasicInfo.getManagerId()).getName());
            } else if(stage.getCode().equals(BusinessStageDict.ChildEnum.TEMPLATE_REVIEW.getCode())){
                r.setExecutor("法务专员");
            } else if(stage.getCode().equals(BusinessStageDict.ChildEnum.BOND_COLLECTION.getCode())){
                r.setExecutor("会计");
            }
            r.setDelete(false);
        });
        return rows;
    }

//    @Override
//    public List<BusinessProcessingTaskVo> findAllList(SearchBusinessProcessingTask search) {
//        List<BusinessProcessingTaskVo> rows = baseMapper.findAllList(search);
//        rows.forEach(r->{
//            List<BusinessSupplierInfo> supplierInfos = businessSupplierInfoService.lambdaQuery().eq(BusinessSupplierInfo::getBusinessBasicInfoId, r.getId()).list();
//            String suppliersName = supplierInfos.stream().map(supplierInfo -> supplierInfo.getSupplierName()).collect(Collectors.joining(","));
//            r.setSupplierName(suppliersName);
//            if(StringUtil.isNotEmpty(r.getMode())){
//                if(r.getMode().equals("1")){
//                    r.setMode("保函");
//                }else if (r.getMode().equals("0")) {
//                    r.setMode("保证金");
//                }
//            }
//            BusinessBasicInfo businessBasicInfo = get(r.getId());
//            Dictionary status = dictService.get(businessBasicInfo.getStatusDic());
//            Dictionary stage = dictService.get(businessBasicInfo.getStage());
//            r.setStage(stage);
//            r.setStatus(status);
//            if(stage.getCode().equals(BusinessStageDict.ChildEnum.CREATE.getCode()) || stage.getCode().equals(BusinessStageDict.ChildEnum.GUARANTEE_MODE.getCode())
//                    || stage.getCode().equals(BusinessStageDict.ChildEnum.AWARD.getCode()) || stage.getCode().equals(BusinessStageDict.ChildEnum.REFUND_DEPOSIT.getCode())){
//                r.setExecutor(userService.get(businessBasicInfo.getManagerId()).getName());
//            } else if(stage.getCode().equals(BusinessStageDict.ChildEnum.TEMPLATE_REVIEW.getCode())){
//                r.setExecutor("法务专员");
//            } else if(stage.getCode().equals(BusinessStageDict.ChildEnum.BOND_COLLECTION.getCode())){
//                r.setExecutor("会计");
//            }
//            if(stage.getCode().equals(BusinessStageDict.ChildEnum.CREATE.getCode())){
//                r.setDelete(true);
//            }else if(status.getCode().equals(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode()) &&
//                    stage.getCode().equals(BusinessStageDict.ChildEnum.EMPTY.getCode())){
//                SalesContractManagement salesContractManagement = salesContractService.getByBusinessNumber(businessBasicInfo.getBusinessNumber());
//                Dictionary dictionary = dictService.get(salesContractManagement.getContractStatus());
//                if(dictionary.getCode().equals(SalesContractStatusDict.ChildEnum.CREATE.getCode()) || dictionary.getCode().equals(SalesContractStatusDict.ChildEnum.OVERRULE.getCode())){
//                    r.setDelete(true);
//                }else {
//                    r.setDelete(false);
//                }
//            }else {
//                r.setDelete(false);
//            }
//
//            //是否展示下载文件按钮
//            r.setDownloadFileFlag(false);
//            if (ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode().equals(status.getCode()) ||
//                    ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode().equals(status.getCode())) {
//                r.setDownloadFileFlag(true);
//            }
//        });
//        return rows;
//    }

}
