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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.project.business.entrust.domain.BizEntrust;
import cn.ezhizao.project.business.entrust.service.IBizEntrustService;
import cn.ezhizao.project.business.entrustExamine.domain.BizEntrustExamine;
import cn.ezhizao.project.business.entrustExamine.domain.vo.RefuseVo;
import cn.ezhizao.project.business.entrustExamine.service.IBizEntrustExamineService;
import cn.ezhizao.project.system.domain.SysUser;

import cn.ezhizao.project.system.service.ISysUserService;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
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.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;

/**
 * 企业租户Controller
 *
 * @author ruoyi
 * @date 2024-09-10
 */
@RestController
@RequestMapping("/business/examine")
public class BizEntrustExamineController extends BaseController {
    @Resource
    private IBizEntrustExamineService bizEntrustExamineService;
    @Resource
    IBizEntrustService bizEntrustService;


    @Resource
    private ISysUserService userService;
    /**
     * 查询企业租户列表
     */
    @PreAuthorize("@ss.hasPermi('business:examine:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizEntrustExamine bizEntrustExamine) throws NoSuchFieldException, IllegalAccessException {
        bizEntrustExamine.setEntrustId(getTenantId());
        setTenantId(bizEntrustExamine);
        startPage();
        List<BizEntrustExamine> list = bizEntrustExamineService.getList(bizEntrustExamine);
        return getDataTable(list);
    }

    @PostMapping("/refuse")
    public AjaxResult refuse(@RequestBody  BizEntrustExamine bizEntrustExamine) {
        bizEntrustExamine.setStatus(2);
        bizEntrustExamineService.updateById(bizEntrustExamine);
        return AjaxResult.success();
    }

    /**
     * 导出企业租户列表
     */
    @PreAuthorize("@ss.hasPermi('business:examine:export')")
    @Log(title = "企业租户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizEntrustExamine bizEntrustExamine) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizEntrustExamine);
        bizEntrustExamine.setEntrustId(getTenantId());
        List<BizEntrustExamine> list = bizEntrustExamineService.getList(bizEntrustExamine);
        ExcelUtil<BizEntrustExamine> util = new ExcelUtil<BizEntrustExamine>(BizEntrustExamine.class);
        util.exportExcel(response, list, "取消委托数据");
    }

    /**
     * 获取企业租户详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:examine:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizEntrustExamineService.getById(id));
    }

    /**
     * 新增企业租户
     */
    @PreAuthorize("@ss.hasPermi('business:examine:add')")
    @Log(title = "企业租户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizEntrustExamine bizEntrustExamine) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizEntrustExamine);
        return toAjax(bizEntrustExamineService.save(bizEntrustExamine));
    }

    /**
     * 修改企业租户
     */
    @PreAuthorize("@ss.hasPermi('business:examine:edit')")
    @Log(title = "企业租户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizEntrustExamine bizEntrustExamine) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizEntrustExamine);
        return toAjax(bizEntrustExamineService.updateById(bizEntrustExamine));
    }

    /**
     * 删除企业租户
     */
    @PreAuthorize("@ss.hasPermi('business:examine:remove')")
    @Log(title = "企业租户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(bizEntrustExamineService.removeBatchByIds(ids));
    }




    @PostMapping("/agree")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult agree(@RequestBody List<Long> ids) throws ParseException {
        //下月
        List<BizEntrustExamine> nextFlagOneList = new ArrayList<>();
        //本月
        List<BizEntrustExamine> flagEmptyList = new ArrayList<>();
        List<BizEntrustExamine> list = bizEntrustExamineService
                .list(new LambdaQueryWrapper<BizEntrustExamine>().in(BizEntrustExamine::getId, ids));
        for (BizEntrustExamine bizEntrustExamine : list) {
            if (bizEntrustExamine.getNextFlag() != null && bizEntrustExamine.getNextFlag() == 1){
                nextFlagOneList.add(bizEntrustExamine);
            }else {
                flagEmptyList.add(bizEntrustExamine);
            }
        }

        if (!CollectionUtils.isEmpty(nextFlagOneList)){
            for (BizEntrustExamine item : nextFlagOneList) {
                BizEntrust bizEntrust = new BizEntrust();
                bizEntrust.setWorkOrderIds(Collections.singletonList(item.getWorkOrderId()));
                String str = item.getCurrentPeriod();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date d = null;
                try {
                    d = format.parse(str);
                } catch (Exception e) {
                    throw new RuntimeException("日期转换错误");
                }
                java.sql.Date date = new java.sql.Date(d.getTime());
                bizEntrust.setCurrentMonth(date);
                extracted1(bizEntrust);
            }
        }

        if (!CollectionUtils.isEmpty(flagEmptyList)){
            for (BizEntrustExamine bizEntrustExamine : flagEmptyList) {
                BizEntrust bizEntrust = new BizEntrust();
                bizEntrust.setWorkOrderIds(Collections.singletonList(bizEntrustExamine.getWorkOrderId()));

                String str = bizEntrustExamine.getCurrentPeriod();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date d = null;
                try {
                    d = format.parse(str);
                } catch (Exception e) {
                    throw new RuntimeException("日期转换错误");
                }
                java.sql.Date date = new java.sql.Date(d.getTime());
                bizEntrust.setCurrentMonth(date);
                extracted(bizEntrust);
            }
        }

        return AjaxResult.success();
    }

    private void extracted1(BizEntrust bizEntrust) {
        List<BizEntrust> entrustList = bizEntrustService.getList(bizEntrust);
        BizEntrustExamine bizEntrustExamine = new BizEntrustExamine();
        bizEntrustExamine.setId(bizEntrust.getExamineId());
        bizEntrustExamine.setStatus(1);
        bizEntrustExamineService.updateById(bizEntrustExamine);
        bizEntrustService.removeByIds(entrustList.stream().map(BizEntrust::getId).collect(Collectors.toList()));
    }

    private void extracted(BizEntrust bizEntrust) {
        List<BizEntrust> entrustList = bizEntrustService.getList(bizEntrust);
        DateTime currentMonth = DateTime.of(bizEntrust.getWorkMonth());
        List<BizEntrust> nextEntrustList = new ArrayList<>();
        bizEntrust.setWorkMonth(currentMonth.offset(DateField.MONTH, 1).toSqlDate());
        List<BizEntrust> list = bizEntrustService.list(new LambdaQueryWrapper<BizEntrust>()
                .eq(BizEntrust::getDeleted, 0)
                .eq(BizEntrust::getWorkMonth, bizEntrust.getWorkMonth())
                .in(BizEntrust::getWorkOrderId, bizEntrust.getWorkOrderIds()));
        List<Long> needWorkIds = list.stream().filter(l ->
                {
                    Long updaterId = l.getCreatorId();
                    SysUser sysUser = userService.selectUserById(Long.valueOf(updaterId));
                    return sysUser == null ? true : false;
                }
        ).map(l -> l.getWorkOrderId()).collect(Collectors.toList());
        if (!needWorkIds.isEmpty()) {
            bizEntrust.setWorkOrderIds(needWorkIds);
            nextEntrustList = bizEntrustService.getList(bizEntrust);
        } else {
            nextEntrustList = null;
        }
        BizEntrustExamine bizEntrustExamine = new BizEntrustExamine();
        bizEntrustExamine.setId(bizEntrust.getExamineId());
        bizEntrustExamine.setStatus(1);
        bizEntrustExamineService.updateById(bizEntrustExamine);
        boolean status = (entrustList.isEmpty() ||
                bizEntrustService.removeByIds(entrustList.stream().map(BizEntrust::getId).collect(Collectors.toList()))) && (CollectionUtils.isEmpty(nextEntrustList) ||
                bizEntrustService.removeByIds(nextEntrustList.stream().map(BizEntrust::getId).collect(Collectors.toList())));
    }


    @PostMapping("/refuseIds")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult refuseIds(@RequestBody RefuseVo vo) {
        List<Long> ids = vo.getIds();
        List<BizEntrustExamine> list = ids.stream().map(id -> {
            BizEntrustExamine bizEntrustExamine = new BizEntrustExamine();
            bizEntrustExamine.setId(id);
            bizEntrustExamine.setStatus(2);
            bizEntrustExamine.setRefuseReason(vo.getReason());
            return bizEntrustExamine;
        }).collect(Collectors.toList());
        bizEntrustExamineService.updateBatchById(list);
        return AjaxResult.success();
    }
}
