package cn.wisenergy.chnmuseum.party.web.controller;

import cn.wisenergy.chnmuseum.party.common.log.MethodLog;
import cn.wisenergy.chnmuseum.party.common.log.OperModule;
import cn.wisenergy.chnmuseum.party.common.log.OperType;
import cn.wisenergy.chnmuseum.party.common.util.DateUtil80;
import cn.wisenergy.chnmuseum.party.common.util.ImportExcelUtil;
import cn.wisenergy.chnmuseum.party.model.TArea;
import cn.wisenergy.chnmuseum.party.model.TUser;
import cn.wisenergy.chnmuseum.party.service.TAreaService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.wisenergy.chnmuseum.party.web.controller.base.BaseController;
import cn.wisenergy.chnmuseum.party.model.TOrgan;
import cn.wisenergy.chnmuseum.party.service.TOrganService;
import cn.wisenergy.chnmuseum.party.common.enums.AuditStatusEnum;
import cn.wisenergy.chnmuseum.party.common.validator.groups.Add;
import cn.wisenergy.chnmuseum.party.common.validator.groups.Update;
import cn.wisenergy.chnmuseum.party.common.vo.GenericPageParam;

import com.beust.jcommander.Parameter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <pre>
 * 机构 前端控制器
 * </pre>
 *
 * @author Danny Lee
 * @since 2021-03-22
 */
@Slf4j
@RestController
@RequestMapping("/organ")
@Api(tags = {"机构操作接口"})
public class TOrganController extends BaseController {

    @Resource
    private TOrganService tOrganService;

    @Resource
    private TAreaService tAreaService;


    @PostMapping("/add")
    @RequiresPermissions("/organ/add")
    @ApiOperation(value = "添加机构", notes = "添加机构")
//    @MethodLog(operModule = OperModule.ORG,operType = OperType.ADD)
    public Map<String, Object> add(TOrgan organ) {

        QueryWrapper<TOrgan> ew = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(organ.getName())) {
            organ.setName(organ.getName().trim());
            ew.eq("is_deleted", 0);
            ew.eq("name", organ.getName());
            List<TOrgan> list = this.tOrganService.list(ew);
            if (list != null&&list.get(0)!=null) {
                HashMap<String, Object> resultMap = new HashMap<>();
                resultMap.put("resultCode", "500");
                resultMap.put("message", "机构名称不能重复!");
                return resultMap;
            }
        }
        organ.setCreateTime(DateUtil80.getDateTimeOfTimestamp(System.currentTimeMillis()));
        organ.setUpdateTime(DateUtil80.getDateTimeOfTimestamp(System.currentTimeMillis()));
        String organCode = getOrganCode(organ.getParentId());
        organ.setLevel(organCode.length()/3);
        organ.setCode(organCode);
        // 保存业务节点信息
        boolean result = tOrganService.save(organ);
        // 返回操作结果
        if (result) {
            return getSuccessResult();
        } else {
            // 保存失败
            return getFailResult();
        }
    }

    @PutMapping("/update")
    @RequiresPermissions("/organ/update")
    @ApiOperation(value = "update", notes = "修改机构信息")
//    @MethodLog(operModule = OperModule.ORG,operType = OperType.UPDATE)
    public Map<String, Object> updateTOrgan(TOrgan tOrgan) {

        try {
            TOrgan byId = tOrganService.selectById(tOrgan.getId());
            if (!byId.getParentId().equals(tOrgan.getParentId())){
                tOrgan.setCode(getOrganCode(tOrgan.getParentId()));
            }
            if (byId.getLevel()!=tOrgan.getCode().length()/3&&byId.getChildren().size()>0){
                HashMap<String, Object> map = new HashMap<>();
                map.put("resultCode", "500");
                map.put("message", "机构存在下级机构,不能修改机构级别!");
                map.put("data", "");
                return map;
            }

            tOrgan.setUpdateTime(DateUtil80.getDateTimeOfTimestamp(System.currentTimeMillis()));
            boolean flag = false;
            flag = tOrganService.updateById(tOrgan);
            if (!flag) {
                return getFailResult();
            }
            return getSuccessResult();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return getFailResult();
    }


    @DeleteMapping("/delete")
    @RequiresPermissions("/organ/delete")
    @ApiOperation(value = "根据ID删除机构", notes = "根据ID删除机构")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "标识ID", paramType = "query", dataType = "String")
    })
//    @MethodLog(operModule = OperModule.ORG,operType = OperType.DELETE)
    public Map<String, Object> deleteTOrgan(String id) {
        boolean result = false;
        try {
            TOrgan tOrgan = tOrganService.getById(id);
            tOrgan.setIsDeleted(true);
            tOrgan.setUpdateTime(DateUtil80.getDateTimeOfTimestamp(System.currentTimeMillis()));
            result = tOrganService.updateById(tOrgan);
            if (!result) {
                return getFailResult();
            }
            return getSuccessResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getFailResult();
    }

    @GetMapping("/getList")
    @RequiresPermissions("/organ/getList")
    @ApiOperation(value = "获取机构全部列表(无分页)", notes = "获取机构全部列表(无分页)")
//    @MethodLog(operModule = OperModule.ORG,operType = OperType.SELECT)
    public Map<String, Object> getTOrganList() {
        TUser user = null;
        try {
            user = getcurUser();
            TOrgan tOrgan = new TOrgan();
            //设置用户数据权限
            tOrgan.setCode(user.getOrgCode());
            List<TOrgan> list = tOrganService.getAllList(tOrgan);
            return getResult(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getFailResult();

    }



    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "nameOrCode", value = "名称或编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startDate", value = "创建时间-开始", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "创建时间-结束", paramType = "query", dataType = "String")
    })
    @PostMapping("/getPageList")
    @RequiresPermissions("/organ/getPageList")
    @ApiOperation(value = "获取机构分页列表", notes = "获取机构分页列表")
    @MethodLog(operModule = OperModule.ORG,operType = OperType.SELECT)
    public Map<String, Object> getTOrganPageList(GenericPageParam genericPageParam) {
        TUser user = getcurUser();
        Page<TOrgan> page = null;
        try {
            LambdaQueryWrapper<TOrgan> queryWrapper = new LambdaQueryWrapper<>();
            // 对名称或编码模糊查询
            if (StringUtils.isNotBlank(genericPageParam.getNameOrCode())) {
                queryWrapper.like(TOrgan::getName, genericPageParam.getNameOrCode());
            }
            // 根据创建时间区间检索
            if (genericPageParam.getStartDate() != null && genericPageParam.getEndDate() != null) {
                queryWrapper.ge(TOrgan::getCreateTime, genericPageParam.getStartDate().atTime(0, 0, 0))
                        .le(TOrgan::getCreateTime, genericPageParam.getEndDate().atTime(23, 59, 59));
            }
            //设置用户数据权限
            queryWrapper.likeRight(TOrgan::getCode,user.getOrgCode());
            queryWrapper.eq(TOrgan::getIsDeleted,false);
            // 设置排序规则
            queryWrapper.orderByDesc(TOrgan::getCreateTime);
            page = this.tOrganService.page(getPage(), queryWrapper);
            return getResult(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getFailResult();
    }

    @ApiOperation(value = "获取机构详情", notes = "获取机构详情")
    @GetMapping("/getById")
    @RequiresPermissions("/organ/getById")
    @MethodLog(operModule = OperModule.ORG,operType = OperType.SELECT)
    public Map<String, Object> getById(String id) {
        TOrgan tOrgan = null;
        try {
            tOrgan = tOrganService.selectById(id);
            return getResult(tOrgan);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getFailResult();
    }


	@GetMapping("/getTree")
	@RequiresPermissions("/organ/getTree")
	@ApiOperation(value = "获取机构树", notes = "获取机构树")
//    @MethodLog(operModule = OperModule.ORG,operType = OperType.SELECT)
	public Map<String, Object> getTree(String name) {
        TUser user = getcurUser();
        List<TOrgan> list = new ArrayList<>();

        try {
            if (StringUtils.isBlank(name)) {
                list = tOrganService.getTree();
            }else {
                list = tOrganService.list(new UpdateWrapper<TOrgan>().like("name",name).likeRight("code",user.getOrgCode()));
            }
            return getResult(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getFailResult();
    }

    @GetMapping("/getAreaTree")
    @RequiresPermissions("/organ/getAreaTree")
    @ApiOperation(value = "获取区域树", notes = "获取机构树")
//    @MethodLog(operModule = OperModule.ORG,operType = OperType.SELECT)
    public Map<String, Object> getAreaTree() {
        List<TArea> list = null;
        try {
            list = tAreaService.getAreaTree();
            return getResult(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getFailResult();
    }


    // 导入EXCEL
    @ApiOperation(value = "导入EXCEL", notes = "导入EXCEL", httpMethod = "POST")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @RequiresPermissions("/organ/import")
    @MethodLog(operModule = OperModule.ORG,operType = OperType.IMPORT)
    public ResponseEntity<Map> upload(MultipartFile file) {
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        try {
            boolean flag = false;
            //使用工具类从文件中读取数据
            List excelList = ImportExcelUtil.readExcel(file.getOriginalFilename(), file.getInputStream());
            flag = tOrganService.batchUpload(excelList);
            if (!flag) {
                resultMap.put("resultCode","500");
                resultMap.put("massage","导入失败!");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
            }
            resultMap.put("resultCode","200");
            resultMap.put("massage","导入成功!");
            return ResponseEntity.ok(resultMap);
        } catch (Exception e) {
            resultMap.put("resultCode","500");
            resultMap.put("massage","导入失败!");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
        }
    }

    private String getOrganCode(String parentId) {
        TOrgan max = tOrganService.selectCodeMax(parentId);
        if (max==null){
            max = tOrganService.getById(parentId);
            String s = max.getCode() + "001";
            return s;
        }
        String s = max.getCode().substring(max.getCode().length() - 3);
        String s1 = max.getCode().substring(0,max.getCode().length() - 3);
        Integer integer = Integer.valueOf(s)+1;
        if (integer<10){
            s1=s1+"00"+integer.toString();
        }else if (integer<100){
            s1=s1+"0"+integer.toString();
        }else {
            s1=s1+integer.toString();
        }
        return s1;
    }

}