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

import cn.ezhizao.common.exception.ServiceException;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.accountAdjustment.domain.BizFinancialAccountAdjustment;
import cn.ezhizao.project.business.company.domain.BizCompany;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
import cn.ezhizao.project.business.keepAccounts.domain.BizFinancialKeepAccount;
import cn.ezhizao.project.business.keepAccounts.domain.BizFinancialKeepAccountDetail;
import cn.ezhizao.project.business.keepAccounts.service.IBizFinancialKeepAccountDetailService;
import cn.ezhizao.project.business.keepAccounts.service.IBizFinancialKeepAccountService;
import cn.ezhizao.project.business.urgent.domain.BizFinancialUrgent;
import cn.ezhizao.project.business.urgent.service.IBizFinancialUrgentService;
import cn.ezhizao.project.business.workOrder.domain.BizWorkOrder;
import cn.ezhizao.project.business.workOrder.service.IBizWorkOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author 周晓
 */
@RestController
@Api(tags = "FinancialUngent数据接口")
@RequestMapping(value = "/business/financialUrgent")
public class BizFinancialUrgentController extends BaseController {

    @Resource
    IBizFinancialUrgentService financialUrgentService;

    @Resource
    IBizCompanyService companyService;
    @Resource
    IBizWorkOrderService workOrderService;
    @Resource
    IBizFinancialKeepAccountService keepAccountService;
    @Resource
    IBizFinancialKeepAccountDetailService keepAccountDetailService;

    @ApiOperation(value = "根据id查询",notes = "根据id查询")
    @GetMapping("/getById/{id}")
    @ResponseBody
    public AjaxResult getById(@PathVariable Long id){
        return success(financialUrgentService.getById(id));
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存",notes = "保存")
    @ResponseBody
    public AjaxResult save(@RequestBody BizFinancialUrgent financialUrgent){
        financialUrgent.setApplierId(financialUrgent.getEmployeeId());
        return (financialUrgent.getId()==null? financialUrgentService.save(financialUrgent): financialUrgentService.updateById(financialUrgent))?success():error();
    }

    @PostMapping("/saveBatch")
    @ApiOperation(value = "批量保存",notes = "批量保存")
    @ResponseBody
    public AjaxResult saveBatch(@RequestBody List<BizFinancialUrgent> list){
        return financialUrgentService.saveOrUpdateBatch(list)?success():error();
    }

    @ApiOperation(value = "删除",notes = "删除")
    @GetMapping("/deleteById/{id}")
    @ResponseBody
    public AjaxResult deleteById(@PathVariable Long id){
        return financialUrgentService.removeById(id)?success():error();
    }

    @ApiOperation(value = "批量删除",notes = "批量删除")
    @PostMapping("/batchDelete")
    @ResponseBody
    public AjaxResult batchDelete(@RequestBody List<Long> list){
        return financialUrgentService.removeBatchByIds(list)?success():error();
    }

    @ApiOperation(value = "带条件List 分页查询",notes= "带条件List 分页查询")
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('business:urgent:list')")
    @ResponseBody
    public TableDataInfo getList( BizFinancialUrgent conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startPage();
        List<BizFinancialUrgent> list = financialUrgentService.getListByBean(conditions);
//        .stream().filter(s -> s.getCompanyName().contains(companyName)).collect(Collectors.toList())

        return getDataTable(list);
    }


    @ApiOperation("获取客户列表")
    @GetMapping("/listCompany")
    @PreAuthorize("@ss.hasPermi('business:urgent:add')")
    public TableDataInfo getCompanyList(BizCompany conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        List<BizCompany> companies = companyService.getList(conditions);
        startPage();
        return getDataTable(companies);
    }

    @ApiOperation("获取账期")
    @GetMapping("/getCreditTermByCompId")
    @PreAuthorize("@ss.hasPermi('business:urgent:add')")
    public AjaxResult getCreditTermByCompId(BizCompany company) {
        BizWorkOrder conditions = new BizWorkOrder();
        conditions.setCompanyId(company.getId());
        conditions.setTaskTypeId(1L);
        conditions.setIsStop(0);
        List<BizWorkOrder> workOrders = workOrderService.getList(conditions);
        if (workOrders.isEmpty()) {
            throw new ServiceException("该客户没有账期");
        }
        Long workOrderId = workOrders.get(0).getId();
        BizFinancialKeepAccount keepAccountConditions = new BizFinancialKeepAccount();
        keepAccountConditions.setWorkOrderId(workOrderId);
        List<BizFinancialKeepAccount> keepAccounts = keepAccountService.getList(keepAccountConditions);
        if (keepAccounts.isEmpty()) {
            throw new ServiceException("该客户没有账期");
        }
        List<BizFinancialKeepAccountDetail> details = keepAccountDetailService.query().eq("financial_keep_account_id", keepAccounts.get(0).getId()).list();
        List<Map<String, Object>> checkouts = details.stream().map(v -> {
            Map<String, Object> map = new HashMap<>();
            map.put("checkDate", v.getYear() + "-" + v.getMonth() + "-01");
            map.put("year", v.getYear());
            map.put("month", v.getMonth());
            return map;
        }).collect(Collectors.toList());
        checkouts.sort(Comparator.comparing(v -> v.get("checkDate").toString()));
        return checkouts.isEmpty() ? success(null) : success(checkouts.get(checkouts.size() - 1));
    }

    /**
     * 新增委托
     */
    @PreAuthorize("@ss.hasPermi('business:urgent:add')")
    @Log(title = "委托", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizFinancialUrgent urgent) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(urgent);
        return toAjax(financialUrgentService.save(urgent));
    }

    /**
     * 修改委托
     */
    @PreAuthorize("@ss.hasPermi('business:urgent:edit')")
    @Log(title = "委托", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizFinancialUrgent urgent) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(urgent);
        return toAjax(financialUrgentService.updateById(urgent));
    }

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

    /**
     * 获取委托详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:urgent:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        BizFinancialUrgent conditions = new BizFinancialUrgent();
        conditions.setId(id);
        return success(financialUrgentService.getListByBean(conditions).stream().findFirst().orElse(new BizFinancialUrgent()));
    }
}
