package com.boman.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.web.controller.BaseController;
import com.boman.common.log.annotation.Log;
import com.boman.common.log.enums.BusinessType;
import com.boman.common.security.annotation.PreAuthorize;
import com.boman.domain.SysDept;
import com.boman.domain.constant.UserConstants;
import com.boman.domain.dto.AjaxResult;
import com.boman.system.domain.vo.TreeSelect;
import com.boman.system.mapper.SysDeptMapper;
import com.boman.system.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;
    @Autowired // 整理数据测试用的
    private SysDeptMapper deptMapper;

    /**
     * 获取部门列表
     */
//    @PreAuthorize(hasPermi = "system:dept:list")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 获取部门列表
     */
    @GetMapping("/deptList")
    public AjaxResult deptList(SysDept dept) {
        List<SysDept> depts = deptService.selectDepts(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize(hasPermi = "system:dept:list")
    @GetMapping("/list/exclude/{id}")
    public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getId().intValue() == id
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), id + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 功能描述: 拿到部门下所有的部门, 包含传过来的deptId
     *
     * @param deptId deptId
     * @return com.boman.domain.dto.AjaxResult
     */
    @GetMapping("/list/children/depts/{deptId}")
    public List<SysDept> listChildrenDepts(@PathVariable(value = "deptId") Long deptId) {
        return deptService.listChildrenDepts(deptId);
    }


    /**
     * 根据区划id去找部门id(只适用于村级以上的部门查询)
     * @param areaId
     * @return
     */
    @GetMapping("/selectByAreaId/{areaId}")
    public List<SysDept> selectByAreaId(@PathVariable("areaId") String areaId) {
        return deptService.selectByAreaId(areaId);
    }

    /**
     * 功能描述: 根据deptId查找子类，不递归
     *
     * @param deptId 可以为null
     * @return java.util.List<com.boman.domain.SysDept>
     */
    @GetMapping("/list/towns")
    public List<SysDept> listTowns(Long deptId) {
        return deptService.listTowns(deptId);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize(hasPermi = "system:dept:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return AjaxResult.success(deptService.selectDeptById(id));
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize(hasPermi = "system:dept:query")
    @GetMapping(value = "/getById/{id}")
    public SysDept getById(@PathVariable("id") Long id)
    {
        return deptService.selectDeptById(id);
    }

    /**
     * 根据部门名称获取该用户属于哪一个部门(疫苗新增/修改时使用)
     */
    @GetMapping(value = "/selectByDeptName/{deptName}")
    public List<SysDept> selectByDeptName(@PathVariable("deptName") String deptName)
    {
        return deptService.selectByDeptName(deptName);
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/depts")
    public AjaxResult depts(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDepts(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @PreAuthorize(hasPermi = "system:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize(hasPermi = "system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getId()))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getId()) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize(hasPermi = "system:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        if (deptService.hasChildById(id))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(id))
        {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(id));
    }


    @GetMapping("/auth/moveData/{limit}")
    public String moveYmjzData( @PathVariable("limit") int limit) throws Exception {
        //List<String> idCardList = mapper.listIdCard(limit, offset);
        List<JSONObject> ymjzList = deptService.syncData(limit);
        int moveData = 0;
        StringBuilder stringBuilder = new StringBuilder();
        List<String> enpty = new ArrayList<>();
        for (int i = 0; i < ymjzList.size(); i++) {
            JSONObject ymjz = ymjzList.get(i);
            String idCard = ymjz.getString("id_card");
            Long deptId = ymjz.getLong("dept_id");
            String sql = "";
            if(deptId == null) {
                enpty.add(idCard);
            }else {
                sql = String.format("UPDATE vaccine_info set dept_id = %s where id_card = '%s'; -- %s \r\n", deptId, idCard, i);
                stringBuilder.append(sql);
            }


            System.err.println("count: " + i + ", " + sql);
            moveData++;
        }
//        File file = new File("E:\\\\work\\vainfo.sql");
        File file = new File("/usr/local/sql/vaccine_info.sql");
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fileWriter = new FileWriter(file, true);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(stringBuilder.toString());
        bufferedWriter.close();
        return "循环了 " + moveData + " 条";
    }

    /**
     * 查找子部门，不递归
     */
    @GetMapping("/parentId/{parentId}")
    public List<SysDept> getByParentId(@PathVariable("parentId") Long parentId) {
        return deptService.getByParentId(parentId);
    }

    /**
     * 功能描述: 把部门表中的ancestors按照规则塞进值
     *
     * @return com.boman.domain.dto.AjaxResult
     */
    @GetMapping("/auth")
    public AjaxResult setAncestors() {
        List<SysDept> sysDepts = deptService.selectDeptsList();
        for (SysDept sysDept : sysDepts) {
            String ancestors = sysDept.getAncestors();
            if (StringUtils.isEmpty(ancestors)) {
                Long parentId = sysDept.getParentId();
                //根据子的parentId找到对应的父对象
                SysDept parent1 = deptService.getParentById(parentId);
                if (parent1 == null) {
                    continue;
                }

                Long id1 = parent1.getId();
                Long parentId1 = parent1.getParentId();
                SysDept parent2 = deptService.getParentById(parentId1);
                if (parent2 == null) {
                    sysDept.setAncestors(id1 + "");
                    deptMapper.updateDept(sysDept);
                    continue;
                }

                Long id2 = parent2.getId();
                Long parentId2 = parent2.getParentId();
                SysDept parent3 = deptService.getParentById(parentId2);
                if (parent3 == null) {
                    sysDept.setAncestors(id2 + "," + id1);
                    deptMapper.updateDept(sysDept);
                    continue;
                }

                Long id3 = parent3.getId();
                sysDept.setAncestors(id3 + "," + id2 + "," + id1);
                deptMapper.updateDept(sysDept);
            }
        }
        
//        System.out.println(JSON.toJSONString(sysDepts));
        return AjaxResult.success();
    }

/*    @GetMapping("/auth/syncData")
    public void syncData() {
            try {
                deptService.syncData();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/

}
