package com.yfd.platform.system.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yfd.platform.annotation.Log;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.modules.basedata.domain.Substation;
import com.yfd.platform.modules.basedata.mapper.SubstationMapper;
import com.yfd.platform.system.domain.SysOrganization;
import com.yfd.platform.system.mapper.SysRoleMapper;
import com.yfd.platform.system.service.ISysOrganizationService;
import com.yfd.platform.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统组织框架 前端控制器
 * </p>
 *
 *
 * @since 2021-12-15
 */
@RestController
@RequestMapping("/system/organization")
@Api(value = "SysOrganizationController", tags = "系统组织框架")
public class SysOrganizationController {

    @Resource
    private ISysOrganizationService organizationService;

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private IUserService userService;

    @Resource
    private SubstationMapper substationMapper;

    /***********************************
     * 用途说明：获取组织范围树结构
     * 参数说明
     *parentid      上级id
     * params       名称（根据名称查询二级）
     * 返回值说明:  组织树集合
     ***********************************/
    @PostMapping("/getOrgScopeTree")
    @ApiOperation("获取组织范围树结构")
    @ResponseBody
    public List<Map<String, Object>> getOrgScopeTree(String roleId) {
        return organizationService.getOrgScopeTree(roleId);
    }

    /***********************************
     * 用途说明：获取组织范围
     * 参数说明
     * 返回值说明:  组织范围集合
     ***********************************/
    @PostMapping("/getOrgTree")
    @ApiOperation("获取组织结构树")
    @ResponseBody
    @PreAuthorize("@el.check('select:org')")
    public List<Map<String, Object>> getOrgTree(String parentid,
                                                String params) {
        return organizationService.getOrgTree(parentid, params);
    }

    /***********************************
     * 用途说明：根据企业ID查询组织详情
     * 参数说明
     * id        企业id
     * 返回值说明:  系统组织框架对象
     ***********************************/
    @PostMapping("/getOrganizationById")
    @ApiOperation("根据企业ID查询组织信息")
    @ResponseBody
    public ResponseResult getOrganizationById(String id, String orgName) {
        if (StrUtil.isBlank(id)) {
            return ResponseResult.error("查询失败！");
        }
        List<Map<String, Object>> sysOrganizations =
                organizationService.getOrganizationById(id, orgName);
        // 查看变电站图片
        sysOrganizations.forEach(organization -> {
            if (ObjectUtil.isNotEmpty(organization.get("orgcode"))) {
                if (ObjectUtil.isNotEmpty(organization.get("contactPhone"))) {
                    String contactPhone = organization.get("contactPhone").toString();
                    organization.put("contactPhone", DesensitizedUtil.mobilePhone(contactPhone));
                }
                String orgcode = organization.get("orgcode").toString();
                List<Substation> substations =
                        substationMapper.selectList(new LambdaQueryWrapper<Substation>().eq(Substation::getStationCode, orgcode));
                if (substations.size() > 0) {
                    Substation substation = substations.get(0);
                    organization.put("images", substation.getImages());
                }
            }
        });
        return ResponseResult.successData(sysOrganizations);
    }

    /***********************************
     * 用途说明：根据ID查询组织详情
     * 参数说明
     * id        系统组织id
     * 返回值说明:  系统组织框架对象
     ***********************************/
    @PostMapping("/getOneById")
    @ApiOperation("根据ID查询组织详情")
    @ResponseBody
    public ResponseResult getOneById(String id) {
        SysOrganization sysOrganization = organizationService.getById(id);
        String contactPhone = sysOrganization.getContactPhone();
        if (StrUtil.isNotBlank(contactPhone)) {
            DesensitizedUtil.mobilePhone(contactPhone);
        }
        return ResponseResult.successData(sysOrganization);
    }

    /***********************************
     * 用途说明：新增系统组织框架
     * 参数说明
     * sysOrganization     系统组织框架对象
     * 返回值说明:  是否新增成功
     ***********************************/
    @Log(module = "系统组织框架", value = "新增企业或者部门！", type = "0")
    @PostMapping("/addOrg")
    @ApiOperation("新增系统组织框架")
    @ResponseBody
    public ResponseResult addOrg(@RequestBody SysOrganization sysOrganization) {
        //判断是否是否填写 有效 否则默认为 1
        if (StrUtil.isEmpty(sysOrganization.getIsvaild())) {
            sysOrganization.setIsvaild("1");
        }
        String uuid = IdUtil.fastSimpleUUID();
        sysOrganization.setId(uuid);
        String orgcode = sysOrganization.getOrgcode();
        LambdaQueryWrapper<SysOrganization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrganization::getOrgcode, orgcode);
        if (StrUtil.isNotBlank(sysOrganization.getParentid())) {
            queryWrapper.eq(SysOrganization::getParentid, sysOrganization.getParentid());
        } else {
            queryWrapper.eq(SysOrganization::getParentid, "0");
        }
        List<SysOrganization> list = organizationService.list(queryWrapper);
        if (list != null && list.size() > 0) {
            return ResponseResult.error("当前区域或者变电站已经存在");
        }
        String contactPhone = sysOrganization.getContactPhone();
        if (StrUtil.isNotBlank(contactPhone) && !Validator.isMobile(contactPhone)) {
            return ResponseResult.error("手机号输入不合法");
        }
        String custom1 = sysOrganization.getCustom1();
        if (StrUtil.isNotBlank(custom1)) {
            String suffix = StrUtil.subAfter(custom1, ".", true).toLowerCase();
            if (!"png".equals(suffix) && !"jpg".equals(suffix) && !"gif".equals(suffix)) {
                return ResponseResult.error("非法文件类型");
            }
        }
        //新增 系统组织R
        boolean isOk = organizationService.addOrganization(sysOrganization);
        /* SysUser userInfo = userService.getUserInfo();
        Integer usertype = userInfo.getUsertype();
        if (!("0").equals(sysOrganization.getParentid()) && usertype != 0) {
            List<SysRole> roleByUserId = sysRoleMapper.getRoleByUserId(userInfo.getId());

        }*/
        if (isOk) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /***********************************
     * 用途说明：修改系统组织框架
     * 参数说明
     * sysOrganization     系统组织框架对象
     * 返回值说明:  是否修改成功
     ***********************************/
    @Log(module = "系统组织框架", value = "修改企业或者部门信息！", type = "0")
    @PostMapping("/updateById")
    @ApiOperation("修改系统组织框架")
    @ResponseBody
    public ResponseResult updateById(@RequestBody SysOrganization sysOrganization) {
        String orgcode = sysOrganization.getOrgcode();
        LambdaQueryWrapper<SysOrganization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrganization::getOrgcode, orgcode);
        if (StrUtil.isNotBlank(sysOrganization.getParentid())) {
            queryWrapper.eq(SysOrganization::getParentid, sysOrganization.getParentid());
        } else {
            queryWrapper.eq(SysOrganization::getParentid, "0");
        }
        queryWrapper.ne(SysOrganization::getId, sysOrganization.getId());
        List<SysOrganization> list = organizationService.list(queryWrapper);
        if (list != null && list.size() > 0) {
            return ResponseResult.error("当前区域或者变电站已经存在");
        }
        String contactPhone = sysOrganization.getContactPhone();
        if (StrUtil.isNotBlank(contactPhone) && !Validator.isMobile(contactPhone)) {
            return ResponseResult.error("手机号输入不合法");
        }
        boolean isOk = organizationService.updateOrganization(sysOrganization);
        if (isOk) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /***********************************
     * 用途说明：修改系统组织框架
     * 参数说明
     * sysOrganization     系统组织框架对象
     * 返回值说明:  是否修改成功
     ***********************************/
    @Log(module = "系统组织框架", value = "设置企业/部门是否有效！", type = "0")
    @PostMapping("/setIsValid")
    @ApiOperation("设置组织是否有效")
    @ResponseBody
    public ResponseResult setIsValid(@RequestParam String id,
                                     @RequestParam String isvaild) {
        boolean isOk = organizationService.setIsValid(id, isvaild);
        //boolean isOk = organizationService.update(updateWrapper);
        if (isOk) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /***********************************
     * 用途说明：根据id删除系统组织框架
     * 参数说明
     * id     系统组织框架id
     * 返回值说明:  是否删除成功
     ***********************************/
    @Log(module = "系统组织框架", value = "根据ID删除企业或者部门！", type = "0")
    @PostMapping("/deleteById")
    @ApiOperation("根据id删除系统组织框架")
    @ResponseBody
    public ResponseResult deleteById(@RequestParam String id) {
       /* String[] orgIds = id.split(",");
        for (String orgId : orgIds) {
            LambdaQueryWrapper<SysOrganization> queryWrapper =
                    new LambdaQueryWrapper<>();
            List<SysOrganization> list =
                    organizationService.list(queryWrapper.eq(SysOrganization::getParentid, orgId));
            List<String> ids =
                    list.stream().map(SysOrganization::getId).collect(Collectors.toList());
            boolean isOk = organizationService.removeById(orgId);
            if (!isOk) {
                continue;
            }
            for (String oid : ids) {
                organizationService.removeById(oid);
            }
        }*/
        boolean ok = organizationService.deleteById(id);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("删除失败");
        }

    }

}
