package com.yuchen.saas.park.service.service.approve;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuchen.saas.park.api.dto.approve.PeopleApproveHandleDto;
import com.yuchen.saas.park.api.dto.approve.PeopleApproveQueryDto;
import com.yuchen.saas.park.api.entity.approve.PeopleApprove;
import com.yuchen.saas.park.api.entity.approve.PeopleApproveHandleRecord;
import com.yuchen.saas.park.api.entity.park.PmgBatParkPeople;
import com.yuchen.saas.park.api.entity.property.PropertyHouses;
import com.yuchen.saas.park.service.mapper.approve.PeopleApproveMapper;
import com.yuchen.saas.park.service.service.PmgBatParkPeopleService;
import com.yuchen.saas.park.service.service.property.PropertyHousesService;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.constant.NestConstant;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PeopleApproveService extends BaseServiceImpl<PeopleApproveMapper, PeopleApprove> {

    @Resource
    private PeopleApproveHandleRecordService peopleApproveHandleRecordService;

    @Resource
    @Lazy
    private PmgBatParkPeopleService pmgBatParkPeopleService;
    @Resource
    private PropertyHousesService propertyHousesService;

    public List<PeopleApprove> getAll() {

        LambdaQueryWrapper<PeopleApprove> qw = new LambdaQueryWrapper<>();
        List<PeopleApprove> peopleApproveList = baseMapper.selectList(qw);

        return peopleApproveList;
    }

    public boolean savePeopleApprove(PeopleApprove peopleApprove) {
        this.assembleSaveDto(peopleApprove);
        return this.saveOrUpdate(peopleApprove);

    }

    private void assembleSaveDto(PeopleApprove peopleApprove) {
        if (Func.isEmpty(peopleApprove.getId())) {
            peopleApprove.setApplyStatus("1");
            peopleApprove.setApplyTime(new Date());
            peopleApprove.setCreateTime(new Date());
            peopleApprove.setCreateUser(AuthUtil.getUserId());
            peopleApprove.setCreateDept(Func.isNotEmpty(AuthUtil.getDeptId()) ? Long.valueOf(AuthUtil.getDeptId()) : null);
        } else {
            peopleApprove.setUpdateTime(new Date());
            peopleApprove.setUpdateUser(AuthUtil.getUserId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean accept(PeopleApproveHandleDto handleDto) {
        PeopleApprove peopleApprove = getById(handleDto.getId());
        LambdaQueryWrapper<PmgBatParkPeople> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(Func.isNotEmpty(peopleApprove.getParkId()),PmgBatParkPeople::getParkId, peopleApprove.getParkId());
        qw2.eq(Func.isNotEmpty(peopleApprove.getBuildingId()),PmgBatParkPeople::getBuildingId, peopleApprove.getBuildingId());
        qw2.eq(Func.isNotEmpty(peopleApprove.getBuildingUnitId()),PmgBatParkPeople::getBuildingUnitId, peopleApprove.getBuildingUnitId());
        qw2.eq(Func.isNotEmpty(peopleApprove.getFloorId()),PmgBatParkPeople::getFloorId, peopleApprove.getFloorId());
        qw2.eq(Func.isNotEmpty(peopleApprove.getRoomId()),PmgBatParkPeople::getRoomId, peopleApprove.getRoomId());
        qw2.eq(PmgBatParkPeople::getPeopleType, 1);
        qw2.orderByDesc(PmgBatParkPeople::getCreateTime);
        List<PmgBatParkPeople> owner = pmgBatParkPeopleService.list(qw2);
        if (Func.isEmpty(peopleApprove)) {
            throw new ServiceException("人员审批不存在");
        }
        // 确认
        if (handleDto.getOptType() == 1) {
            // 已通过
            peopleApprove.setApplyStatus("3");
            PeopleApprove appr = this.getById(handleDto.getId());


            LambdaQueryWrapper<PmgBatParkPeople> qw = new LambdaQueryWrapper<>();
            qw.eq(Func.isNotEmpty(appr.getIdCard()),PmgBatParkPeople::getIdCard, appr.getIdCard());
            qw.eq(Func.isNotEmpty(appr.getParkId()),PmgBatParkPeople::getParkId, appr.getParkId());
            qw.eq(Func.isNotEmpty(appr.getBuildingId()),PmgBatParkPeople::getBuildingId, appr.getBuildingId());
            qw.eq(Func.isNotEmpty(appr.getBuildingUnitId()),PmgBatParkPeople::getBuildingUnitId, appr.getBuildingUnitId());
            qw.eq(Func.isNotEmpty(appr.getApproveType()),PmgBatParkPeople::getPeopleType, appr.getApproveType());
            qw.eq(Func.isNotEmpty(appr.getFloorId()),PmgBatParkPeople::getFloorId, appr.getFloorId());
            qw.eq(Func.isNotEmpty(appr.getRoomId()),PmgBatParkPeople::getRoomId, appr.getRoomId());
            PmgBatParkPeople people = pmgBatParkPeopleService.getOne(qw);
            if (Func.isNotEmpty(people)) {
                if (peopleApprove.getApproveType() == 1) {
                    people.setBindAccount(appr.getContactPhone());
                    people.setBindStatus(1);
                    pmgBatParkPeopleService.saveOrUpdate(people);
                } else if (peopleApprove.getApproveType() == 99) {
                    people.setImgsrc(appr.getFacePhoto());
                    pmgBatParkPeopleService.saveOrUpdate(people);
                } else {

                    people.setBindAccount(Func.isNotEmpty(owner) ? owner.get(0).getPhone() : peopleApprove.getContactPhone());
                    people.setBindStatus(1);
                    pmgBatParkPeopleService.saveOrUpdate(people);
                }

            } else {
                if (peopleApprove.getApproveType() != 1 && peopleApprove.getApproveType() != 99) {

                    PmgBatParkPeople newPeople = new PmgBatParkPeople();
                    BeanUtils.copyProperties(peopleApprove, newPeople);

                    newPeople.setBindAccount(Func.isNotEmpty(owner) ? owner.get(0).getPhone() : peopleApprove.getContactPhone() );
                    newPeople.setBindStatus(1);
                    newPeople.setPeopleType(peopleApprove.getApproveType().longValue());
                    newPeople.setPhone(peopleApprove.getContactPhone());
                    newPeople.setId(null);
                    pmgBatParkPeopleService.save(newPeople);
                } else {
                    PmgBatParkPeople newPeople = new PmgBatParkPeople();
                    BeanUtils.copyProperties(peopleApprove, newPeople);
                    newPeople.setBindAccount(peopleApprove.getContactPhone());
                    newPeople.setBindStatus(1);
                    newPeople.setPeopleType(peopleApprove.getApproveType().longValue());
                    newPeople.setPhone(peopleApprove.getContactPhone());
                    newPeople.setId(null);
                    pmgBatParkPeopleService.save(newPeople);
                }
            }
            // 人脸审核
            if (peopleApprove.getApproveType() == 99) {
                LambdaQueryWrapper<PmgBatParkPeople> qw3 = new LambdaQueryWrapper<>();
                qw3.eq(PmgBatParkPeople::getIdCard, peopleApprove.getIdCard());
                qw3.eq(PmgBatParkPeople::getParkId, peopleApprove.getParkId());
                qw3.eq(PmgBatParkPeople::getBuildingId, peopleApprove.getBuildingId());
                qw3.eq(PmgBatParkPeople::getBuildingUnitId, peopleApprove.getBuildingUnitId());
                qw3.eq(PmgBatParkPeople::getFloorId, peopleApprove.getFloorId());
                qw3.eq(PmgBatParkPeople::getRoomId, peopleApprove.getRoomId());
                qw3.eq(PmgBatParkPeople::getPeopleType, peopleApprove.getTenantType());
                List<PmgBatParkPeople> peoples = pmgBatParkPeopleService.list(qw3);
                for (PmgBatParkPeople p : peoples) {
                    p.setImgsrc(peopleApprove.getFacePhoto());
                    pmgBatParkPeopleService.saveOrUpdate(p);
                }
                //pmgBatParkPeopleService.saveOrUpdateBatch(peoples);
            }

        } else if (handleDto.getOptType() == 2) { // 驳回
            // 已驳回
            peopleApprove.setApplyStatus("4");
        }
        peopleApprove.setConfirmUser(AuthUtil.getUser().getUserName());
        //peopleApprove.setConfirmUser("1");
        peopleApprove.setConfirmTime(new Date());
        updateById(peopleApprove);
        // 添加处理记录
        PeopleApproveHandleRecord handleRecord = new PeopleApproveHandleRecord();
        handleRecord.setApproveId(peopleApprove.getId());
        handleRecord.setOperateTime(new Date());
        if (handleDto.getOptType() == 1) {
            handleRecord.setOperateType("确认");
        } else if (handleDto.getOptType() == 2) {
            handleRecord.setOperateType("驳回");
        }

        //handleRecord.setOperateUser(AuthUtil.getUser().getOrgUserId());
        handleRecord.setOperateUser(AuthUtil.getUser()==null?1l:AuthUtil.getUser().getOrgUserId());
        handleRecord.setRemark(handleDto.getRemark());
        peopleApproveHandleRecordService.save(handleRecord);
        return Boolean.TRUE;
    }
    private QueryWrapper<String> getPageQueryParam(PeopleApproveQueryDto qryDto) {


        QueryWrapper<String> qw = new QueryWrapper<>();
        if (Func.isNotEmpty(qryDto.getParkId())) {
            qw.eq("h.park_id",qryDto.getParkId());
        }
        if (Func.isNotEmpty(qryDto.getBuildingId())) {
            qw.eq("h.building_id",qryDto.getBuildingId());
        }
        if (Func.isNotEmpty(qryDto.getBuildingUnitId())) {
            qw.eq("h.building_unit_id",qryDto.getBuildingUnitId());
        }
        if (Func.isNotEmpty(qryDto.getFloorId())) {
            qw.eq("h.floor_id",qryDto.getFloorId());
        }
        if (Func.isNotEmpty(qryDto.getRoomId())) {
            qw.eq("h.room_id",qryDto.getRoomId());
        }
        if (Func.isNotEmpty(qryDto.getOwnerType())) {
            qw.eq("h.owner_type",qryDto.getOwnerType());
        }
        if (Func.isNotEmpty(qryDto.getIdType())) {
            qw.eq("h.id_type",qryDto.getIdType());
        }
        if (Func.isNotEmpty(qryDto.getIdCard())) {
            qw.like("h.id_card",qryDto.getIdCard());
        }
        if (Func.isNotEmpty(qryDto.getName())) {
            qw.like("h.name",qryDto.getName());
        }
        if (Func.isNotEmpty(qryDto.getApplyStatus())) {
            qw.eq("h.apply_status",qryDto.getApplyStatus());
        }
        qw.eq("h.is_deleted", NestConstant.DB_NOT_DELETED);
        return qw;
    }
    public Page<PeopleApprove> getPeopleApproveList(PeopleApproveQueryDto queryDto) {
        Page<PeopleApprove> page = new Page<>(queryDto.getCurrent(), queryDto.getSize());
        LambdaQueryWrapper<PeopleApprove> qw = new LambdaQueryWrapper<>();
        qw.eq(Func.isNotEmpty(queryDto.getParkId()), PeopleApprove::getParkId, queryDto.getParkId());
        qw.eq(Func.isNotEmpty(queryDto.getBuildingId()), PeopleApprove::getBuildingId, queryDto.getBuildingId());
        qw.eq(Func.isNotEmpty(queryDto.getBuildingUnitId()), PeopleApprove::getBuildingUnitId, queryDto.getBuildingUnitId());
        qw.eq(Func.isNotEmpty(queryDto.getRoomId()), PeopleApprove::getRoomId, queryDto.getRoomId());
        qw.eq(Func.isNotEmpty(queryDto.getOwnerType()), PeopleApprove::getOwnerType, queryDto.getOwnerType());
        qw.eq(Func.isNotEmpty(queryDto.getIdType()), PeopleApprove::getIdType, queryDto.getIdType());
        qw.like(Func.isNotEmpty(queryDto.getIdCard()), PeopleApprove::getIdCard, queryDto.getIdCard());
        qw.like(Func.isNotEmpty(queryDto.getName()), PeopleApprove::getName, queryDto.getName());
        qw.like(Func.isNotEmpty(queryDto.getContactPhone()), PeopleApprove::getContactPhone, queryDto.getContactPhone());
        qw.eq(Func.isNotEmpty(queryDto.getApplyStatus()), PeopleApprove::getApplyStatus, queryDto.getApplyStatus());
        qw.eq(Func.isNotEmpty(queryDto.getApproveType()), PeopleApprove::getApproveType, queryDto.getApproveType());
        qw.orderByDesc(PeopleApprove::getCreateTime);
        return this.page(page, qw);

    }
    public PeopleApprove getPeopleApproveDetail(Long id) {
        PeopleApprove appr = this.getById(id);
        if (!appr.getApplyStatus().equals("1")) {
            LambdaQueryWrapper<PeopleApproveHandleRecord> qw = new LambdaQueryWrapper<>();
            qw.eq(PeopleApproveHandleRecord::getApproveId, appr.getId());
            qw.orderByDesc(PeopleApproveHandleRecord::getOperateTime);
            List<PeopleApproveHandleRecord> list = peopleApproveHandleRecordService.list(qw);
            PeopleApproveHandleRecord record = list.get(0);
            appr.setRemark(record.getRemark());
        }
        LambdaQueryWrapper<PropertyHouses> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(PropertyHouses::getParkId, appr.getParkId());
        qw2.eq(PropertyHouses::getBuildingId, appr.getBuildingId());
        qw2.eq(PropertyHouses::getUnitNum, appr.getBuildingUnitId());
        qw2.eq(PropertyHouses::getLevelId, appr.getFloorId());
        qw2.eq(PropertyHouses::getId, appr.getRoomId());
        PropertyHouses house = propertyHousesService.getOne(qw2);
        appr.setResourceCode(house.getResourceCode());
        appr.setDeliveryDate(house.getDeliveryDate());
        appr.setHouseStatus(house.getHouseStatus());
        if (Func.isNotEmpty(appr.getApplySource())) {
            if (appr.getApplySource().equals("1")) {
                appr.setApplySource("小程序");
            } else if (appr.getApplySource().equals("2")) {
                appr.setApplySource("PC端");
            } else {
                appr.setApplySource("小程序");
            }
        } else {
            appr.setApplySource("小程序");
        }

        //String userName = AuthUtil.getUserName();
        //appr.setConfirmUser(userName);
        return appr;
//        if (!appr.getApplyStatus().equals("1")) {
//
//        }

    }

    public Page<PeopleApprove> getTenantApproveList(PeopleApproveQueryDto queryDto) {
        Page<PeopleApprove> page = new Page<>(queryDto.getCurrent(), queryDto.getSize());
        LambdaQueryWrapper<PeopleApprove> qw = new LambdaQueryWrapper<>();
        qw.eq(Func.isNotEmpty(queryDto.getParkId()), PeopleApprove::getParkId, queryDto.getParkId());
        qw.eq(Func.isNotEmpty(queryDto.getBuildingId()), PeopleApprove::getBuildingId, queryDto.getBuildingId());
        qw.eq(Func.isNotEmpty(queryDto.getBuildingUnitId()), PeopleApprove::getBuildingUnitId, queryDto.getBuildingUnitId());
        qw.eq(Func.isNotEmpty(queryDto.getRoomId()), PeopleApprove::getRoomId, queryDto.getRoomId());
        qw.eq(Func.isNotEmpty(queryDto.getOwnerType()), PeopleApprove::getOwnerType, queryDto.getOwnerType());
        qw.eq(Func.isNotEmpty(queryDto.getIdType()), PeopleApprove::getIdType, queryDto.getIdType());
        qw.like(Func.isNotEmpty(queryDto.getIdCard()), PeopleApprove::getIdCard, queryDto.getIdCard());
        qw.like(Func.isNotEmpty(queryDto.getName()), PeopleApprove::getName, queryDto.getName());
        qw.like(Func.isNotEmpty(queryDto.getContactPhone()), PeopleApprove::getContactPhone, queryDto.getContactPhone());
        qw.eq(Func.isNotEmpty(queryDto.getApplyStatus()), PeopleApprove::getApplyStatus, queryDto.getApplyStatus());
        List<Long> listLong = new ArrayList<Long>() {{
             add(1l);
             add(99l);
        }};
        qw.notIn(PeopleApprove::getApproveType, listLong);

        //qw.eq(Func.isNotEmpty(queryDto.getApproveType()), PeopleApprove::getApproveType, queryDto.getApproveType());
        qw.orderByDesc(PeopleApprove::getCreateTime);
        return this.page(page, qw);

    }

    public Page<PeopleApprove> getExistApproveList(PeopleApproveQueryDto queryDto) {
        Page<PeopleApprove> page = new Page<>(queryDto.getCurrent(), queryDto.getSize());
        LambdaQueryWrapper<PeopleApprove> qw = new LambdaQueryWrapper<>();
        qw.eq(Func.isNotEmpty(queryDto.getParkId()), PeopleApprove::getParkId, queryDto.getParkId());
        qw.eq(Func.isNotEmpty(queryDto.getBuildingId()), PeopleApprove::getBuildingId, queryDto.getBuildingId());
        qw.eq(Func.isNotEmpty(queryDto.getBuildingUnitId()), PeopleApprove::getBuildingUnitId, queryDto.getBuildingUnitId());
        qw.eq(Func.isNotEmpty(queryDto.getRoomId()), PeopleApprove::getRoomId, queryDto.getRoomId());
        qw.eq(Func.isNotEmpty(queryDto.getOwnerType()), PeopleApprove::getOwnerType, queryDto.getOwnerType());
        qw.eq(Func.isNotEmpty(queryDto.getIdType()), PeopleApprove::getIdType, queryDto.getIdType());
        qw.eq(Func.isNotEmpty(queryDto.getIdCard()), PeopleApprove::getIdCard, queryDto.getIdCard());
        qw.eq(Func.isNotEmpty(queryDto.getName()), PeopleApprove::getName, queryDto.getName());
        qw.eq(Func.isNotEmpty(queryDto.getApplyStatus()), PeopleApprove::getApplyStatus, queryDto.getApplyStatus());
        qw.eq(Func.isNotEmpty(queryDto.getApproveType()), PeopleApprove::getApproveType, queryDto.getApproveType());
        qw.orderByDesc(PeopleApprove::getApplyTime);
        return this.page(page, qw);

    }

    /*
    public List<PeopleApprove> getLevelsByBuildingId(Long buildingId) {

        LambdaQueryWrapper<PeopleApprove> qw = new LambdaQueryWrapper<>();
        qw.eq(PeopleApprove::getBuildingId, buildingId);
        List<PeopleApprove> peopleApproveList = baseMapper.selectList(qw);

        return peopleApproveList;
    }
    public List<PeopleApprove> getLevelsByBuildingAndUnitId(Long buildingId, Long buildingUnitId) {

        LambdaQueryWrapper<PeopleApprove> qw = new LambdaQueryWrapper<>();
        qw.eq(PeopleApprove::getBuildingId, buildingId);
        qw.eq(PeopleApprove::getBuildingUnitId, buildingUnitId);
        List<PeopleApprove> peopleApproveList = baseMapper.selectList(qw);

        return peopleApproveList;
    }

    private LambdaQueryWrapper<PeopleApprove> getPageQueryParam(PeopleApproveQryDto req) {
        LambdaQueryWrapper<PeopleApprove> qw = new LambdaQueryWrapper<>();
        if (Func.isNotEmpty(req.getBuildingId())) {
            qw.eq(PeopleApprove::getBuildingId, req.getBuildingId());
        }
        if (Func.isNotEmpty(req.getBuildingUnitId())) {
            qw.eq(PeopleApprove::getBuildingUnitId, req.getBuildingUnitId());
        }

        qw.eq(PeopleApprove::getIsDeleted, NestConstant.DB_NOT_DELETED);
        return qw;
    }

    public Page<PeopleApprove> selectPage(PeopleApproveQryDto req) {
        Page<PeopleApprove> page = new Page<>(req.getCurrent(), req.getSize());
        baseMapper.propertyBuildingsLvlPage(page, this.getPageQueryParam(req));
        return page;
    }
*/

}
