package cn.ezhizao.project.business.entrustOrder.controller;

import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.project.business.deduct.domain.BizDeduct;
import cn.ezhizao.project.business.deduct.service.IBizDeductService;
import cn.ezhizao.project.business.entrust.domain.BizEntrust;
import cn.ezhizao.project.business.entrust.service.IBizEntrustService;
import cn.ezhizao.project.tenant.domain.Tenant;
import cn.ezhizao.project.tenant.service.ITenantService;
import cn.hutool.core.date.DateTime;
import org.springframework.security.access.prepost.PreAuthorize;
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 cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.project.business.entrustOrder.domain.BizEntrustOrder;
import cn.ezhizao.project.business.entrustOrder.service.IBizEntrustOrderService;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.web.page.TableDataInfo;

/**
 * 委托签约合同Controller
 *
 * @author ruoyi
 * @date 2023-12-05
 */
@RestController
@RequestMapping("/business/entrustOrder")
public class BizEntrustOrderController extends BaseController {
    @Resource
    private IBizEntrustOrderService bizEntrustOrderService;
    @Resource
    private IBizEntrustService entrustService;
    @Resource
    private ITenantService tenantService;
    @Resource
    private IBizDeductService bizDeductService;

    /**
     * 查询委托签约合同列表
     */
    @PreAuthorize("@ss.hasPermi('business:entrustOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizEntrustOrder bizEntrustOrder) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizEntrustOrder);
        startPage();
        startOrderBy();
        List<BizEntrustOrder> list = bizEntrustOrderService.getList(bizEntrustOrder);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('business:entrustOrder:confirm')")
    @Log(title = "委托签约合同", businessType = BusinessType.UPDATE)
    @PostMapping("/confirm")
    public AjaxResult confirm(@RequestBody BizEntrustOrder bizEntrustOrder) {
        bizEntrustOrder.setStatus(1);
        return toAjax(bizEntrustOrderService.updateById(bizEntrustOrder));
    }

    @PreAuthorize("@ss.hasPermi('business:entrustOrder:finished')")
    @Log(title = "委托签约合同", businessType = BusinessType.UPDATE)
    @PostMapping("/finished")
    public AjaxResult finished(@RequestBody BizEntrustOrder bizEntrustOrder) {
        bizEntrustOrder.setStatus(2);
        return toAjax(bizEntrustOrderService.updateById(bizEntrustOrder));
    }

    /**
     * 导出委托签约合同列表
     */
    @PreAuthorize("@ss.hasPermi('business:entrustOrder:export')")
    @Log(title = "委托签约合同", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizEntrustOrder bizEntrustOrder) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizEntrustOrder);
        startOrderBy();
        List<BizEntrustOrder> list = bizEntrustOrderService.getList(bizEntrustOrder);
        list.forEach(l->{
            switch (l.getStatus()) {
                case 0:
                    l.setStatusTyp("未签订");
                    break;
                case 1:
                    l.setStatusTyp("进行中");
                    break;
                case 2:
                    l.setStatusTyp("已完成");
                    break;
            }
        });
        ExcelUtil<BizEntrustOrder> util = new ExcelUtil<BizEntrustOrder>(BizEntrustOrder.class);
        util.exportExcel(response, list, "委托签约合同数据");
    }

    /**
     * 获取委托签约合同详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:entrustOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        BizEntrustOrder condition = new BizEntrustOrder();
        condition.setId(id);
        BizEntrustOrder item = bizEntrustOrderService.getList(condition).stream().findFirst().orElse(null);
        return success(item);
    }

    /**
     * 新增委托签约合同
     */
    @PreAuthorize("@ss.hasPermi('business:entrustOrder:add')")
    @Log(title = "委托签约合同", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizEntrustOrder bizEntrustOrder) throws NoSuchFieldException, IllegalAccessException {
        /* 校验是否存在同家公司未完结的合同*/
        //空对象
        BizEntrustOrder order = new BizEntrustOrder();
        setTenantId(order);
        //往来单位赋值
        order.setFromTenantId(bizEntrustOrder.getFromTenantId());
        //查询是否存在相同的往来单位
        List<BizEntrustOrder> list = bizEntrustOrderService.getList(order);
        //存在相同的往来单位
        if (list.size() > 0) {
            for (BizEntrustOrder item : list) {
                //判断合同是否完结
                if (item.getStatus() != 2) {

                    return AjaxResult.error("不能新建同家公司新合同");
                }
            }
        }

        return toAjax(bizEntrustOrderService.save(bizEntrustOrder));
    }

    /**
     * 修改委托签约合同
     */
    @PreAuthorize("@ss.hasPermi('business:entrustOrder:edit')")
    @Log(title = "委托签约合同", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizEntrustOrder bizEntrustOrder) throws NoSuchFieldException, IllegalAccessException {
        return toAjax(bizEntrustOrderService.updateById(bizEntrustOrder));
    }

    /**
     * 删除委托签约合同
     */
    @PreAuthorize("@ss.hasPermi('business:entrustOrder:remove')")
    @Log(title = "委托签约合同", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(bizEntrustOrderService.removeBatchByIds(ids));
    }

    @PreAuthorize("@ss.hasAnyPermi('business:entrustOrder:add,business:entrustOrder:edit')")
    @GetMapping("/listTenant")
    public TableDataInfo listTenant(Tenant tenant) {
        startPage();
        if (StringUtils.isNotBlank(tenant.getOperateType())) {
            tenant.setUserId(SecurityUtils.getUserId());
        }
        List<Tenant> list = tenantService.getList(tenant);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasAnyPermi('business:entrustOrder:add')")
    @GetMapping("/getMonths/{entrustOrderId}")
    public AjaxResult getMonths(@PathVariable Long entrustOrderId) {
        // 根据Tenant获取没有对账的委托月
        // BizDeduct deduct = bizDeductService.query().eq("entrust_order_id", entrustOrderId).orderByDesc("year", "month").last("limit 1").one();
        BizEntrustOrder entrustOrder = bizEntrustOrderService.getById(entrustOrderId);
        // 所有委托月
        List<BizEntrust> entrust = entrustService.query().eq("from_tenant_id", entrustOrder.getFromTenantId()).eq("to_tenant_id", entrustOrder.getTenantId()).list();
        List<BizDeduct> deducts = bizDeductService.query().eq("from_tenant_id", entrustOrder.getFromTenantId()).eq("tenant_id", entrustOrder.getTenantId()).list();
        entrust = entrust.stream().filter(v -> v.getWorkMonth() != null &&
                deducts.stream().noneMatch(e -> v.getWorkMonth().compareTo(e.getStartMonth()) >= 0 && v.getWorkMonth().compareTo(e.getEndMonth()) <= 0)
        ).collect(Collectors.toList());
        List<String> months = entrust.stream().map(v -> DateTime.of(v.getWorkMonth()).toString("yyyy-MM-dd")).distinct().sorted().collect(Collectors.toList());
        return success(months);
    }

}
