package com.casic.missiles.controller.sys;

import cn.hutool.core.lang.Assert;
import com.casic.missiles.core.common.annotion.BussinessLog;
import com.casic.missiles.core.common.annotion.Permission;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.enums.meter.MeterDeptTypeEnum;
import com.casic.missiles.model.exception.RequestValidException;
import com.casic.missiles.model.exception.ServiceException;
import com.casic.missiles.model.log.LogObjectHolder;
import com.casic.missiles.modular.application.enums.AdminExceptionEnum;
import com.casic.missiles.modular.domain.service.IDomainDeptService;
import com.casic.missiles.modular.interfaces.dictmap.DeptDict;
import com.casic.missiles.modular.system.model.Dept;
import com.casic.missiles.modular.system.service.IDeptService;
import com.casic.missiles.modular.system.vo.IdVO;
import com.casic.missiles.service.meter.IMeterOrganizeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 系统组织管理扩展，替换系统组织管理中相应接口
 * @Author: wangpeng
 * @Date: 2022/11/27 11:21
 */
@Api(tags = "系统组织管理扩展接口")
@Controller
@RequestMapping("/sys/extend/dept")
public class DeptExtendController {
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IDomainDeptService domainDeptService;
    @Autowired
    private IMeterOrganizeService organizeService;

    @ApiOperation("新增组织机构（同基础包中接口参数）")
    @BussinessLog(value = "添加组织机构", key = "simpleName", dict = DeptDict.class)
    @PostMapping("/add")
    @Permission
    @ResponseBody
    @Transactional
    public ReturnDTO add(@RequestBody @Valid Dept dept, BindingResult result) {
        //系统dept逻辑
        Assert.isFalse(result.hasErrors(), () -> {
            throw new RequestValidException(result, Optional.of((new Throwable()).getStackTrace()[2]));
        });
        this.initPids(dept);
        boolean success = this.deptService.save(dept);
        //新增计量组织信息，根据deptType判断
        List<String> collect = Arrays.stream(MeterDeptTypeEnum.values()).map(MeterDeptTypeEnum::getCode).collect(Collectors.toList());
        int addFlag = 1;
        if(collect.contains(dept.getDeptType())){
            addFlag = organizeService.addOrganize(dept);
        }
        if(addFlag > 0 && success){
            return ReturnUtil.success();
        }
        return ReturnUtil.failed("保存组织失败");
    }

    @ApiOperation("修改组织机构-（同基础包中接口参数）")
    @BussinessLog(value = "修改组织机构", key = "simpleName", dict = DeptDict.class)
    @PostMapping("/update")
    @Permission
    @ResponseBody
    @Transactional
    public ReturnDTO update(@RequestBody @Valid Dept dept, BindingResult result) {
        Assert.isFalse(null == dept.getId(), () -> {
            throw new ServiceException(AdminExceptionEnum.DEPT_ID_NULL, Optional.of((new Throwable()).getStackTrace()[2]));
        });
        Assert.isFalse(result.hasErrors(), () -> {
            throw new RequestValidException(result, Optional.of((new Throwable()).getStackTrace()[2]));
        });
        Assert.isFalse(dept.getId().equals(dept.getPid()), () -> {
            throw new ServiceException(AdminExceptionEnum.DEPT_PID_SAME, Optional.of((new Throwable()).getStackTrace()[2]));
        });
        LogObjectHolder.me().set(this.deptService.getById(dept.getId()));
        this.initPids(dept);
        boolean success = this.deptService.updateById(dept);
        //更新计量组织信息
        organizeService.updateByDept(dept);
        if(success){
            return ReturnUtil.success();
        }
        return ReturnUtil.failed("更新组织失败");
    }

    @ApiOperation("删除组织机构-（同基础包中接口参数）")
    @BussinessLog(value = "删除部门", dict = DeptDict.class)
    @PostMapping("/delete")
    @Permission
    @ResponseBody
    @Transactional
    public ReturnDTO delete(@RequestBody IdVO dto) {
        LogObjectHolder.me().set(this.domainDeptService.getDeptName(dto.getId()));
        this.deptService.deleteDept(dto.getId());
        //删除计量组织信息
        organizeService.deleteByDeptId(dto.getId());
        return ReturnUtil.success();
    }


    private void initPids(Dept dept) {
        if (null != dept.getPid() && !dept.getPid().equals(0L)) {
            Long pid = dept.getPid();
            Dept temp = (Dept)this.deptService.getById(pid);
            String pids = temp.getPids();
            dept.setPid(pid);
            dept.setPids(pids + "[" + pid + "],");
        } else {
            dept.setPid(0L);
            dept.setPids("[0],");
        }

    }
}
