package easydo.technology.system.rest;

import easydo.technology.components.JdbcClient;
import easydo.technology.system.model.SysDept;
import easydo.technology.system.model.Tenant;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
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.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tenant")
public class TenantController {

    @Resource
    private JdbcClient jdbcClient;

    @Resource
    private DataSource dataSource;

    @PostMapping(value = "/getList")
    public Object getList(@RequestBody(required = false) Map<String, Object> map) {
        try {
            if (map == null) {
                map = new HashMap<>();
            }
            List<Tenant> list = jdbcClient.getJdbcList(map, Tenant.class);
            return new ResponseEntity<>(list, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping(value = "/getPage")
    public Object getPage(@RequestBody(required = false) Map<String, Object> map) {
        try {
            if (map == null) {
                map = new HashMap<>();
            }
            Map<String, Object> page = jdbcClient.getJdbcPage(map, Tenant.class);
            Object records = page.get("records");
            if (records == null) {
                page.put("records", new java.util.ArrayList<>());
            }
            return new ResponseEntity<>(page, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping(value = "/save")
    public Object save(@RequestBody Tenant model) {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false); // 开启事务

            model.setStatus("enable"); // 强制设置状态为启用
            jdbcClient.jdbcInsert(model, connection);

            // 同步创建关联部门
            SysDept dept = new SysDept();
            dept.setName(model.getName());
            dept.setPid(1L); // 顶级部门
            dept.setFirmFunctionary(model.getManagerName());
            dept.setFirmFunctionaryPhone(model.getManagerPhone());
            dept.setDeptSort(1);
            dept.setTenantId(model.getId());
            jdbcClient.jdbcInsert(dept, connection);

            connection.commit(); // 提交事务
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception ignored) {
                }
            }
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception ignored) {
                }
            }
        }
    }

    @PostMapping(value = "/update")
    public Object update(@RequestBody Tenant model) {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false); // 开启事务

            jdbcClient.jdbcUpdateById(model, connection);

            // 同步更新关联部门信息
            SysDept deptQuery = new SysDept();
            deptQuery.setPid(1L);
            deptQuery.setTenantId(model.getId());
            SysDept dept = jdbcClient.getJdbcModel(deptQuery, connection);

            if (dept != null) {
                dept.setName(model.getName());
                dept.setFirmFunctionary(model.getManagerName());
                dept.setFirmFunctionaryPhone(model.getManagerPhone());
                jdbcClient.jdbcUpdateById(dept, connection);
            }

            connection.commit(); // 提交事务
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception ignored) {
                }
            }
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception ignored) {
                }
            }
        }
    }

    @PostMapping(value = "/remove")
    public Object remove(@RequestBody Tenant model) {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            jdbcClient.jdbcRemoveById(model, connection);

            // Go 版本此处删除部门逻辑被注释掉，这里保留同样逻辑（默认不执行）
            // SysDept dept = new SysDept();
            // dept.setPid(1L);
            // dept.setTenantId(model.getId());
            // jdbcClient.jdbcRemove(dept, connection);

            connection.commit();
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            if (connection != null) {
                try {
                    connection.rollback();
                } catch (Exception ignored) {
                }
            }
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception ignored) {
                }
            }
        }
    }
}

