package com.dxhy.manage.controller;

import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.dxhy.common.util.MD5;
import org.apache.commons.lang.StringUtils;
//import org.apache.logging.log4j.util.Strings;
import org.bouncycastle.jce.provider.JDKMessageDigest;
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.dxhy.certificate.model.ReturnTokenModel;
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 com.dxhy.manage.config.ManageConstants;
import com.dxhy.manage.entity.SysDeptEntity;
import com.dxhy.manage.service.SysDeptService;

import lombok.extern.slf4j.Slf4j;

/**
 * 部门管理
 *
 * @author jiaohongyang
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@RestController
@RequestMapping("/manage/dept")
@Slf4j
public class SysDeptController extends AbstractController {
    @Resource
    private SysDeptService sysDeptService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public ResponseEntity<?> list() {
        List<SysDeptEntity> deptList = sysDeptService.queryList("");
        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) {
            company = userInfo.getCompany();
        }

        List<SysDeptEntity> deptList = sysDeptService.queryListUser(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) {
            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) {
            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) {
        log.debug("传入值：" + params);
        PageUtils page = sysDeptService.queryPage(params);
        return ResponseEntity.ok(R.ok().put("page", page));
    }

    /**
     * 保存
     */

    @RequestMapping("/save")
    public ResponseEntity<?> save(@RequestBody SysDeptEntity dept) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String date = df.format(new Date());
            // 根据税号和 orgtype 判断重复项
            if (ManageConstants.DeptType.DEPT_TYPE_0.getCode().equals(dept.getDeptType())) {
                dept.setOrgType(ManageConstants.OrgType.ORG_TYPE_0.getCode());
            } else if (ManageConstants.DeptType.DEPT_TYPE_1.getCode().equals(dept.getDeptType())) {
                dept.setOrgType(ManageConstants.OrgType.ORG_TYPE_1.getCode());
            } else if (ManageConstants.DeptType.DEPT_TYPE_2.getCode().equals(dept.getDeptType())) {
                dept.setOrgType(ManageConstants.OrgType.ORG_TYPE_2.getCode());
            } else if (ManageConstants.DeptType.DEPT_TYPE_3.getCode().equals(dept.getDeptType())) {
                dept.setOrgType(ManageConstants.OrgType.ORG_TYPE_5.getCode());
            }
            int count = sysDeptService.queryDeptTaxNo(dept.getTaxno(), dept.getOrgType(), dept.getCompany(), null);
            if (count > 0) {
                if (ManageConstants.OrgType.ORG_TYPE_1.getCode().equals(dept.getOrgType())) {
                    return ResponseEntity
                        .ok(R.error("集团编码：" + dept.getCompany() + "  ,税号: " + dept.getTaxno() + "保存失败，集团编码不能重复！"));
                } else {
                    return ResponseEntity
                        .ok(R.error("集团编码：" + dept.getCompany() + "  ,税号: " + dept.getTaxno() + "保存失败，税号重复！"));
                }
            }
            // 若 appId,appKey为空，自动生成
            if (StringUtils.isBlank(dept.getAceId()) || StringUtils.isBlank(dept.getAceKey())) {
                String aceId = "app_secId" + dept.getCompany() + date;
                String aceKey = "app_secKey" + dept.getCompany() + date;
                aceId = Base64.getEncoder().encodeToString(aceId.getBytes("utf-8"));
                aceKey = Base64.getEncoder().encodeToString(aceKey.getBytes("utf-8"));
                dept.setAceId(MD5.getEncode(aceId));
                dept.setAceKey(MD5.getEncode(aceKey));
            }
            sysDeptService.saveDept(sysDeptService.toDept(dept));
            return ResponseEntity.ok(R.ok("集团编码：" + dept.getCompany() + "  ,税号: " + dept.getTaxno() + "保存成功"));

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity
                .ok(R.error("集团编码：" + dept.getCompany() + "  ,税号: " + dept.getTaxno() + "保存失败，请稍后重试！"));
        }

    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public ResponseEntity<?> update(@RequestBody SysDeptEntity dept) {
        try {
            if ("1".equals(dept.getDeptType())) {
                dept.setOrgType("1");
            } else if ("3".equals(dept.getDeptType())) {
                dept.setOrgType("5");
            }
            // 根据税号和 orgtype 判断重复项
            int count =
                sysDeptService.queryDeptTaxNo(dept.getTaxno(), dept.getOrgType(), dept.getCompany(), dept.getDeptId());
            if (count > 0) {
                if ("1".equals(dept.getOrgType())) {
                    return ResponseEntity
                        .ok(R.error("集团编码：" + dept.getCompany() + "  ,税号: " + dept.getTaxno() + "保存失败，集团编码不能重复！"));
                } else {
                    return ResponseEntity
                        .ok(R.error("集团编码：" + dept.getCompany() + "  ,税号: " + dept.getTaxno() + "保存失败，税号重复！"));
                }
            }
            dept.setLevelCode("1");
            sysDeptService.updateDept(dept);

            return ResponseEntity.ok(R.ok("集团编码：" + dept.getCompany() + "  ,税号: " + dept.getTaxno() + "保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity
                .ok(R.error("集团编码：" + dept.getCompany() + "  ,税号: " + dept.getTaxno() + "保存失败，请稍后重试！"));
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    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, "删除失败，请稍后重试！"));
        }
    }

    @RequestMapping("/uploadDept")
    public ResponseEntity<?> uploadDept(@RequestBody String datalist) {
        int uploadDept = sysDeptService.uploadDept(datalist);
        if (uploadDept == 0) {
            return ResponseEntity.ok(R.ok("导入成功！"));
        } else if (uploadDept == 1) {
            return ResponseEntity.ok(R.error("导入失败，存在相同税号的组织信息！"));
        } else if (uploadDept == 2) {
            return ResponseEntity.ok(R.error("导入失败，录入的集团编码不存在！"));
        } else if (uploadDept == 3) {
            return ResponseEntity.ok(R.error("导入失败，请稍后重试"));
        } else {
            return ResponseEntity.ok(R.error("导入失败！"));
        }
    }

    /**
     * 证书获取token
     * 
     * @param params
     *            入参 taxno 税号 ， area 地区编码 ip 证书服务器ip index 证书槽位 password 证书密码
     * @return 返回
     */
    @RequestMapping("/getToken")
    public ResponseEntity<?> getToken(@RequestBody Map<String, Object> params) {
        ReturnTokenModel token = sysDeptService.getToken(params);
        if (token.getCode() == 1) {
            return ResponseEntity.ok(R.ok("获取TOKEN成功：\n" + token.getToken()));
        } else {
            return ResponseEntity.ok(R.error(token.getMessage()));
        }
    }
}
