package com.dxhy.admin.sys.controller;

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

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.dxhy.admin.sys.config.SysConfig;
import com.dxhy.admin.sys.entity.SysDeptEntity;
import com.dxhy.admin.sys.service.SysDeptService;
import com.dxhy.admin.sys.service.SysUserOrgService;
import com.dxhy.common.aspect.SysLog;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.utils.Constant;
import com.dxhy.common.utils.PageUtils;
import com.dxhy.common.utils.R;
import com.dxhy.common.vo.UserInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 部门管理
 *
 * @author jiaohongyang
 */
@RestController
@RequestMapping("/sys/dept")
@Slf4j

public class SysDeptController extends AbstractController {
    @Resource
    private SysDeptService sysDeptService;
    @Resource
    private SysUserOrgService sysUserOrgService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public ResponseEntity<?> list(@RequestBody Map<String, String> pramsMap) {
        long deptId = 0;
        if(StringUtils.isNotEmpty(pramsMap.get("deptId"))) {
            deptId = Long.parseLong(pramsMap.get("deptId"));
        }else{
            deptId = -1;
        }
        String company = "";
        UserInfo userInfo = getUserInfo();
        if (Long.parseLong(getUserId()) != Constant.SUPER_ADMIN && !userInfo.getCompany().contains(SysConfig.ZXQY)) {
            company = userInfo.getCompany();
        }

        List<SysDeptEntity> deptList = sysDeptService.queryList(company,deptId);
        log.info("树状信息：{}", JSON.toJSONString(deptList));
        return ResponseEntity.ok(R.ok().put("data", deptList));
    }

    /**
     * 列表
     */
    @RequestMapping("/listUser")
    public ResponseEntity<?> listUser() {
        String company = "";
        UserInfo userInfo = getUserInfo();
        if (Long.parseLong(getUserId()) != Constant.SUPER_ADMIN && !userInfo.getCompany().contains(SysConfig.ZXQY)) {
            company = userInfo.getCompany();
        }

        List<SysDeptEntity> deptList = sysDeptService.queryListUser(company);

        return ResponseEntity.ok(R.ok().put("data", deptList));
    }

    /**
     * 列表 查验上级id 是 0 和1 的企业
     */
    @RequestMapping("/listParentTree")
    public ResponseEntity<?> listParentTree() {
        String company = null;
        UserInfo userInfo = getUserInfo();
        if (Long.parseLong(getUserId()) != Constant.SUPER_ADMIN && !userInfo.getCompany().contains(SysConfig.ZXQY)) {
            company = userInfo.getCompany();
        }
        List<SysDeptEntity> deptList = sysDeptService.queryListParentTree(company);

        return ResponseEntity.ok(R.ok().put("data", deptList));
    }

    /**
     * 列表 查验上级id 是 0 和1 的企业
     */
    @RequestMapping("/listParent")
    public ResponseEntity<?> listParent() {
        String company = null;
        UserInfo userInfo = getUserInfo();
        if (Long.parseLong(getUserId()) != Constant.SUPER_ADMIN && !userInfo.getCompany().contains(SysConfig.ZXQY)) {
            company = userInfo.getCompany();
        }
        List<SysDeptEntity> deptList = sysDeptService.queryListParent(company);

        return ResponseEntity.ok(R.ok().put("data", deptList));
    }

    /**
     * 上级部门Id(管理员则为0)
     */
    @RequestMapping("/info")
    public ResponseEntity<?> info() {
        long deptId = 0;
        if (Integer.parseInt(getUserId()) != Constant.SUPER_ADMIN
            && !getUserInfo().getCompany().contains(SysConfig.ZXQY)) {
            List<SysDeptEntity> deptList = sysDeptService.queryList("");
            Long parentId = 0L;
            for (SysDeptEntity sysDeptEntity : deptList) {
                if (parentId == null) {
                    parentId = sysDeptEntity.getParentId();
                    continue;
                }
                if (parentId > sysDeptEntity.getParentId()) {
                    parentId = sysDeptEntity.getParentId();
                }
            }
            deptId = parentId;
        }
        return ResponseEntity.ok(R.ok().put("data", deptId));
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{deptId}")
    public ResponseEntity<?> info(@PathVariable("deptId") Long deptId) {
        SysDeptEntity dept = sysDeptService.queryDeptById(deptId);

        return ResponseEntity.ok(R.ok().put("dept", dept));
    }

    /**
     * 根据 部门id 获取部门下的数据
     */
    @RequestMapping("/infoDept")
    public ResponseEntity<?> infoDeptId(@RequestBody Map<String, Object> params) {
        UserInfo userInfo = getUserInfo();
        if (Long.parseLong(userInfo.getId()) != Constant.SUPER_ADMIN
            && !userInfo.getCompany().contains(SysConfig.ZXQY)) {
            params.put("company", userInfo.getCompany());
        }
        log.debug("传入值：" + params);
        PageUtils page = sysDeptService.queryPage(params);
        return ResponseEntity.ok(R.ok().put("page", page));
    }

    /**
     * 供应商
     */
    @RequestMapping("/venderDeptList")
    public ResponseEntity<?> venderDeptList(@RequestBody Map<String, Object> params) {
        log.debug("传入值：" + params);
        PageUtils page = sysDeptService.queryVenderDept(params);
        return ResponseEntity.ok(R.ok().put("page", page));
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @SysLog("进项平台保存部门信息")
    public ResponseEntity<?> save(@RequestBody SysDeptEntity dept) {
        UserInfo userInfo = getUserInfo();
        try {
            // 如果添加总部的话 orttype 只能是 1
            if (dept.getDeptId() == null) {
                dept.setOrgType("1");
                dept.setParentId(0L);
                dept.setOrderNum(0);
                dept.setCompany("ZXQY_" + dept.getCompany());
            } else {
                dept.setParentId(dept.getDeptId());
                dept.setDeptId(null);
            }
            // 中心企业
            if (SysConfig.DeptType.DEPT_TYPE_0.getCode().equals(dept.getDeptType())) {
                // 中心企业
                dept.setOrgType(SysConfig.OrgType.ORG_TYPE_0.getCode());
            } else if (SysConfig.DeptType.DEPT_TYPE_1.getCode().equals(dept.getDeptType())) {
                // 集团
                dept.setOrgType(SysConfig.OrgType.ORG_TYPE_1.getCode());
            }
            // 根据上级id 获取机构信息
            if (SysConfig.DeptType.DEPT_TYPE_3.getCode().equals(dept.getDeptType())) {
                SysDeptEntity queryDeptById = sysDeptService.queryDeptById(dept.getParentId());
                if (queryDeptById != null) {
                    if (SysConfig.OrgType.ORG_TYPE_2.getCode().equals(queryDeptById.getOrgType())) {
                        dept.setOrgType(SysConfig.OrgType.ORG_TYPE_5.getCode());
                    } else if (SysConfig.OrgType.ORG_TYPE_3.getCode().equals(queryDeptById.getOrgType())) {
                        dept.setOrgType(SysConfig.OrgType.ORG_TYPE_8.getCode());
                    } else if (SysConfig.OrgType.ORG_TYPE_5.getCode().equals(queryDeptById.getOrgType())
                        || SysConfig.OrgType.ORG_TYPE_7.getCode().equals(queryDeptById.getOrgType())) {
                        dept.setOrgType(SysConfig.OrgType.ORG_TYPE_7.getCode());
                    } else if (SysConfig.OrgType.ORG_TYPE_8.getCode().equals(queryDeptById.getOrgType())
                        || SysConfig.OrgType.ORG_TYPE_9.getCode().equals(queryDeptById.getOrgType())) {
                        dept.setOrgType(SysConfig.OrgType.ORG_TYPE_9.getCode());
                    }
                }
            }
            dept.setName(dept.getTaxname());
            // 根据税号和 orgtype 判断重复项
            int count = sysDeptService.queryDeptTaxNo(dept.getTaxno(), dept.getOrgType(), dept.getCompany(), null,
                dept.getOrgCode());
            if (count > 0) {
                if (SysConfig.OrgType.ORG_TYPE_1.getCode().equals(dept.getOrgType())) {
                    return ResponseEntity.ok(R.error("保存失败，集团编码不能重复！"));
                } else {
                    if (StringUtils.isNotBlank(dept.getOrgCode())) {
                        return ResponseEntity.ok(R.error("保存失败，组织编码重复！"));
                    } else {
                        return ResponseEntity.ok(R.error("保存失败，税号重复！"));
                    }
                }
            }
            sysDeptService.saveDept(dept);
            return ResponseEntity.ok(R.ok("保存成功"));

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(R.error("保存失败，请稍后重试！"));
        }

    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @SysLog("进项平台修改部门信息")
    public ResponseEntity<?> update(@RequestBody SysDeptEntity dept) {
        try {
            // 根据税号和 orgtype 判断重复项
            int count = sysDeptService.queryDeptTaxNo(dept.getTaxno(), dept.getOrgType(), dept.getCompany(),
                dept.getDeptId(), dept.getOrgCode());
            if (count > 0) {
                if (SysConfig.OrgType.ORG_TYPE_1.getCode().equals(dept.getOrgType())) {
                    return ResponseEntity.ok(R.error("保存失败，集团编码不能重复！"));
                } else {
                    if (StringUtils.isNotBlank(dept.getOrgCode())) {
                        return ResponseEntity.ok(R.error("保存失败，组织编码重复！"));
                    } else {
                        return ResponseEntity.ok(R.error("保存失败，税号重复！"));
                    }
                }
            }
            sysDeptService.updateDept(dept);

            // 修改税号和名称 需修改 关联表中的数据
            sysUserOrgService.updateDeptId(dept.getTaxno(), dept.getTaxname(), dept.getDeptId());

            return ResponseEntity.ok(R.ok("保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(R.error("保存失败，请稍后重试！"));
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @SysLog("进项平台删除部门信息")
    public ResponseEntity<?> delete(@RequestBody Map<String, Object> params) {
        String deptId = (String)params.get("deptId");
        // 判断是否有子部门
        List<Long> deptList = sysDeptService.queryDetpIdList(Long.parseLong(deptId));
        if (deptList.size() > 0) {
            return ResponseEntity.ok(R.error(41000, "请先删除子部门！"));
        }
        try {
            sysDeptService.deleteDept(Long.parseLong(deptId));
            return ResponseEntity.ok(R.ok("删除成功！"));
        } catch (Exception e) {
            return ResponseEntity.ok(R.error(40010, "删除失败，请稍后重试！"));
        }
    }

}
