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

import cn.ezhizao.common.utils.file.FileUploadUtils;
import cn.ezhizao.common.utils.file.FileUtils;
import cn.ezhizao.framework.config.RuoYiConfig;
import cn.ezhizao.framework.config.ServerConfig;
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.company.domain.BizCompany;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
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.service.IBizFinancialKeepAccountService;
import cn.ezhizao.project.business.receiveTicket.service.IBizFinancialReceiveTicketDetailService;
import cn.ezhizao.project.business.receiveTicket.service.IBizFinancialReceiveTicketService;
import cn.ezhizao.project.business.salary.service.IBizFinancialSalaryDetailService;
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.aspectj.weaver.loadtime.Aj;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "收票 数据接口")
@RequestMapping(value = "/business/archiveTicket")
public class ArchiveTicketController extends BaseController {

    @Resource
    private ServerConfig serverConfig;
    @Resource
    IBizFinancialKeepAccountService financialKeepAccountService;
    @Resource
    IBizArchiveReceiveTicketService bizArchiveReceiveTicketService;
    @Resource
    IBizEntrustService entrustService;
    @Resource
    IBizCompanyService companyService;
    @Resource
    IBizArchiveReceiveTicketFinishedService archiveReceiveTicketFinishedService;
    @Resource
    IBizFinancialReceiveTicketDetailService financialReceiveTicketDetailService;
    @Resource
    IBizFinancialSalaryDetailService financialSalaryDetailServicel;


    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo getList(BizCompany conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startPage();
        startOrderBy();
        List<BizCompany> list = companyService.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 分页查询")
    @GetMapping("/getCheckout")
    @ResponseBody
    public AjaxResult getCheckout(BizArchiveReceiveTicket conditions) throws NoSuchFieldException, IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        // 获取受委托账期
        BizEntrust entrustConditions = new BizEntrust();
        entrustConditions.setCompanyId(conditions.getCompanyId());
        entrustConditions.setTaskTypeId(1L);
        entrustConditions.setTicketFinished(0);
        entrustConditions.setIsZero(0);
        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);
        return success(map);
    }

    @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));
    }

    @ApiModelProperty("上传票据")
    @PostMapping("/uploadFiles")
    public AjaxResult uploadFiles(@RequestParam("file") MultipartFile file, @RequestParam Long companyId, @RequestParam String currentMonth, @RequestParam Long ticketTypeId) throws Exception {
        if (companyId.equals(0L)) {
            return AjaxResult.error("没有提供客户id");
        }

        if (ticketTypeId.equals(0L)) {
            return AjaxResult.error("没有提供票据类型");
        }

        if (currentMonth.equals("")) {
            return AjaxResult.error("没有提供账期年月");
        }

        String month = DateTime.of(currentMonth, "yyyy-MM-dd").toString("MM");
        String year = DateTime.of(currentMonth, "yyyy-MM-dd").toString("yyyy");
// 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String extractName = FileUploadUtils.extractFilename(file);
        String url = serverConfig.getUrl() + fileName;
        BizArchiveReceiveTicket archiveReceiveTicket = new BizArchiveReceiveTicket();
        archiveReceiveTicket.setTypeId(ticketTypeId);
        archiveReceiveTicket.setCompanyId(companyId);
        archiveReceiveTicket.setAccountSetsId(0L);
        archiveReceiveTicket.setMonth(month);
//            archiveReceiveTicket.setMonth(String.format("%02s", month));
        archiveReceiveTicket.setYear(year);
        // 2023-07-17 补上
        archiveReceiveTicket.setFileUrl(fileName);
        archiveReceiveTicket.setFileName(FileUtils.getName(fileName));

        SimpleDateFormat fmtTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String currentTime = fmtTime.format(new Date());
        archiveReceiveTicket.setCreateTime(Timestamp.valueOf(currentTime));
        return bizArchiveReceiveTicketService.save(archiveReceiveTicket) ? AjaxResult.success("上传成功") : AjaxResult.error("保存失败");

    }

    @PostMapping("/finishedReceiveTicket")
    public AjaxResult finishedReceiveTicket(@RequestParam String currentMonth, @RequestParam Long companyId, @RequestParam Integer isFinished) {
        // 判断是否可以关闭账期 该月是否已有工资和收票
        if (currentMonth == null || currentMonth.equals("")) {
            return AjaxResult.error("没有提供账期年月");
        }

        if (companyId == null || companyId.equals(0L)) {
            return AjaxResult.error("没有选择客户");
        }

        if (isFinished == null) {
            return AjaxResult.error("没有提供是否关闭账期的状态");
        }

        String month = DateTime.of(currentMonth, "yyyy-MM-dd").toString("MM");
        String year = DateTime.of(currentMonth, "yyyy-MM-dd").toString("yyyy");

        if (isFinished.equals(1)) {
            if (financialReceiveTicketDetailService.query().eq("company_id", companyId).eq("year", year).eq("month", month).count() <= 0) {
                return AjaxResult.error("该账期未收票");
            }

            if (financialSalaryDetailServicel.query().eq("company_id", companyId).eq("year", year).eq("month", month).count() <= 0) {
                return AjaxResult.error("该账期未录工资");
            }
        }

        QueryWrapper<BizArchiveReceiveTicketFinished> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("year", year);
        queryWrapper.eq("month", month);
        queryWrapper.eq("company_id", companyId);
        List<BizArchiveReceiveTicketFinished> uploadTicketFinished = archiveReceiveTicketFinishedService.list(queryWrapper);
        if (uploadTicketFinished == null || uploadTicketFinished.size() == 0) {
            // 此时没有,那么就闯进啊
            BizArchiveReceiveTicketFinished insert = new BizArchiveReceiveTicketFinished();
            insert.setYear(year);
            insert.setMonth(month);
            insert.setCompanyId(companyId);
            insert.setIsFinished(isFinished);
            if (!archiveReceiveTicketFinishedService.save(insert)) {
                return AjaxResult.error("创建账期失败");
            } else {
                return AjaxResult.success();
            }

        } else if (uploadTicketFinished.size() == 1) {
            //

            BizArchiveReceiveTicketFinished current = uploadTicketFinished.get(0);
            current.setIsFinished(isFinished);
            if (!archiveReceiveTicketFinishedService.saveOrUpdate(current)) {
                return AjaxResult.error("更新账期失败!");
            } else {
                return AjaxResult.success();
            }
        } else {
            return AjaxResult.error("找到了多条账期信息!");
        }
    }
}
