/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package easydo.technology.quartz.task;

import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BizException;
import easydo.technology.model.*;
import easydo.technology.model.vo.GLDContract;
import easydo.technology.service.GLDCostService;
import easydo.technology.service.GLDMasterService;
import easydo.technology.system.domain.SysDept;
import easydo.technology.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务
 */
@Slf4j
@Component
public class JobTask {
    @Resource
    DataSource dataSource;
    @Resource
    JdbcClient jdbcClient;
    @Resource
    GLDMasterService gldMasterService;
    @Resource
    GLDCostService gldCostService;

    protected void pullDeptFromGldMaster() throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            List<GldDept> existList = jdbcClient.getJdbcList(new HashMap<>(), GldDept.class, connection);
            List<GldDept> list = gldMasterService.getGetDept();
            for (GldDept model : list) {
                List<GldDept> filterList = existList.stream().filter(exist -> model.getId().equals(exist.getId()))
                        .collect(Collectors.toList());
                if (filterList.size() > 0) {
                    jdbcClient.jdbcUpdateById(model, connection);
                } else {
                    jdbcClient.jdbcInsert(model, connection);
                }
            }
            connection.commit();
        } catch (Exception e) {
            connection.rollback();
            throw new BizException(e.getMessage());
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    protected void pullMemberFromGldMaster() throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            List<GldMember> existList = jdbcClient.getJdbcList(new HashMap<>(), GldMember.class, connection);
            List<GldMember> list = gldMasterService.getGetMember();
            for (GldMember model : list) {
                List<GldMember> filterList = existList.stream().filter(exist -> model.getId().equals(exist.getId()))
                        .collect(Collectors.toList());
                if (filterList.size() > 0) {
                    jdbcClient.jdbcUpdateById(model, connection);
                } else {
                    jdbcClient.jdbcInsert(model, connection);
                }
            }
            connection.commit();
        } catch (Exception e) {
            connection.rollback();
            throw new BizException(e.getMessage());
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    protected void pullProjectFromGldMaster() throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            List<GldProject> existGLDList = jdbcClient.getJdbcList(new HashMap<>(), GldProject.class, connection);
            List<ProjectInfo> existProjList = jdbcClient.getJdbcList(new HashMap<>(), ProjectInfo.class, connection);
            List<GldProject> list = gldMasterService.getGetProject();
            for (GldProject model : list) {
                List<GldProject> filterList = existGLDList.stream().filter(exist -> model.getId().equals(exist.getId()))
                        .collect(Collectors.toList());
                if (filterList.size() > 0) {
                    jdbcClient.jdbcUpdateById(model, connection);
                } else {
                    jdbcClient.jdbcInsert(model, connection);
                }
                List<ProjectInfo> filterProjList = existProjList.stream()
                        .filter(exist -> model.getId().equals(exist.getId())).collect(Collectors.toList());
                ProjectInfo info = new ProjectInfo();
                info.setId(model.getId());
                info.setProjectAddr(model.getAddress());
                info.setProjectName(model.getProjectName());
                info.setProjectNo(model.getCode());
                if (model.getActive()) {
                    info.setProjectStatus("active");
                } else {
                    info.setProjectStatus("inactive");
                }
                info.setGldDeptId(model.getDeptId());
                GldDept gldDept = new GldDept();
                gldDept.setId(model.getDeptId());
                gldDept = jdbcClient.getJdbcModel(gldDept, connection);
                if (StringUtil.isEmpty(gldDept.getCode())) {
                    continue;
                }
                SysDept dept = new SysDept();
                dept.setCode(gldDept.getCode());
                dept = jdbcClient.getJdbcModel(dept, connection);
                if (StringUtil.isEmpty(dept.getDeptId())) {
                    info.setDeptId((long) 1);
                } else {
                    info.setDeptId(dept.getDeptId());
                }

                if (filterProjList.size() > 0) {
                    jdbcClient.jdbcUpdateById(info, connection);
                } else {
                    jdbcClient.jdbcInsert(info, connection);
                }
            }
            connection.commit();
        } catch (Exception e) {
            connection.rollback();
            throw new BizException(e.getMessage());
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    protected void pullTenantFromGldMaster() throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            List<GldTenant> existList = jdbcClient.getJdbcList(new HashMap<>(), GldTenant.class, connection);
            List<GldTenant> list = gldMasterService.getGetTenant();
            for (GldTenant model : list) {
                List<GldTenant> filterList = existList.stream().filter(exist -> model.getId().equals(exist.getId()))
                        .collect(Collectors.toList());
                if (filterList.size() > 0) {
                    jdbcClient.jdbcUpdateById(model, connection);
                } else {
                    jdbcClient.jdbcInsert(model, connection);
                }
            }
            connection.commit();
        } catch (Exception e) {
            connection.rollback();
            throw new BizException(e.getMessage());
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    protected void pullContractFromGld() throws Exception {
        Connection connection = null;
        Map<String, Object> map = new HashMap<>();
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);
            map.put("isHaveContract", 0);
            map.put("projectIdBegin", 1);
            List<Purchase> list = jdbcClient.getJdbcList(map, Purchase.class, connection);
            for (Purchase model : list) {
                List<GLDContract> contractList = gldCostService.getContractList(model.getProjectId(),
                        model.getPurchaseNo());
                if (!contractList.isEmpty()) {
                    PurchaseBidNotice bidNotice = new PurchaseBidNotice();
                    bidNotice.setPurchaseId(model.getId());
                    bidNotice = jdbcClient.getJdbcModel(bidNotice, connection);
                    Supplier supplier = new Supplier();
                    supplier.setId(bidNotice.getBidCompanyIds());
                    supplier = jdbcClient.getJdbcModel(supplier, connection);
                
                    for (GLDContract contract : contractList) {
                        PurchaseContract purchaseContract = new PurchaseContract();
                        purchaseContract.setPurchaseId(model.getId());
                        purchaseContract.setProjectId(model.getProjectId());
                        purchaseContract.setContractName(contract.getName());
                        purchaseContract.setContractNo(contract.getCode());
                        purchaseContract.setSignAmount(contract.getTaxAmount());
                        purchaseContract.setCreateTime(contract.getCreateTime());
                        purchaseContract.setEndTime(contract.getApprovedEndTime());
                        purchaseContract.setObjectId(contract.getObjectId());
                        purchaseContract.setFileName(contract.getFileName());
                        purchaseContract.setSupplierId(supplier.getId());
                        purchaseContract.setSupplierName(supplier.getSupplierName());
                        purchaseContract.setSupplierNo(supplier.getSupplierNo());
                        jdbcClient.jdbcInsert(purchaseContract, connection);
                    }
                    model.setIsHaveContract(true);
                    jdbcClient.jdbcUpdateById(model, connection);
                }
            }

            connection.commit();
        } catch (Exception e) {
            connection.rollback();
            throw new BizException(e.getMessage());
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }
}
