package com.jeethink.dataCenter.controller;

import com.jeethink.common.constant.Constants;
import com.jeethink.common.constant.UserConstants;
import com.jeethink.common.core.controller.BaseController;
import com.jeethink.common.core.domain.AjaxResult;
import com.jeethink.common.utils.SecurityUtils;
import com.jeethink.common.utils.StringUtils;
import com.jeethink.dataCenter.domain.Warehouse;
import com.jeethink.dataCenter.service.IWarehouseService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * 库房信息
 *
 * @author wms
 */
@RestController
@RequestMapping("/datacenter/warehouse")
public class WarehouseController extends BaseController
{

    @Autowired
    private IWarehouseService warehouseService;

    /**
     * 获取库房列表
     */
    @PreAuthorize("@ss.hasPermi('datacenter:warehouse:list')")
    @GetMapping("/list")
    public AjaxResult list(Warehouse warehouse)
    {

        List<Warehouse> warehouseList = warehouseService.selectWarehouseList(warehouse);
        return AjaxResult.success(warehouseList);
    }

    /**
     * 查询库房树数据
     */
    @PreAuthorize("@ss.hasPermi('datacenter:warehouse:list')")
    @GetMapping("/tree")
    public AjaxResult tree()
    {
        List<Warehouse> list = warehouseService.selectWarehouseList(new Warehouse());
        Iterator<Warehouse> it = list.iterator();
        while (it.hasNext())
        {
            Warehouse wh = it.next();
            if (wh.getLevel() >= Constants.WAREHOUSE_LEVEL_MAX) {
                it.remove();
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 查询库房树数据（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('datacenter:warehouse:list')")
    @GetMapping("/tree/exclude/{id}")
    public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id)
    {
        Warehouse warehouse = warehouseService.selectWarehouseById(id);
        List<Warehouse> warehouseList = warehouseService.selectWarehouseList(new Warehouse());
        Iterator<Warehouse> it = warehouseList.listIterator();
        while (it.hasNext())
        {
            Warehouse wh = it.next();
            if (wh.getId().intValue() == id
                || ArrayUtils.contains(StringUtils.split(wh.getAncestors(), ","), id + "")
                || wh.getLevel() >= Constants.WAREHOUSE_LEVEL_MAX)
            {
                it.remove();
            }
        }
        return AjaxResult.success(warehouseList);
    }

    /**
     * 根据主键获取详情
     */
    @PreAuthorize("@ss.hasPermi('datacenter:warehouse:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return AjaxResult.success(warehouseService.selectWarehouseById(id));
    }

    /**
     * 新增库房
     */
    @PreAuthorize("@ss.hasPermi('datacenter:warehouse:add')")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Warehouse warehouse)
    {
        if (StringUtils.isNotNull(warehouse.getRelaUser()))
        {
            if (warehouse.getLevel() < Constants.WAREHOUSE_LEVEL_MAX)//层级为4（档案卷）才能关联人
            {
                return AjaxResult.error("新增库房“" + warehouse.getName() + "”失败，该等级不能关联人员");
            }
            else
            {
                List<Warehouse> list = warehouseService.selectWarehouseByRelaUser(warehouse.getRelaUser());
                if (list.size() > 0) {
                    return AjaxResult.error("新增库房“" + warehouse.getName() + "”失败，关联人员已与“"+list.get(0).getName()+"”关联");
                }
            }
        }

        warehouse.setCreateBy(SecurityUtils.getUsername());
        warehouse.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(warehouseService.insertWarehouse(warehouse));
    }

    /**
     * 修改库房
     */
    @PreAuthorize("@ss.hasPermi('datacenter:warehouse:edit')")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Warehouse warehouse)
    {
        if (StringUtils.isNotNull(warehouse.getRelaUser()))
        {
            if (warehouse.getLevel() < Constants.WAREHOUSE_LEVEL_MAX)//层级为4（档案卷）才能关联人
            {
                return AjaxResult.error("修改库房“" + warehouse.getName() + "”失败，该等级不能关联人员");
            }
            else
            {
                List<Warehouse> list = warehouseService.selectWarehouseByRelaUser(warehouse.getRelaUser());
                if (list.size() > 1) {
                    return AjaxResult.error("修改库房“" + warehouse.getName() + "”失败，关联人员已与其他库房关联");
                }
                if (list.size() > 0 && !list.get(0).getId().equals(warehouse.getId())) {
                    return AjaxResult.error("修改库房“" + warehouse.getName() + "”失败，关联人员已与“"+list.get(0).getName()+"”关联");
                }
            }
        }
        else if (warehouse.getParentId().equals(warehouse.getId()))
        {
            return AjaxResult.error("修改库房'" + warehouse.getName() + "'失败，上级库房不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, warehouse.getStatus())
                && warehouseService.selectNormalChildrenById(warehouse.getId()) > 0)
        {
            return AjaxResult.error("该库房包含未停用的子库房！");
        }
        warehouse.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(warehouseService.updateWarehouse(warehouse));
    }

    /**
     * 删除库房
     */
    @PreAuthorize("@ss.hasPermi('datacenter:warehouse:remove')")
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        if (warehouseService.hasChildById(id))
        {
            return AjaxResult.error("存在下级库房，不允许删除");
        }
        return toAjax(warehouseService.deleteWarehouseById(id));
    }

    @PostMapping("/realArchives")
    public AjaxResult realArchives(@Validated @RequestBody HashMap hashMap){
        List<String> list = (List<String>) hashMap.get("list");
        Long id = Long.valueOf((Integer) hashMap.get("id"));
        String ancestorsId = (String) hashMap.get("ancestorsId");
        int i = 0;
        warehouseService.deleteArchives(id);
        if(list.size()>0){
            for(String archivesId : list){
                String name=warehouseService.selectArchivesById(archivesId);
                Warehouse warehouse = new Warehouse();
                warehouse.setParentId(id);
                warehouse.setArchivesId(archivesId);
                warehouse.setAncestors(ancestorsId);
                warehouse.setCreateBy(SecurityUtils.getUsername());
                warehouse.setUpdateBy(SecurityUtils.getUsername());
                warehouse.setLevel(5);
                warehouse.setStatus("0");
                warehouse.setOrderNum(i);
                warehouse.setName(name);
                warehouseService.insertWarehouse(warehouse);
                i++;
            }
        }
        return AjaxResult.success();
    }
    @GetMapping("/selectArchives/{parentId}")
    public AjaxResult selectArchives(@PathVariable Long parentId)
    {
        return AjaxResult.success(warehouseService.selectArchivesByParentId(parentId));
    }
}
