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

import java.sql.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.project.business.channel.domain.BizChannel;
import cn.ezhizao.project.business.channel.service.IBizChannelService;
import cn.ezhizao.project.business.company.domain.BizCompany;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
import cn.ezhizao.project.business.order.domain.BizArchiveInputDetailProcess;
import cn.ezhizao.project.business.order.domain.vo.InputVo;
import cn.ezhizao.project.business.order.domain.vo.TimeVo;
import cn.ezhizao.project.business.order.service.IBizArchiveInputDetailProcessService;
import cn.ezhizao.project.business.workOrder.domain.BizWorkOrderRecord;
import cn.ezhizao.project.business.workOrder.service.IBizWorkOrderRecordService;
import cn.ezhizao.project.system.domain.SysFileStorage;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.service.ISysFileStorageService;
import cn.ezhizao.project.system.service.ISysUserService;
import cn.ezhizao.project.business.upgrade.domain.BizArchiveInputDetailUpdate;
import cn.ezhizao.project.business.upgrade.domain.BizWorkOrderDetailUpdate;
import cn.ezhizao.project.business.upgrade.domain.BizWorkOrderUpdate;
import cn.ezhizao.project.business.upgrade.service.IBizArchiveInputDetailUpdateService;
import cn.ezhizao.project.business.upgrade.service.IBizWorkOrderDetailUpdateService;
import cn.ezhizao.project.business.upgrade.service.IBizWorkOrderUpdateService;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
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.project.business.upgrade.domain.BizArchiveInputUpdate;
import cn.ezhizao.project.business.upgrade.service.IBizArchiveInputTempService;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.web.page.TableDataInfo;

/**
 * 档案入库Controller
 *
 * @author ruoyi
 * @date 2024-10-12
 */
@RestController
@RequestMapping("/business/upgrade/archiveinput")
public class BizArchiveInputTempController extends BaseController
{
    @Resource
    private IBizArchiveInputTempService bizArchiveInputTempService;
    @Resource
    private IBizCompanyService companyService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private IBizChannelService channelService;
    @Resource
    private ISysFileStorageService fileStorageService;
    @Resource
    private IBizWorkOrderUpdateService workOrderService;
    @Resource
    private IBizWorkOrderDetailUpdateService bizWorkOrderDetailService;

    @Resource
    private IBizWorkOrderRecordService workOrderRecordService;
    @Resource
    private IBizArchiveInputDetailUpdateService bizArchiveInputDetailUpdateService;
    @Resource
    private IBizArchiveInputDetailProcessService archiveInputDetailProcessService;
    /**
     * 查询档案入库列表
     */
    @PreAuthorize("@ss.hasPermi('business:upgrade:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(InputVo bizArchiveInput) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizArchiveInput);
        //分页
        startPage();
        //排序
        startOrderBy();
        //根据客户名称模糊查询去除两边空格
        if (bizArchiveInput.getCompanyName() != null) {
            if (!bizArchiveInput.getCompanyName().equals(""))
                bizArchiveInput.setCompanyName(bizArchiveInput.getCompanyName().trim());
        }
//        List<BizArchiveInput> list = bizArchiveInputService.getList(bizArchiveInput);
        List<BizArchiveInputUpdate> list = bizArchiveInputTempService.getListByInput(bizArchiveInput);

        return getDataTable(list);
    }


    /**
     * 导出档案入库列表
     */
    @PreAuthorize("@ss.hasPermi('business:upgrade:order:export')")
    @Log(title = "档案入库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizArchiveInputUpdate bizArchiveInputUpdate) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizArchiveInputUpdate);
        List<BizArchiveInputUpdate> list = bizArchiveInputTempService.getList(bizArchiveInputUpdate);
        ExcelUtil<BizArchiveInputUpdate> util = new ExcelUtil<BizArchiveInputUpdate>(BizArchiveInputUpdate.class);
        util.exportExcel(response, list, "档案入库数据");
    }

    /**
     * 获取档案入库详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:upgrade:order:list')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(getById(id));
    }
    private BizArchiveInputUpdate getById(Long id) {
        BizArchiveInputUpdate condition = new BizArchiveInputUpdate();
        condition.setId(id);
        BizArchiveInputUpdate bizArchiveInput = bizArchiveInputTempService.getList(condition).stream().findFirst().orElse(null);
        if (bizArchiveInput != null && bizArchiveInput.getReferrerDataSource() != null) {
            switch (bizArchiveInput.getReferrerDataSource()) {
                case "company":
                    BizCompany source = companyService.getById(bizArchiveInput.getSourceId());
                    bizArchiveInput.setSourceName(source != null ? source.getName() : "");
                    break;
                case "employee":
                    SysUser sysUser = sysUserService.selectUserById(bizArchiveInput.getSourceId());
                    bizArchiveInput.setSourceName(sysUser != null ? sysUser.getNickName() : "");
                    break;
                case "channel":
                    BizChannel channel = channelService.getById(bizArchiveInput.getSourceId());
                    bizArchiveInput.setSourceName(channel != null ? channel.getName() : "");
                    break;
                default:
                    break;
            }
        }
        if (bizArchiveInput != null) {
            BizArchiveInputDetailUpdate conditionDetail = new BizArchiveInputDetailUpdate();
            conditionDetail.setContractId(bizArchiveInput.getId());
            BizArchiveInputDetailProcess conditionProcess = new BizArchiveInputDetailProcess();
            List<SysFileStorage> sysFileStorages = fileStorageService.query().eq("master_table_name", "biz_archive_input").eq("master_id", bizArchiveInput.getId()).list();
            List<BizArchiveInputDetailUpdate> details = bizArchiveInputDetailUpdateService.getList(conditionDetail);
            for (BizArchiveInputDetailUpdate detail : details) {
                BizWorkOrderDetailUpdate one = bizWorkOrderDetailService.getOne(new LambdaQueryWrapper<BizWorkOrderDetailUpdate>()
                        .eq(BizWorkOrderDetailUpdate::getContractDetailId, detail.getId())
                        .eq(BizWorkOrderDetailUpdate::getIsStop, 0)
                        .eq(BizWorkOrderDetailUpdate::getTaskTypeId, detail.getTaskTypeId()));
                if (one != null) {
                    List<BizWorkOrderRecord> list = workOrderRecordService.list(new LambdaQueryWrapper<BizWorkOrderRecord>()
                            .eq(BizWorkOrderRecord::getWorkOrderId, one.getWorkOrderId()));
                    if (CollectionUtils.isNotEmpty(list)) {
                        detail.setDisabled(true);
                    } else {
                        detail.setDisabled(false);
                    }
                }
                if (bizArchiveInput.getServiceType() == 1) {
                    TimeVo time = getTime(detail.getContractId(), detail.getId(), detail.getTaskTypeId(), detail.getCompanyId());
                    if (time != null) {
                        detail.setTimeVo(time);
                    }
                }
            }

            List<BizArchiveInputDetailProcess> processes = archiveInputDetailProcessService.getList(conditionProcess);
            details.forEach(l -> l.setProcesses(processes.stream().filter(v -> v.getContractDetailId().equals(l.getId())).collect(Collectors.toList())));
            bizArchiveInput.setDetails(details);
            bizArchiveInput.setFiles(sysFileStorages);
        }
        return bizArchiveInput;
    }

    //获取当前合同工单起始结束区间
    public TimeVo getTime(Long contractId, Long contractDetailId, Long typeId, Long companyId) {
        //排序获取当前索引位置
        BizWorkOrderDetailUpdate one = bizWorkOrderDetailService.getOne(
                new LambdaQueryWrapper<BizWorkOrderDetailUpdate>()
                        .eq(BizWorkOrderDetailUpdate::getContractId, contractId)
                        .eq(BizWorkOrderDetailUpdate::getContractDetailId, contractDetailId)
                        .eq(BizWorkOrderDetailUpdate::getCompanyId, companyId)
                        .eq(BizWorkOrderDetailUpdate::getTaskTypeId, typeId).eq(BizWorkOrderDetailUpdate::getDeleted, 0));
        if (one == null) {
            return null;
        }
        Long workOrderId = one.getWorkOrderId();

        BizWorkOrderUpdate workOrder = workOrderService.getById(workOrderId);
        if (workOrder == null) {
            logger.error("获取工单失败");
            return null;
        }
        List<BizWorkOrderDetailUpdate> list = bizWorkOrderDetailService.list(new LambdaQueryWrapper<BizWorkOrderDetailUpdate>()
                .eq(BizWorkOrderDetailUpdate::getWorkOrderId, workOrderId)
                .eq(BizWorkOrderDetailUpdate::getTaskTypeId, typeId)
                .orderByAsc(BizWorkOrderDetailUpdate::getCreateTime));

        List<Long> indexList = list.stream().map(m -> m.getContractDetailId()).collect(Collectors.toList());
        //确定当前索引元素
        int i = indexList.indexOf(contractDetailId);
        if (i == -1) {
            return null;
        }
        //当前元素所有月份
        BizWorkOrderDetailUpdate bizWorkOrderDetail = list.get(i);
        int monthNum = bizWorkOrderDetail.getFreeNum() + bizWorkOrderDetail.getServiceNum();
        //判断是不是第一个
        if (i == 0) {
            DateTime startMonth = DateTime.of(workOrder.getStartMonth());
            Date endMonth = startMonth.offset(DateField.MONTH, monthNum - 1).toSqlDate();
            return new TimeVo(workOrder.getStartMonth(), endMonth);
        } else {
            //中间的工单
            //获取起始时间 并获取 i 之前所有月数 相加为起始时间
            int totalNum = getMonthNum(i - 1, list);
            DateTime month = DateTime.of(workOrder.getStartMonth());
            Date startMonth = month.offset(DateField.MONTH, totalNum).toSqlDate();
            DateTime startMonthTemp = DateTime.of(startMonth);
            Date endMonth = startMonthTemp.offset(DateField.MONTH, monthNum - 1).toSqlDate();
            return new TimeVo(startMonth, endMonth);
        }

    }
    public static int getMonthNum(int i, List<BizWorkOrderDetailUpdate> list) {
        int total = 0;
        while (i >= 0) {
            BizWorkOrderDetailUpdate bizWorkOrderDetail = list.get(i);
            total += bizWorkOrderDetail.getFreeNum() + bizWorkOrderDetail.getServiceNum();
            i--;
        }
        return total;
    }
    /**
     * 新增档案入库
     */
    @PreAuthorize("@ss.hasPermi('business:upgrade:order:add')")
    @Log(title = "档案入库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizArchiveInputUpdate bizArchiveInputUpdate) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizArchiveInputUpdate);
        return toAjax(bizArchiveInputTempService.save(bizArchiveInputUpdate));
    }

    /**
     * 修改档案入库
     */
    @PreAuthorize("@ss.hasPermi('business:upgrade:order:edit')")
    @Log(title = "档案入库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizArchiveInputUpdate bizArchiveInputUpdate) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizArchiveInputUpdate);
        return toAjax(bizArchiveInputTempService.updateById(bizArchiveInputUpdate));
    }

    /**
     * 删除档案入库
     */

    @PreAuthorize("@ss.hasPermi('business:upgrade:order:edit')")
    @Log(title = "档案入库", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizArchiveInputTempService.removeBatchByIds(ids));
    }
    @Transactional
    @PreAuthorize("@ss.hasPermi('business:upgrade:order:edit')")
    @PostMapping("delete")
    public AjaxResult deldeleteArchiveInputete(Long id){
        return toAjax(bizArchiveInputTempService.deleteArchiveInput(getTenantId() == null ? 0 : getTenantId(),id));
    }
}
