package com.yimeng.okr.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yimeng.okr.entity.AssessmentDimension;
import com.yimeng.okr.entity.KpiTemplate;
import com.yimeng.okr.entity.SysDepartment;
import com.yimeng.okr.entity.SysUser;
import com.yimeng.okr.enums.UserRole;
import com.yimeng.okr.mapper.AssessmentDimensionMapper;
import com.yimeng.okr.mapper.KpiTemplateMapper;
import com.yimeng.okr.mapper.SysDepartmentMapper;
import com.yimeng.okr.mapper.SysUserMapper;
import com.yimeng.okr.service.AuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
@Order(3)
public class DataInitializer implements CommandLineRunner {

    private final AuthService authService;
    private final KpiTemplateMapper kpiTemplateMapper;
    private final SysDepartmentMapper deptMapper;
    private final SysUserMapper userMapper;
    private final AssessmentDimensionMapper dimensionMapper;
    private final PasswordEncoder passwordEncoder;

    @Value("${app.seed.demo-data-enabled:true}")
    private boolean demoDataEnabled;

    @Override
    public void run(String... args) {
        log.info("Initializing default admin account...");
        authService.initAdmin();
        log.info("Default admin account ready");
        initDimensions();
        initKpiTemplates();
        if (demoDataEnabled) {
            initOrganization();
        }
    }

    private void initOrganization() {
        long deptCount = deptMapper.selectCount(null);
        if (deptCount > 0) return; // already initialized

        // Departments
        SysDepartment sz = createDept("深圳总部", 0L, 1);
        SysDepartment dev = createDept("开发技术中心", sz.getId(), 2);
        SysDepartment fin = createDept("行财中心", sz.getId(), 3);
        SysDepartment plan = createDept("企划中心", sz.getId(), 4);
        SysDepartment ai = createDept("AI技术中心", sz.getId(), 5);
        SysDepartment gs = createDept("甘肃运营中心", 0L, 6);
        log.info("Departments seeded: 6");

        // Users (after admin id=1)
        String pw = "emoon123456";
        SysUser hantuo = createUser("hantuo", pw, "韩拓", "hantuo@emoon.com", "CEO / 总经理", sz.getId(), null, UserRole.SUPER_ADMIN);
        SysUser wangkang = createUser("wangkang", pw, "王康", "wangkang@emoon.com", "全栈开发工程师", dev.getId(), hantuo.getId(), UserRole.SUPER_ADMIN);
        SysUser hanchao = createUser("hanchao", pw, "韩朝", "hanzhao@emoon.com", "后端开发工程师", dev.getId(), wangkang.getId(), UserRole.EMPLOYEE);
        SysUser gaoli = createUser("gaoli", pw, "高力", "gaoli@emoon.com", "前端开发工程师", dev.getId(), wangkang.getId(), UserRole.EMPLOYEE);
        SysUser fansicheng = createUser("fansicheng", pw, "樊思呈", "fansicheng@emoon.com", "财务总监", fin.getId(), hantuo.getId(), UserRole.EMPLOYEE);
        SysUser liumeng = createUser("liumeng", pw, "刘萌", "liumeng@emoon.com", "产品经理", plan.getId(), hantuo.getId(), UserRole.EMPLOYEE);
        SysUser fengyuanji = createUser("fengyuanji", pw, "冯元积", "fengyuanji@emoon.com", "区域经理", gs.getId(), hantuo.getId(), UserRole.EMPLOYEE);

        // Set department leaders
        setDeptLeader(sz.getId(), hantuo.getId());
        setDeptLeader(dev.getId(), wangkang.getId());
        setDeptLeader(fin.getId(), fansicheng.getId());
        setDeptLeader(plan.getId(), liumeng.getId());
        setDeptLeader(gs.getId(), fengyuanji.getId());

        log.info("Users seeded: 7 + admin");
    }

    private SysDepartment createDept(String name, Long parentId, int sort) {
        SysDepartment d = new SysDepartment();
        d.setName(name);
        d.setParentId(parentId);
        d.setSortOrder(sort);
        deptMapper.insert(d);
        return d;
    }

    private SysUser createUser(String username, String password, String realName, String email,
                                String position, Long deptId, Long superiorId, UserRole role) {
        SysUser u = new SysUser();
        u.setUsername(username);
        u.setPasswordHash(passwordEncoder.encode(password));
        u.setRealName(realName);
        u.setEmail(email);
        u.setPosition(position);
        u.setDepartmentId(deptId);
        u.setSuperiorId(superiorId);
        u.setRole(role);
        userMapper.insert(u);
        return u;
    }

    private void setDeptLeader(Long deptId, Long leaderId) {
        SysDepartment d = deptMapper.selectById(deptId);
        if (d != null) {
            d.setLeaderId(leaderId);
            deptMapper.updateById(d);
        }
    }

    private void initDimensions() {
        long count = dimensionMapper.selectCount(null);
        if (count > 0) return;

        seedDimension("交付质量", 10, 1);
        seedDimension("协作沟通", 10, 2);
        seedDimension("学习成长", 10, 3);
        seedDimension("创新贡献", 10, 4);
        log.info("Assessment dimensions seeded: 4 (total 40)");
    }

    private void seedDimension(String name, int maxScore, int sortOrder) {
        AssessmentDimension d = new AssessmentDimension();
        d.setName(name);
        d.setMaxScore(maxScore);
        d.setSortOrder(sortOrder);
        dimensionMapper.insert(d);
    }

    private void initKpiTemplates() {
        long count = kpiTemplateMapper.selectCount(null);
        if (count > 0) return;

        seedTemplate("前端开发工程师", "前端", "[{\"name\":\"业务功能交付\",\"maxScore\":20},{\"name\":\"UI还原度与交互\",\"maxScore\":10},{\"name\":\"前端性能优化\",\"maxScore\":10},{\"name\":\"代码质量与规范\",\"maxScore\":10},{\"name\":\"组件库建设\",\"maxScore\":10}]");
        seedTemplate("后端开发工程师", "后端", "[{\"name\":\"API交付与文档\",\"maxScore\":20},{\"name\":\"线上质量与事故\",\"maxScore\":15},{\"name\":\"数据库与存储方案\",\"maxScore\":10},{\"name\":\"系统性能与稳定性\",\"maxScore\":10},{\"name\":\"技术方案设计\",\"maxScore\":5}]");
        seedTemplate("全栈开发工程师", "全栈", "[{\"name\":\"功能交付闭环\",\"maxScore\":20},{\"name\":\"系统架构设计\",\"maxScore\":10},{\"name\":\"前后端联调质量\",\"maxScore\":10},{\"name\":\"线上稳定性\",\"maxScore\":10},{\"name\":\"技术文档与分享\",\"maxScore\":10}]");
        seedTemplate("移动端开发工程师", "移动端", "[{\"name\":\"App功能交付\",\"maxScore\":20},{\"name\":\"Crash率与稳定性\",\"maxScore\":15},{\"name\":\"性能与包大小\",\"maxScore\":10},{\"name\":\"平台适配兼容\",\"maxScore\":10},{\"name\":\"应用商店审核\",\"maxScore\":5}]");
        seedTemplate("CEO / 总经理", "管理", "[{\"name\":\"公司战略目标达成\",\"maxScore\":20},{\"name\":\"营收与增长指标\",\"maxScore\":15},{\"name\":\"团队建设与文化\",\"maxScore\":10},{\"name\":\"融资与资本运作\",\"maxScore\":10},{\"name\":\"对外合作与品牌\",\"maxScore\":5}]");
        seedTemplate("人力资源总监", "人力", "[{\"name\":\"招聘到岗率与时效\",\"maxScore\":20},{\"name\":\"员工留存与满意度\",\"maxScore\":15},{\"name\":\"培训与人才发展\",\"maxScore\":10},{\"name\":\"薪酬绩效管理\",\"maxScore\":10},{\"name\":\"合规与劳动关系\",\"maxScore\":5}]");
        seedTemplate("财务总监", "财务", "[{\"name\":\"财务报表准确及时\",\"maxScore\":20},{\"name\":\"预算管控与成本\",\"maxScore\":15},{\"name\":\"税务合规与筹划\",\"maxScore\":10},{\"name\":\"现金流管理\",\"maxScore\":10},{\"name\":\"审计与内控\",\"maxScore\":5}]");
        seedTemplate("区域经理", "区域运营", "[{\"name\":\"区域营收目标达成\",\"maxScore\":20},{\"name\":\"客户拓展与留存\",\"maxScore\":15},{\"name\":\"团队管理与绩效\",\"maxScore\":10},{\"name\":\"市场占有率提升\",\"maxScore\":10},{\"name\":\"合规与风险管控\",\"maxScore\":5}]");
        seedTemplate("产品经理", "产品", "[{\"name\":\"产品交付与迭代\",\"maxScore\":20},{\"name\":\"用户增长与留存\",\"maxScore\":15},{\"name\":\"需求质量与文档\",\"maxScore\":10},{\"name\":\"竞品分析与规划\",\"maxScore\":10},{\"name\":\"跨部门协作\",\"maxScore\":5}]");
        seedTemplate("运营总监", "运营", "[{\"name\":\"核心业务指标达成\",\"maxScore\":20},{\"name\":\"用户活跃与转化\",\"maxScore\":15},{\"name\":\"活动策划与执行\",\"maxScore\":10},{\"name\":\"内容与渠道运营\",\"maxScore\":10},{\"name\":\"数据驱动优化\",\"maxScore\":5}]");
        seedTemplate("市场营销总监", "市场", "[{\"name\":\"品牌曝光与声量\",\"maxScore\":20},{\"name\":\"线索获取与转化\",\"maxScore\":15},{\"name\":\"内容营销产出\",\"maxScore\":10},{\"name\":\"渠道投放ROI\",\"maxScore\":10},{\"name\":\"竞品与行业研究\",\"maxScore\":5}]");
        seedTemplate("医疗合规总监", "医疗合规", "[{\"name\":\"合规体系搭建\",\"maxScore\":20},{\"name\":\"政策法规落实\",\"maxScore\":15},{\"name\":\"数据安全与隐私\",\"maxScore\":10},{\"name\":\"审计与风险排查\",\"maxScore\":10},{\"name\":\"培训与宣贯\",\"maxScore\":5}]");

        log.info("KPI templates seeded (4 roles)");
    }

    private void seedTemplate(String name, String category, String json) {
        KpiTemplate t = new KpiTemplate();
        t.setName(name); t.setCategory(category); t.setItemsJson(json);
        kpiTemplateMapper.insert(t);
    }
}
