package com.pangu.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.pangu.common.core.domain.AjaxResult;

/**
 * 岗位管理Controller
 * 
 * @author 湖北新华业务中台研发团队
 */
@RestController
@RequestMapping("/api/system/post")
public class SysPostController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询岗位列表
     */
    @GetMapping("/list")
    public AjaxResult list(
            @RequestParam(required = false) String postCode,
            @RequestParam(required = false) String postName,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        StringBuilder sql = new StringBuilder();
        sql.append("SELECT post_id, post_code, post_name, post_sort, status, create_time, remark ");
        sql.append("FROM sys_post WHERE 1=1 ");

        List<Object> params = new ArrayList<>();
        if (postCode != null && !postCode.isEmpty()) {
            sql.append("AND post_code LIKE ? ");
            params.add("%" + postCode + "%");
        }
        if (postName != null && !postName.isEmpty()) {
            sql.append("AND post_name LIKE ? ");
            params.add("%" + postName + "%");
        }
        if (status != null && !status.isEmpty()) {
            sql.append("AND status = ? ");
            params.add(status);
        }

        String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") t";
        Integer total = jdbcTemplate.queryForObject(countSql, Integer.class, params.toArray());

        sql.append("ORDER BY post_sort LIMIT ? OFFSET ?");
        params.add(pageSize);
        params.add((pageNum - 1) * pageSize);

        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql.toString(), params.toArray());

        return AjaxResult.success().put("rows", rows).put("total", total != null ? total : 0);
    }

    /**
     * 获取岗位详情
     */
    @GetMapping("/{postId}")
    public AjaxResult getInfo(@PathVariable Long postId) {
        String sql = "SELECT * FROM sys_post WHERE post_id = ?";
        Map<String, Object> post = jdbcTemplate.queryForMap(sql, postId);
        return AjaxResult.success(post);
    }

    /**
     * 新增岗位
     */
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> post) {
        String postCode = (String) post.get("postCode");
        String postName = (String) post.get("postName");

        Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_post WHERE post_code = ?", Integer.class, postCode);
        if (count != null && count > 0) {
            return AjaxResult.error("岗位编码已存在");
        }

        String sql = "INSERT INTO sys_post (post_code, post_name, post_sort, status, " +
                "create_by, create_time, remark) VALUES (?, ?, ?, ?, 'admin', NOW(), ?)";

        jdbcTemplate.update(sql,
                postCode,
                postName,
                post.getOrDefault("postSort", 0),
                post.getOrDefault("status", "0"),
                post.get("remark"));

        return AjaxResult.success();
    }

    /**
     * 修改岗位
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String, Object> post) {
        Long postId = Long.valueOf(post.get("postId").toString());

        String sql = "UPDATE sys_post SET post_code = ?, post_name = ?, post_sort = ?, " +
                "status = ?, remark = ?, update_by = 'admin', update_time = NOW() WHERE post_id = ?";

        jdbcTemplate.update(sql,
                post.get("postCode"),
                post.get("postName"),
                post.getOrDefault("postSort", 0),
                post.getOrDefault("status", "0"),
                post.get("remark"),
                postId);

        return AjaxResult.success();
    }

    /**
     * 删除岗位
     */
    @DeleteMapping("/{postIds}")
    public AjaxResult remove(@PathVariable String postIds) {
        String[] ids = postIds.split(",");
        for (String id : ids) {
            Integer count = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM sys_user_post WHERE post_id = ?",
                    Integer.class, Long.valueOf(id));
            if (count != null && count > 0) {
                return AjaxResult.error("岗位已分配给用户，无法删除");
            }
            jdbcTemplate.update("DELETE FROM sys_post WHERE post_id = ?", Long.valueOf(id));
        }
        return AjaxResult.success();
    }
}
