/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springblade.common.utils.BaiduApiUtil;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.manager.dto.FindAllUserByConditionDTO;
import org.springblade.manager.entity.ContractInfo;
import org.springblade.manager.entity.ProjectContractArea;
import org.springblade.manager.mapper.ProjectContractAreaMapper;
import org.springblade.manager.vo.CRolePostVO;
import org.springblade.manager.vo.ContractInfoVO;
import org.springblade.manager.mapper.ContractInfoMapper;
import org.springblade.manager.service.IContractInfoService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.manager.vo.WbsTreeContractTreeVO;
import org.springblade.manager.vo.WbsTreeVO;
import org.springblade.system.user.entity.User;
import org.springblade.system.user.vo.UserVO2;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 合同段信息表 服务实现类
 *
 * @author liuyc
 * @since 2022-04-14
 */
@Service
@AllArgsConstructor
public class ContractInfoServiceImpl
        extends BaseServiceImpl<ContractInfoMapper, ContractInfo>
        implements IContractInfoService {

    private final ContractInfoMapper contractInfoMapper;
    private final ProjectContractAreaMapper projectContractAreaMapper;

    @Override
    public List<ContractInfo> selectContractByProjectIds(List<Long> ids) {
        return this.baseMapper.selectContractByProjectIds(ids);
    }

    @Override
    public IPage<ContractInfoVO> selectContractInfoPage(IPage<ContractInfoVO> page, ContractInfoVO contractInfo) {
        List<ContractInfoVO> dat = baseMapper.selectContractInfoPage(page, contractInfo);
        return page.setRecords(dat);
    }

    @Override
    public List<ContractInfo> selectContractInfoPageByPid(String pid) {
        return baseMapper.selectContractInfoPageByPid(pid);
    }

    @Override
    public List<CRolePostVO> findJobByRoleId(String id) {
        return contractInfoMapper.findJobByRoleId(id);
    }

    @Override
    public IPage<UserVO2> findAllUserByCondition(IPage<UserVO2> page, FindAllUserByConditionDTO values) {
        List<UserVO2> list = contractInfoMapper.findAllUserByCondition(page, values);
        return page.setRecords(list);
    }

    @Override
    public IPage<User> findUserListByCondition(IPage<User> page, FindAllUserByConditionDTO values) {
        List<User> userListByCondition = contractInfoMapper.findUserListByCondition(page, values);
        return page.setRecords(userListByCondition);
    }

    @Override
    public List<User> findUserInfoByCondition(String rId, String pId, String userName) {
        if (userName == null || ("").equals(userName)) {
            userName = "";
        }
        return contractInfoMapper.findUserInfoByCondition(rId, pId, userName);
    }


    @Override
    public List<User> findUserByName(String name) {
        List<User> userByName = contractInfoMapper.findUserByName(name);
        return userByName;
    }

    @Override
    public Boolean updatePasswordByUserId(String userId, String password) {
        Integer row = contractInfoMapper.updatePasswordByUserId(userId, password);
        if (row > 0) {
            return true;
        }
        return false;
    }

    @Override
    public String selectStartFileId(String startFileUrl) {
//        return contractInfoMapper.selectStartFileId(startFileUrl);
        return null;
    }

    @Override
    public Boolean deleteFile(String url) {
        return contractInfoMapper.deleteFile(url);
    }

    @Override
    public List<WbsTreeContractTreeVO> tree(String wbsId, String projectId, String contractId) {
        return ForestNodeMerger.merge(baseMapper.tree(wbsId, projectId, contractId, null, null));
    }

    /**
     * 对客户端接口
     *
     * @param contractId 合同段ID
     * @param wbsType    需要查询的节点类型
     * @return 合同段自身的划分树
     */
    @Override
    public List<WbsTreeContractTreeVO> queryContractWbsTreeByContractIdAndType(String contractId, Integer wbsType, String parentId) {
        List<WbsTreeContractTreeVO> vo = this.baseMapper.tree(null, null, contractId, wbsType, parentId);
        return ForestNodeMerger.merge(vo);
    }

    @Override
    public List<WbsTreeContractTreeVO> queryContractWbsTreeAll(String contractId, Integer wbsType, String parentId) {
        return this.baseMapper.tree(null, null, contractId, wbsType, parentId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAndUpdateContract(ContractInfoVO contractInfo) {
        //新增合同段
        boolean row = saveOrUpdate(contractInfo);
        if (row) {
            //获取合同段位置信息
            String projectPlace = contractInfo.getProjectPlace();
            try {
                Map<String, Object> addressInfo = BaiduApiUtil.geocoding(projectPlace);
                Map<String, String> position = BaiduApiUtil.getPosition(addressInfo.get("lat").toString()
                        + "," + addressInfo.get("lng").toString());
                ProjectContractArea projectContractArea = new ProjectContractArea();
                projectContractArea.setProvince(position.get("province"));
                projectContractArea.setCity(position.get("city"));
                projectContractArea.setCounty(position.get("district"));
                projectContractArea.setCity_code(position.get("adcode"));
                projectContractArea.setProjectId(contractInfo.getPId());
                projectContractArea.setIsDeleted(0);
                projectContractArea.setContractId(String.valueOf(contractInfo.getId()));
                //判重
                QueryWrapper<ProjectContractArea> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("project_id", contractInfo.getPId());
                queryWrapper.eq("contract_id", contractInfo.getId());
                queryWrapper.eq("province", position.get("province"));
                queryWrapper.eq("city", position.get("city"));
                queryWrapper.eq("county", position.get("district"));
                queryWrapper.eq("city_code", position.get("adcode"));
                queryWrapper.eq("is_deleted", contractInfo.getIsDeleted());
                ProjectContractArea projectContractArea1 = projectContractAreaMapper.selectOne(queryWrapper);
                if (projectContractArea1 == null) {
                    int insert = projectContractAreaMapper.insert(projectContractArea);
                    if (insert > 0) {
                        return true;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    @Override
    public List<ContractInfo> findContractInProject(String ids) {
        return baseMapper.selectList(Wrappers.<ContractInfo>query().lambda().eq(ContractInfo::getPId, ids));
    }
}
