package com.ruoyi.web.controller.warehouse.basicData;


import com.ruoyi.common.core.domain.entity.TWarehouse;
import com.ruoyi.basicData.service.ITWarehouseService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
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.Iterator;
import java.util.List;

/**
 * 仓库Controller
 *
 * @author ruoyi
 * @date 2020-12-11
 */
@RestController
@RequestMapping("/basicdata/warehouse")
public class TWarehouseController extends BaseController {
    @Autowired
    private ITWarehouseService tWarehouseService;

    /**
     * 查询仓库列表
     */
    @PreAuthorize("@ss.hasPermi('basicdata:warehouse:list')")
    @GetMapping("/list")
    public AjaxResult list(TWarehouse tWarehouse) {
        // startPage();
        List<TWarehouse> list = tWarehouseService.selectTWarehouseList(tWarehouse);
        return  AjaxResult.success(list); // getDataTable(list);
    }

    /**
     * 查询仓库列表
     */
    @GetMapping("/lists")
    public TableDataInfo lists(TWarehouse tWarehouse) {
        startPage();
        List<TWarehouse> list = tWarehouseService.selectTWarehouseLists(tWarehouse);
        return  getDataTable(list);
    }

    /**
     * 导出仓库列表
     */
    @PreAuthorize("@ss.hasPermi('basicdata:warehouse:export')")
    @Log(title = "仓库", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TWarehouse tWarehouse) {
        List<TWarehouse> list = tWarehouseService.selectTWarehouseList(tWarehouse);
        ExcelUtil<TWarehouse> util = new ExcelUtil<TWarehouse>(TWarehouse.class);
        return util.exportExcel(list, "warehouse");
    }

    /**
     * 获取仓库详细信息
     */
    @PreAuthorize("@ss.hasPermi('basicdata:warehouse:query')")
    @GetMapping(value = "/{fId}")
    public AjaxResult getInfo(@PathVariable Long fId) {
        return AjaxResult.success(tWarehouseService.selectTWarehouseById(fId));
    }

    /**
     * 查询仓库列表（排除节点）
     */
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<TWarehouse> tWarehouses = tWarehouseService.selectTWarehouseList(new TWarehouse());
        Iterator<TWarehouse> it = tWarehouses.iterator();
        while (it.hasNext()) {
            TWarehouse d = (TWarehouse) it.next();
            if (d.getfId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return AjaxResult.success(tWarehouses);
    }


    /**
     * 新增仓库
     */
   /* @PreAuthorize("@ss.hasPermi('basicdata:warehouse:add')")
    @Log(title = "仓库", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@RequestParam("tWarehouse") String tWarehouse, @RequestParam("tWarehouseArea") String tWarehouseArea) {
        // 检验编号、名称、地址 唯一
        TWarehouse tWarehouses = JSONArray.parseObject(tWarehouse, TWarehouse.class);
        if (UserConstants.NOT_UNIQUE.equals(tWarehouseService.checkUFNoUnique(tWarehouses))) {
            return AjaxResult.error("新增仓库'" + tWarehouses.getfNo() + "'失败，编号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(tWarehouseService.checkUFNnameUnique(tWarehouses))) {
            return AjaxResult.error("新增仓库'" + tWarehouses.getfName() + "'失败，名称已存在");
        }
        JSONArray jsonArray = JSONArray.parseArray(tWarehouseArea);
        List<TWarehouseArea> tWarehouseAreaList = JSONObject.parseArray(jsonArray.toJSONString(), TWarehouseArea.class);
        for (TWarehouseArea tWarehouseAreas : tWarehouseAreaList) {
            tWarehouseAreas.setfWarehouseid(tWarehouses.getfId());
            if (UserConstants.NOT_UNIQUE.equals(tWarehouseService.checkUFTWarehouseAreaNoUnique(tWarehouseAreas))) {
                return AjaxResult.error("新增仓库'" + tWarehouseAreas.getfNo() + "'失败，库区编号已存在");
            } else if (UserConstants.NOT_UNIQUE.equals(tWarehouseService.checkUTWarehouseAreaFNnameUnique(tWarehouseAreas))) {
                return AjaxResult.error("新增仓库'" + tWarehouseAreas.getfName() + "'失败，库区名称已存在");
            }
        }

        // 获取当前的用户
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return tWarehouseService.insertTWarehouse1(tWarehouse, tWarehouseArea, loginUser);
    }*/

    /**
     * 新增仓库
     */
    @PreAuthorize("@ss.hasPermi('basicdata:warehouse:add')")
    @Log(title = "仓库", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@Validated @RequestBody TWarehouse tWarehouse) {
        if (UserConstants.NOT_UNIQUE.equals(tWarehouseService.checkNameUnique(tWarehouse))) {
            return AjaxResult.error("新增仓库'" + tWarehouse.getfNo() + "'失败，仓库已存在");
        }
        tWarehouse.setCreateBy(SecurityUtils.getUsername());
        return toAjax(tWarehouseService.insertTWarehouse(tWarehouse));
    }

    /**
     * 修改仓库
     */
    /*@PreAuthorize("@ss.hasPermi('basicdata:warehouse:edit')")
    @Log(title = "仓库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWarehouse tWarehouse) {
        return tWarehouseService.updateTWarehouse(tWarehouse);
    }*/

    @PreAuthorize("@ss.hasPermi('basicdata:warehouse:edit')")
    @PutMapping
    @RepeatSubmit
    public AjaxResult edit(@Validated @RequestBody TWarehouse tWarehouse) {
        if (UserConstants.NOT_UNIQUE.equals(tWarehouseService.checkNameUnique(tWarehouse))) {
            return AjaxResult.error("修改仓库'" + tWarehouse.getfNo() + "'失败，仓库已存在");
        }
        tWarehouse.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(tWarehouseService.updateTWarehouses(tWarehouse));
    }


    /**
     * 删除仓库
     */
    /*@PreAuthorize("@ss.hasPermi('basicdata:warehouse:remove')")
    @Log(title = "仓库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{fIds}")
    @RepeatSubmit
    public AjaxResult remove(@PathVariable Long[] fIds) {
        return tWarehouseService.deleteTWarehouseByIds(fIds);
    }*/

    /**
     * 删除仓库
     */
    @PreAuthorize("@ss.hasPermi('basicdata:warehouse:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{fId}")
    @RepeatSubmit
    public AjaxResult removeWarehouse(@PathVariable Long fId) {
        if (tWarehouseService.hasChildByfId(fId)) {
            return AjaxResult.error("存在下级,不允许删除");
        }
        // 获取仓库信息
        TWarehouse tWarehouse = tWarehouseService.selectTWarehouseById(fId);
        if(tWarehouse.getfLocation()==1){ // 库位
            if (tWarehouseService.checkDeptExistWarehouseItems(fId)) {
                return AjaxResult.error("库位存在货物,不允许删除");
            }
        } else if (tWarehouse.getParentId() == 100){ //  仓库
            if (tWarehouseService.checkDeptExistWarehouse(fId)) {
                return AjaxResult.error("仓库存在货物,不允许删除");
            }
        }
        return toAjax(tWarehouseService.deleteTWarehouseById(fId));
    }


    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(TWarehouse tWarehouse) {
        List<TWarehouse> tWarehouses = tWarehouseService.selectTWarehouseList(tWarehouse);
        return AjaxResult.success(tWarehouseService.buildDeptTreeSelect(tWarehouses));
    }



}
