package com.ruoyi.order.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.asset.domain.TbAssetInformation;
import com.ruoyi.asset.mapper.TbAssetInformationMapper;
import com.ruoyi.asset.service.ITbAssetInformationService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.order.domain.dto.OrderDTO;
import com.ruoyi.order.domain.dto.OrderTypeEnum;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.order.domain.TbOrder;
import com.ruoyi.order.service.ITbOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 资产单据Controller
 * 
 * @author 原动力
 * @date 2023-05-24
 */
@RestController
@RequestMapping("/order/order")
public class TbOrderController extends BaseController
{
    @Autowired
    private ITbOrderService tbOrderService;

    @Resource
    private ISysDeptService sysDeptService;

    @Resource
    private ITbAssetInformationService tbAssetInformationService;

    /**
     * 查询资产单据列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(TbOrder tbOrder)
    {
        startPage();
        List<TbOrder> list = tbOrderService.selectTbOrderList(tbOrder);
        ArrayList<OrderDTO> orderList = new ArrayList<>();
        for (TbOrder order : list) {
            OrderDTO orderDTO = BeanUtil.toBean(order, OrderDTO.class);
            String applicationDepartment = order.getApplicationDepartment();
            if (StrUtil.isNotBlank(applicationDepartment)) {
                SysDept sysDept = sysDeptService.selectDeptById(Long.valueOf(applicationDepartment));
                if (sysDept != null) {
                    orderDTO.setApplicationDepartmentName(sysDept.getDeptName());
                }
            }
            String preparedDepartment = order.getPreparedDepartment();
            if (StrUtil.isNotBlank(preparedDepartment)) {
                SysDept sysDept = sysDeptService.selectDeptById(Long.valueOf(preparedDepartment));
                if (sysDept != null) {
                    orderDTO.setPreparedDepartmentName(sysDept.getDeptName());
                }
            }
            String lendDepartment = order.getLendDepartment();
            if (StrUtil.isNotBlank(lendDepartment)) {
                SysDept sysDept = sysDeptService.selectDeptById(Long.valueOf(lendDepartment));
                if (sysDept != null) {
                    orderDTO.setLendDepartmentName(sysDept.getDeptName());
                }
            }
            String allocationCallOutDepartment = order.getAllocationCallOutDepartment();
            if (StrUtil.isNotBlank(allocationCallOutDepartment)) {
                SysDept sysDept = sysDeptService.selectDeptById(Long.valueOf(allocationCallOutDepartment));
                if (sysDept != null) {
                    orderDTO.setAllocationCallOutDepartmentName(sysDept.getDeptName());
                }
            }
            String allocationCallInDepartment = order.getAllocationCallInDepartment();
            if (StrUtil.isNotBlank(allocationCallInDepartment)) {
                SysDept sysDept = sysDeptService.selectDeptById(Long.valueOf(allocationCallInDepartment));
                if (sysDept != null) {
                    orderDTO.setAllocationCallInDepartmentName(sysDept.getDeptName());
                }
            }
            String corporation = order.getCorporation();
            if (StrUtil.isNotBlank(corporation)) {
                SysDept sysDept = sysDeptService.selectDeptById(Long.valueOf(corporation));
                if (sysDept != null) {
                    orderDTO.setCorporationName(sysDept.getDeptName());
                }
            }
            orderList.add(orderDTO);
        }
        return getDataTable(orderList);
    }

    /**
     * 导出资产单据列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:export')")
    @Log(title = "资产单据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbOrder tbOrder)
    {
        List<TbOrder> list = tbOrderService.selectTbOrderList(tbOrder);
        ExcelUtil<TbOrder> util = new ExcelUtil<TbOrder>(TbOrder.class);
        util.exportExcel(response, list, "资产单据数据");
    }

    /**
     * 获取资产单据详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tbOrderService.selectTbOrderById(id));
    }

    /**
     * 新增资产单据
     */
    @PreAuthorize("@ss.hasPermi('order:order:add')")
    @Log(title = "资产单据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbOrder tbOrder)
    {
        Long type = tbOrder.getOrderType();
        boolean result = OrderTypeEnum.checkout(type);
        if (!result) {
            return AjaxResult.error(MessageUtils.message("order.type.not.exist"));
        }

        String orderNumber = "";
        String dateTimeId = DateUtils.dateTimeNow("yyyyMMddHHmmssSSS");
        Long orderType = tbOrder.getOrderType();
        for (OrderTypeEnum typeEnum : OrderTypeEnum.values()) {
            if (typeEnum.getTypeCode().equals(orderType)) {
                orderNumber = typeEnum.getTypeName() + dateTimeId;
            }
        }
        tbOrder.setOrderNumber(orderNumber);

        if (type.equals(OrderTypeEnum.ADJUSTMENT.getTypeCode())) {
            // 资产调整，即修改资产信息后记录
            // 需要传参 AdjustmentAssetNumber 资产编号、AdjustmentOriginalAssetInfo 资产原信息JSON字符串格式
            TbOrder.adjustmentOrder(tbOrder);

            AjaxResult ajaxResult = checkAdjustment(tbOrder);

            if (ajaxResult != null) {
                return ajaxResult;
            }
        } else if (type.equals(OrderTypeEnum.ALLOCATION.getTypeCode())) {
            // 资产调拨
            TbOrder.allocationOrder(tbOrder);

            AjaxResult ajaxResult = checkAllocationOrder(tbOrder);

            if (ajaxResult != null) {
                return ajaxResult;
            }
        } else if (type.equals(OrderTypeEnum.LEND.getTypeCode())) {
            // 资产借出
            TbOrder.lendOrder(tbOrder);

            AjaxResult ajaxResult = checkLendOrder(tbOrder);

            if (ajaxResult != null) {
                return ajaxResult;
            }
        } else {
            // 资产其他变动
            TbOrder.otherOrder(tbOrder);
        }

        if (tbOrder.getRecordStatus() == 1) {
            AjaxResult ajaxResult = checkOrder(tbOrder);
            if (ajaxResult != null) {
                return ajaxResult;
            }
        }

        tbOrder.setPreparedBy(getUsername());
        tbOrder.setPreparedDepartment(getDeptId().toString());

        SysDept sysDept = sysDeptService.selectDeptById(getDeptId());
        if (sysDept == null) {
            return error("部门不存在");
        }
        String ancestors = sysDept.getAncestors();
        String[] split = ancestors.split(",");
        String deptId;
        if (split.length > 2) {
            deptId = split[2];
        } else {
            deptId = split[split.length - 1];
        }
        tbOrder.setCorporation(deptId);

        return toAjax(tbOrderService.insertTbOrder(tbOrder));
    }

    /**
     * 修改资产单据
     */
    @PreAuthorize("@ss.hasPermi('order:order:edit')")
    @Log(title = "资产单据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbOrder tbOrder)
    {
        return toAjax(tbOrderService.updateTbOrder(tbOrder));
    }

    /**
     * 删除资产单据
     */
    @PreAuthorize("@ss.hasPermi('order:order:remove')")
    @Log(title = "资产单据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tbOrderService.deleteTbOrderByIds(ids));
    }
    /** 检验单据 */
    private AjaxResult checkOrder(TbOrder tbOrder) {

        Date applicationDate = tbOrder.getApplicationDate();
        String applicationDepartment = tbOrder.getApplicationDepartment();
        String reason = tbOrder.getReason();

        if (applicationDate == null) {
            return error("申请日期不能为空");
        }
        if (StrUtil.isBlank(applicationDepartment)) {
            return error("申请部门不能为空");
        }
        if (StrUtil.isBlank(reason)) {
            return error("原因说明不能为空");
        }

        if (!tbOrder.getOrderType().equals(OrderTypeEnum.ADJUSTMENT.getTypeCode())) {
            String assetTotalNetValue = tbOrder.getAssetTotalNetValue();
            String assetTotalOriginalValue = tbOrder.getAssetTotalOriginalValue();
            if (StrUtil.isBlank(assetTotalNetValue)) {
                return error("资产总净值不能为空");
            }
            if (StrUtil.isBlank(assetTotalOriginalValue)) {
                return error("资产总原值不能为空");
            }
        }

        return null;
    }

    /** 检验调整单据 */
    private AjaxResult checkAdjustment(TbOrder tbOrder) {
        String adjustmentAssetNumber = tbOrder.getAdjustmentAssetNumber();
        if (StrUtil.isBlank(adjustmentAssetNumber)) {
            return error("资产编号不能为空");
        }
        TbAssetInformation tbAssetInformation = tbAssetInformationService.selectTbAssetAdjustmentByAssetNumber(adjustmentAssetNumber);
        if (tbAssetInformation == null) {
            return error("调整资产不存在");
        }
        String jsonStr = JSONUtil.toJsonStr(tbAssetInformation);
        tbOrder.setAdjustmentOriginalAssetInfo(jsonStr);
        return null;
    }

    /** 检验调拨单据 */
    private AjaxResult checkAllocationOrder(TbOrder tbOrder) {
        String allocationCallInBy = tbOrder.getAllocationCallInBy();
        Date allocationCallInDate = tbOrder.getAllocationCallInDate();
        String allocationCallInDepartment = tbOrder.getAllocationCallInDepartment();
        String allocationCallOutBy = tbOrder.getAllocationCallOutBy();
        Date allocationCallOutDate = tbOrder.getAllocationCallOutDate();
        String allocationCallOutDepartment = tbOrder.getAllocationCallOutDepartment();
        String allocationNewLocationNumber = tbOrder.getAllocationNewLocationNumber();
        String allocationNewResponsiblePerson = tbOrder.getAllocationNewResponsiblePerson();

        if (StrUtil.isBlank(allocationCallInBy)) {
            return error("调入经办人不能为空");
        }

        if (allocationCallInDate == null) {
            return error("调入日期不能为空");
        }

        if (StrUtil.isBlank(allocationCallInDepartment)) {
            return error("调入部门不能为空");
        }

        if (StrUtil.isBlank(allocationCallOutBy)) {
            return error("调出经办人不能为空");
        }

        if (allocationCallOutDate == null) {
            return error("调出日期不能为空");
        }

        if (StrUtil.isBlank(allocationCallOutDepartment)) {
            return error("调出部门不能为空");
        }

        if (StrUtil.isBlank(allocationNewLocationNumber)) {
            return error("新功能位置编号不能为空");
        }

        if (StrUtil.isBlank(allocationNewResponsiblePerson)) {
            return error("新管理人不能为空");
        }

        return null;
    }

    /** 检验借出单据 */
    private AjaxResult checkLendOrder(TbOrder tbOrder) {
        String lendDepartment = tbOrder.getLendDepartment();
        String lendBySponsor = tbOrder.getLendBySponsor();
        String lendPassingUnit = tbOrder.getLendPassingUnit();

        if (StrUtil.isBlank(lendDepartment)) {
            return error("借出部门不能为空");
        }

        if (StrUtil.isBlank(lendBySponsor)) {
            return error("借出经手人不能为空");
        }

        if (StrUtil.isBlank(lendPassingUnit)) {
            return error("往来单位不能为空");
        }

        return null;
    }


}
