package cn.ezhizao.project.business.accountAdjustment.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.accountAdjustment.service.BizFinancialAccountAdjustmentService;
import cn.ezhizao.project.business.company.domain.BizCompany;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
import cn.ezhizao.project.business.entrust.domain.BizEntrust;
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.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.web.bind.annotation.*;

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


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

    @Resource
    BizFinancialAccountAdjustmentService financialAccountAdjustmentService;

    @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(financialAccountAdjustmentService.getById(id));
    }

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

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

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

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

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('business:accountAdjustment:list')")
    @ResponseBody
    public TableDataInfo getList( BizFinancialAccountAdjustment conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startPage();
        //分页数据
        List<BizFinancialAccountAdjustment> list = financialAccountAdjustmentService.getListByBean(conditions);
        return getDataTable(list);
    }

    @ApiOperation("获取客户列表")
    @GetMapping("/listCompany")
    @PreAuthorize("@ss.hasPermi('business:accountAdjustment: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:accountAdjustment:add')")
    public TableDataInfo 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());
        return getDataTable(checkouts);
    }

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

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

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

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