package easydo.technology.controller;

import easydo.technology.annotation.WebLog;
import easydo.technology.components.JdbcClient;
import easydo.technology.components.ZeroSpringFolderComponent;
import easydo.technology.exception.BizException;
import easydo.technology.model.PurchaseContract;
import easydo.technology.model.Supplier;
import easydo.technology.model.SupplierBank;
import easydo.technology.service.MDMService;
import easydo.technology.utils.LocalDateUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/supplier")
public class SupplierController {
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;
    @Resource
    MDMService mdmService;

    @WebLog
    @RequestMapping(value = "/getPage")
    public Object getPage(@RequestBody Map<String, Object> map)throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            String sql = "select sum(sign_amount) as sign_amount from purchase_contract";

            Map<String, Object> page = jdbcClient.getJdbcPage(map, Supplier.class, connection);
            List<Supplier> supplierList = (List<Supplier>) page.get("records");
            for (Supplier model : supplierList) {
                PurchaseContract contract = new PurchaseContract();
                contract.setSupplierId(model.getId());
                int bidCount = jdbcClient.getJdbcCount(contract, connection);
                model.setBidCount(bidCount);

                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("supplierId", model.getId());
                PurchaseContract purchaseContract = jdbcClient.getJdbcModelByMap(paramMap, sql, PurchaseContract.class,
                        connection);
                model.setTotalAmount(purchaseContract.getSignAmount());
            }

            return new ResponseEntity<>(page, HttpStatus.OK);
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/getList")
    public Object getList(@RequestBody Map<String, Object> map) throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();

            List<Supplier> list = jdbcClient.getJdbcList(map, Supplier.class, connection);
            return new ResponseEntity<>(list, HttpStatus.OK);
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/save")
    public Object save(@RequestBody Supplier model) throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            jdbcClient.jdbcInsert(model, connection);

            SupplierBank existBank = new SupplierBank();
            existBank.setSupplierId(model.getId());
            List<SupplierBank> existBankList = jdbcClient.getJdbcList(existBank, connection);
            for (SupplierBank bank : existBankList) {
                jdbcClient.jdbcRemoveById(bank, connection);
            }
            List<SupplierBank> bankList = model.getBankList();
            for (SupplierBank bank : bankList) {
                bank.setId(UUID.randomUUID().toString());
                bank.setSupplierId(model.getId());
                jdbcClient.jdbcInsert(bank, connection);
            }
            try {
                mdmService.sendSupplier(model, false);
            } catch (Exception ee) {
                ee.printStackTrace();
            }

            connection.commit();
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/update")
    public Object update(@RequestBody Supplier model) throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            model.setUpdateTime(LocalDateUtil.localDateTimeFormatyMdHms(LocalDateTime.now()));
            jdbcClient.jdbcUpdateById(model, connection);

            SupplierBank existBank = new SupplierBank();
            existBank.setSupplierId(model.getId());
            List<SupplierBank> existBankList = jdbcClient.getJdbcList(existBank, connection);
            for (SupplierBank bank : existBankList) {
                jdbcClient.jdbcRemoveById(bank, connection);
            }
            List<SupplierBank> bankList = model.getBankList();
            for (SupplierBank bank : bankList) {
                bank.setId(UUID.randomUUID().toString());
                bank.setSupplierId(model.getId());
                jdbcClient.jdbcInsert(bank, connection);
            }
            try {
                mdmService.sendSupplier(model, false);
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            connection.commit();
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/remove")
    public Object remove(@RequestBody Supplier model) throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            jdbcClient.jdbcRemoveById(model, connection);

            SupplierBank existBank = new SupplierBank();
            existBank.setSupplierId(model.getId());
            List<SupplierBank> existBankList = jdbcClient.getJdbcList(existBank, connection);
            for (SupplierBank bank : existBankList) {
                jdbcClient.jdbcRemoveById(bank, connection);
            }
            try {
                mdmService.sendSupplier(model, true);
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            connection.commit();
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/getById")
    public Object getById(@RequestBody Supplier model) throws Exception {
        Map<String, Object> result = new HashMap<>();
        Connection connection = null;
        try {
            connection = dataSource.getConnection();

            model = jdbcClient.getJdbcModelById(model, connection);
            ZeroSpringFolderComponent.build(dataSource).fetch(model);

            SupplierBank supplierBank = new SupplierBank();
            supplierBank.setSupplierId(model.getId());
            List<SupplierBank> bankList = jdbcClient.getJdbcList(supplierBank, connection);

            result.put("supplier", model);
            result.put("bankList", bankList);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }
}
