package com.zfire.mall.manager.datasource.engin.logic;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.datasource.engin.entity.AgencyBills;
import com.zfire.mall.manager.datasource.engin.entity.AgencyBillsBean;
import com.zfire.mall.manager.datasource.engin.entity.SysUser;
import com.zfire.mall.manager.datasource.engin.mapper.AgencyBillsMapper;
import com.zfire.mall.manager.datasource.engin.mapper.SysUserMapper;
import com.zfire.mall.manager.datasource.engin.service.AgenyBillsService;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.plus.entity.DepositManage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class AgencyBillsLogic {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    AgenyBillsService agenyBillsService;
    @Resource
    AgencyBillsMapper agencyBillsMapper;

    @DS("engin")
    public IPage<AgencyBills> queryAllowAgencyBills(String userName, String recordNo, String projectName, String useUnit,
                                                    Integer pageNum, Integer pageSize) {
        List<Integer> subOrganizationList = this.validUser(userName);

//        return agenyBillsService.lambdaQuery()
//                .in(AgencyBills::getOrganizationid, new HashSet<>(subOrganizationList))
//                .like(StringUtils.isNotEmpty(recordNo), AgencyBills::getRecordNo, recordNo)
//                .like(StringUtils.isNotEmpty(projectName), AgencyBills::getProjectName, projectName)
//                .like(StringUtils.isNotEmpty(useUnit), AgencyBills::getUseUnit, useUnit)
//
//                .and(v -> v.eq(AgencyBills::getProjectStatus, "跟进")
//                        .or(vl -> vl.eq(AgencyBills::getProjectStatus, "签单")
//                                .eq(AgencyBills::getExternalQuery, true))
//                )
//                .eq(AgencyBills::getAuthContract, 1)
//                .isNotNull(AgencyBills::getDeclareTime)
//                .orderByDesc(AgencyBills::getId)
//                .page(new Page<>(pageNum, pageSize));
        return agencyBillsMapper.queryAllowAgencyBills(new Page<>(pageNum, pageSize), subOrganizationList, recordNo, projectName, useUnit);
    }

    private List<Integer> validUser(String userName) {
        SysUser user = sysUserMapper.findUserByName(userName);
        if (Objects.isNull(user)) {
            throw new RemoteServiceException("账号有误");
        }
        Integer organizationId = user.getOrganizationId();
        List<Integer> organizationList = new ArrayList<Integer>() {{
            this.add(organizationId);
        }};
        List<Integer> subOrganizationList;
        subOrganizationList = agencyBillsMapper.findSubOrganization(organizationList);
        subOrganizationList.addAll(organizationList);
        return subOrganizationList;
    }

    @DS("engin")
    public AgencyBillsBean findBills(String recordNo, String userId) {
//        AgencyBills bills = agenyBillsService.lambdaQuery()
//                .eq(AgencyBills::getUserid, userId)
//                .eq(AgencyBills::getRecordNo, recordNo)
//                .and(v -> v.eq(AgencyBills::getProjectStatus, "跟进")
//                        .or(vl -> vl.eq(AgencyBills::getProjectStatus, "签单")
//                                .eq(AgencyBills::getExternalQuery, true))
//                )
//                .isNotNull(AgencyBills::getDeclareTime)
//                .one();
        AgencyBills bills = agencyBillsMapper.findBills(recordNo, userId);

        if (Objects.isNull(bills)) {
            throw new RemoteServiceException("信息有误");
        }

        AgencyBillsBean agencyBillsBean = new AgencyBillsBean();
        BeanUtils.copyProperties(bills, agencyBillsBean);
        agencyBillsBean.setItems(agenyBillsService.machine4AgencyList(bills.getId()));

        return agencyBillsBean;
    }

    @DS("engin")
    public void updateAgencyBillsStatus(String userId, String recordNo)  {
        try {
            agencyBillsMapper.updateAgencyBillsStatus(userId, recordNo);

            log.info("成功，更改工程机登录单签单状态：" + recordNo);
        } catch (Exception e) {
            log.error("失败，更改工程机登录单签单状态：" + recordNo, e);
        }

    }

    @DS("engin")
    public void depositConfirmUpdateAgencyBills(DepositManage depositManage)  {
        AgencyBills bills = agencyBillsMapper.findAgencyBillsByRecordNo(depositManage.getRefEnginRecordNo());

        if (Objects.isNull(bills)) {
            throw new RemoteServiceException("找不着对应登录单编号：" + depositManage.getRefEnginRecordNo());
        }

        try {
            agencyBillsMapper.depositConfirmUpdateAgencyBills(depositManage);
            log.info("押金审核通过，成功，更改工程机登录单：" + depositManage.getRefEnginRecordNo());
        } catch (Exception e) {
            log.error("押金审核通过，失败，更改工程机登录单：" + depositManage.getRefEnginRecordNo(), e);
        }
    }

    @DS("engin")
    public List<AgencyBills> queryBills(Collection<String> bills) {
        if (CollectionUtil.isEmpty(bills)) {
            throw new RemoteServiceException("未发现需要查询的登录编号");
        }

        return agencyBillsMapper.queryBills(bills);
    }

}
