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

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.archiveTicket.domain.BizArchiveReceiveTicket;
import cn.ezhizao.project.business.archiveTicket.service.IBizArchiveReceiveTicketService;
import cn.ezhizao.project.business.entrust.domain.BizEntrust;
import cn.ezhizao.project.business.entrust.service.IBizEntrustService;
import cn.ezhizao.project.business.financialBase.domain.BizArchiveReceiveTicketFinished;
import cn.ezhizao.project.business.financialBase.service.IBizArchiveReceiveTicketFinishedService;
import cn.ezhizao.project.business.keepAccounts.domain.BizFinancialKeepAccount;
import cn.ezhizao.project.business.keepAccounts.domain.BizFinancialKeepAccountDetail;
import cn.ezhizao.project.business.keepAccounts.service.IBizFinancialKeepAccountService;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
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;

@RestController
@Api(tags = "收票 数据接口")
@RequestMapping(value = "/business/archiveTicket")
public class ArchiveTicketController extends BaseController {
    @Resource
    IBizFinancialKeepAccountService financialKeepAccountService;
    @Resource
    IBizArchiveReceiveTicketService bizArchiveReceiveTicketService;
    @Resource
    IBizEntrustService entrustService;

    @Resource
    IBizArchiveReceiveTicketFinishedService archiveReceiveTicketFinishedService;

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo getList(BizFinancialKeepAccount conditions) throws NoSuchFieldException, IllegalAccessException {

        String month = String.format("%02d", Integer.valueOf(conditions.getMonth()));
        conditions.setMonth(month);
        setTenantId(conditions);
        startPage();
        startOrderBy();
        List<BizFinancialKeepAccount> list = financialKeepAccountService.getList(conditions);
        return getDataTable(list);
    }
    @PostMapping("/save")
    @ApiOperation(value = "保存", notes = "保存")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult save(@RequestBody BizArchiveReceiveTicket archiveReceiveTicket) {

//        return (archiveReceiveTicket.getId() == null ? archiveReceiveTicketService.save(archiveReceiveTicket) : archiveReceiveTicketService.updateById(archiveReceiveTicket)) ? Rutils.success() : Rutils.error();
//        Map<String, Object> deleteCondition = new HashMap<>();
//        deleteCondition.put("companyId", archiveReceiveTicket.getCompanyId());
//        deleteCondition.put("year", archiveReceiveTicket.getYear());
//        deleteCondition.put("month", archiveReceiveTicket.getMonth());
        BizArchiveReceiveTicket deleteCondition = new BizArchiveReceiveTicket();
        deleteCondition.setYear(archiveReceiveTicket.getYear());
        deleteCondition.setMonth(archiveReceiveTicket.getMonth());
        deleteCondition.setCompanyId(archiveReceiveTicket.getCompanyId());
        bizArchiveReceiveTicketService.physicalDelete(deleteCondition);
        archiveReceiveTicket.getFiles().forEach(l -> {
            l.setYear(archiveReceiveTicket.getYear());
            l.setMonth(archiveReceiveTicket.getMonth());
            l.setCompanyId(archiveReceiveTicket.getCompanyId());
        });
        if (archiveReceiveTicket.getIsFinished().equals(1) || archiveReceiveTicket.getUploadTicketFinished() != null) {
            BizArchiveReceiveTicketFinished uploadTicketFinished = archiveReceiveTicket.getUploadTicketFinished() != null ? archiveReceiveTicketFinishedService.getById(archiveReceiveTicket.getUploadTicketFinished().getId()) : new BizArchiveReceiveTicketFinished();
            uploadTicketFinished.setYear(archiveReceiveTicket.getYear());
            uploadTicketFinished.setMonth(archiveReceiveTicket.getMonth());
            uploadTicketFinished.setCompanyId(archiveReceiveTicket.getCompanyId());
            uploadTicketFinished.setIsFinished(archiveReceiveTicket.getIsFinished());
            archiveReceiveTicketFinishedService.saveOrUpdate(uploadTicketFinished);
        }
        return archiveReceiveTicket.getFiles().isEmpty() ||  bizArchiveReceiveTicketService.saveOrUpdateBatch(archiveReceiveTicket.getFiles()) ? success(archiveReceiveTicket) : error();
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @GetMapping("/listFiles")
    @ResponseBody
    public AjaxResult getFiles(BizArchiveReceiveTicket conditions) throws NoSuchFieldException, IllegalAccessException {
//        setTenantId(conditions);
//        startPage();
        List<BizArchiveReceiveTicket> list = bizArchiveReceiveTicketService.getList(conditions);
        Map<String, Object> map = new HashMap<>();
        map.put("files", list);
        // 获取受委托账期
        BizEntrust entrustConditions = new BizEntrust();
        entrustConditions.setCompanyId(conditions.getCompanyId());
        entrustConditions.setTaskTypeId(1L);
        List<BizEntrust>entrusts = entrustService.getList(entrustConditions);
        entrusts.sort(Comparator.comparing(BizEntrust::getWorkMonth).reversed());
        List<Map<String, Object>> workMonths = entrusts.stream().map(v -> {
            Map<String, Object> month = new HashMap<>();
            month.put("id", v.getId());
            month.put("year", DateTime.of(v.getCurrentMonth()).toString("yyyy"));
            month.put("month", DateTime.of(v.getCurrentMonth()).toString("MM"));
            month.put("currentMonth", DateTime.of(v.getCurrentMonth()).toString("yyyy年MM月"));
            month.put("companyId", v.getCompanyId());
            return month;
        }).collect(Collectors.toList());
        map.put("months", workMonths);

        BizArchiveReceiveTicketFinished finished = new BizArchiveReceiveTicketFinished();
        finished.setCompanyId(conditions.getCompanyId());
        finished.setYear(conditions.getYear());
        finished.setMonth(conditions.getMonth());
        List<BizArchiveReceiveTicketFinished> status = archiveReceiveTicketFinishedService.getListByBean(finished);
        finished = status.isEmpty() ? finished : status.get(0);
        finished.setIsFinished(finished.getIsFinished() != null ? finished.getIsFinished() : 0);
        map.put("finished", finished);

//        BizFinancialKeepAccount bizFinancialKeepAccount = new BizFinancialKeepAccount();
        return success(map);
    }


    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PostMapping("/getCheckout")
    @ResponseBody
    public AjaxResult getCheckout(@RequestBody Map<String, Object> conditions) {
        return success();
    }

    @ApiModelProperty("获取完成状态")
    @PostMapping("/getFinished")
    @ResponseBody
    public AjaxResult getFinished(@RequestBody BizArchiveReceiveTicket archiveReceiveTicket) {
        QueryWrapper<BizArchiveReceiveTicketFinished> wrapper = new QueryWrapper<>();
        wrapper.eq("year", archiveReceiveTicket.getYear());
        wrapper.eq("month", archiveReceiveTicket.getMonth());
        wrapper.eq("company_id", archiveReceiveTicket.getCompanyId());

        return success(archiveReceiveTicketFinishedService.getOne(wrapper));
    }
}
