package cn.ezhizao.project.business.finance.IndividualIncomeTaxIsZero.controller;

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

import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.framework.lock.DistributionLock;
import cn.ezhizao.framework.lock.LockKey;
import cn.ezhizao.project.business.finance.IndividualIncomeTaxIsZero.domain.BizFinancialIndividualIncomeTaxDetailIsZero;
import cn.ezhizao.project.business.finance.IndividualIncomeTaxIsZero.domain.BizFinancialIndividualIncomeTaxIsZero;
import cn.ezhizao.project.business.finance.IndividualIncomeTaxIsZero.service.IBizFinancialIndividualIncomeTaxIsZeroService;
import cn.ezhizao.project.business.history.domain.BizHistory;
import cn.ezhizao.project.business.history.service.IBizHistoryService;
import cn.ezhizao.project.business.workOrder.domain.BizWorkOrderRecord;
import cn.ezhizao.project.business.workOrder.service.IBizWorkOrderRecordService;
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.finance.IndividualIncomeTaxIsZero.service.IBizFinancialIndividualIncomeTaxDetailIsZeroService;
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 2023-11-17
 */
@RestController
@RequestMapping("/business/individualIncomeTaxDetailIsZero")
public class BizFinancialIndividualIncomeTaxDetailIsZeroController extends BaseController {
    @Resource
    private IBizFinancialIndividualIncomeTaxDetailIsZeroService bizFinancialIndividualIncomeTaxDetailService;

    @Resource
    private IBizFinancialIndividualIncomeTaxIsZeroService bizFinancialIndividualIncomeTaxService;

    @Resource
    private IBizWorkOrderRecordService bizWorkOrderRecordService;

    @Resource
    private IBizHistoryService bizHistoryService;


    /**
     * 查询个税详情列表
     */
    @PreAuthorize("@ss.hasPermi('business:individualIncomeTaxDetail:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizFinancialIndividualIncomeTaxDetailIsZero bizFinancialIndividualIncomeTaxDetail) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizFinancialIndividualIncomeTaxDetail);
        startPage();
        List<BizFinancialIndividualIncomeTaxDetailIsZero> list = bizFinancialIndividualIncomeTaxDetailService.getList(bizFinancialIndividualIncomeTaxDetail);
        return getDataTable(list);
    }

    /**
     * 导出个税详情列表
     */
    @PreAuthorize("@ss.hasPermi('business:individualIncomeTaxDetail:export')")
    @Log(title = "个税详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizFinancialIndividualIncomeTaxDetailIsZero bizFinancialIndividualIncomeTaxDetail) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizFinancialIndividualIncomeTaxDetail);
        List<BizFinancialIndividualIncomeTaxDetailIsZero> list = bizFinancialIndividualIncomeTaxDetailService.getList(bizFinancialIndividualIncomeTaxDetail);
        ExcelUtil<BizFinancialIndividualIncomeTaxDetailIsZero> util = new ExcelUtil<BizFinancialIndividualIncomeTaxDetailIsZero>(BizFinancialIndividualIncomeTaxDetailIsZero.class);
        util.exportExcel(response, list, "个税详情数据");
    }

    /**
     * 获取个税详情详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:individualIncomeTaxDetail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizFinancialIndividualIncomeTaxDetailService.getById(id));
    }

    /**
     * 新增个税详情
     */
    @PreAuthorize("@ss.hasPermi('business:individualIncomeTaxDetail:saveDetail')")
    @Log(title = "个税详情", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizFinancialIndividualIncomeTaxDetailIsZero bizFinancialIndividualIncomeTaxDetail) throws NoSuchFieldException, IllegalAccessException {

        String join = LockKey.join(LockKey.INCOMETAXZERO, getUserId());
        DistributionLock lock = new DistributionLock(join);

        try {
            lock.lock();
            String status = "";
            switch (bizFinancialIndividualIncomeTaxDetail.getStatus()) {
                case 0:
                    status = "个税未开始";
                    break;
                case 1:
                    status = "个税进行中";
                    break;
                case 3:
                    status = "个税已完成";
                    break;

            }
            bizFinancialIndividualIncomeTaxDetail.setVerifierId(getUserId());
            bizFinancialIndividualIncomeTaxDetail.setVerifierTime(new Date());

            //零申报
            BizHistory bizHistory = new BizHistory();
            bizHistory.setTableName("biz_financial_individual_income_tax_zero");
            bizHistory.setCompanyId(bizFinancialIndividualIncomeTaxDetail.getCompanyId());
            bizHistory.setEvent("保存");
            bizHistory.setTenantId(getTenantId());
            bizHistory.setBelongPeriod(bizFinancialIndividualIncomeTaxDetail.getYear() + "-" +String.format("%02d", Integer.valueOf(bizFinancialIndividualIncomeTaxDetail.getMonth())));
            bizHistoryService.save(bizHistory);
            return toAjax(bizFinancialIndividualIncomeTaxDetailService.save(bizFinancialIndividualIncomeTaxDetail) && addRecord(bizFinancialIndividualIncomeTaxDetail.getCompanyId(), bizFinancialIndividualIncomeTaxDetail.getFinancialIndividualIncomeTaxId(),

                    bizFinancialIndividualIncomeTaxDetail.getYear(), bizFinancialIndividualIncomeTaxDetail.getMonth(), SecurityUtils.getUserId(), status));
        } catch (Exception e) {
            e.printStackTrace();
            return error("保存失败");
        } finally {
            lock.unlock();
        }
    }


    /**
     * 修改个税详情
     */
    @PreAuthorize("@ss.hasPermi('business:individualIncomeTaxDetail:saveDetail')")
    @Log(title = "个税详情", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody BizFinancialIndividualIncomeTaxDetailIsZero bizFinancialIndividualIncomeTaxDetail) throws NoSuchFieldException, IllegalAccessException {

        String status = "";
        switch (bizFinancialIndividualIncomeTaxDetail.getStatus()) {
            case 0:
                status = "个税未开始";
                break;
            case 1:
                status = "个税进行中";
                //零申报
                BizHistory bizHistory = new BizHistory();
                bizHistory.setTableName("biz_financial_individual_income_tax_zero");
                bizHistory.setCompanyId(bizFinancialIndividualIncomeTaxDetail.getCompanyId());
                bizHistory.setBelongPeriod(bizFinancialIndividualIncomeTaxDetail.getYear() + "-" + String.format("%02d", Integer.valueOf(bizFinancialIndividualIncomeTaxDetail.getMonth())) );
                bizHistory.setEvent("退回");
                bizHistory.setReason(bizFinancialIndividualIncomeTaxDetail.getRefuseReason());
                bizHistory.setTenantId(getTenantId());
                bizHistoryService.save(bizHistory);
                break;
            case 3:
                status = "个税已完成";
                //零申报
                BizHistory bizHistory2 = new BizHistory();
                bizHistory2.setTableName("biz_financial_individual_income_tax_zero");
                bizHistory2.setCompanyId(bizFinancialIndividualIncomeTaxDetail.getCompanyId());
                bizHistory2.setEvent("保存");
                bizHistory2.setTenantId(getTenantId());
                bizHistory2.setBelongPeriod(bizFinancialIndividualIncomeTaxDetail.getYear() + "-" + String.format("%02d", Integer.valueOf(bizFinancialIndividualIncomeTaxDetail.getMonth())) );
                bizHistoryService.save(bizHistory2);
                break;

        }
        bizFinancialIndividualIncomeTaxDetail.setVerifierId(getUserId());
        bizFinancialIndividualIncomeTaxDetail.setVerifierTime(new Date());


        return toAjax(bizFinancialIndividualIncomeTaxDetailService.updateById(bizFinancialIndividualIncomeTaxDetail) && addRecord(bizFinancialIndividualIncomeTaxDetail.getCompanyId(), bizFinancialIndividualIncomeTaxDetail.getFinancialIndividualIncomeTaxId(),

                bizFinancialIndividualIncomeTaxDetail.getYear(), bizFinancialIndividualIncomeTaxDetail.getMonth(), SecurityUtils.getUserId(), status));
    }


    /**
     * 删除个税详情
     */
    @PreAuthorize("@ss.hasPermi('business:individualIncomeTaxDetail:remove')")
    @Log(title = "个税详情", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(bizFinancialIndividualIncomeTaxDetailService.removeBatchByIds(ids));
    }

    private boolean addRecord(Long companyId, Long bizFinancialSalaryId, String year, String month, Long recorderId, String description) {
        // 获取个税任务信息
        BizFinancialIndividualIncomeTaxIsZero bizFinancialSalary = bizFinancialIndividualIncomeTaxService.getById(bizFinancialSalaryId);

        //查询work_order_id
        Long workOrderId = bizFinancialSalary.getWorkOrderId();

        //查询在biz_work_order_record表中是否有数据
        List<BizWorkOrderRecord> records = bizWorkOrderRecordService.query().eq("work_order_id", workOrderId).eq("year", year).eq("month", month).eq("from_id", 0).list();
        //如果没有
        if (records.isEmpty()) {
            // 新增一条记录
            BizWorkOrderRecord record = new BizWorkOrderRecord();
            record.setMonth(month);
            record.setYear(year);
            record.setTenantId(getTenantId());
            record.setCompanyId(bizFinancialSalary.getCompanyId());
            record.setWorkOrderId(workOrderId);
            record.setStatus(1);
            record.setCompanyId(companyId);
            record.setStatusDescript(description);
            record.setRecorderId(recorderId);
            return bizWorkOrderRecordService.save(record);
        } else {
            // 新增一条子记录
            Long fromId = records.get(0).getId();
            BizWorkOrderRecord fromRecord = records.get(0);
            BizWorkOrderRecord record = new BizWorkOrderRecord();
            record.setFromId(fromId);
            record.setMonth(fromRecord.getMonth());
            record.setCompanyId(companyId);
            record.setYear(fromRecord.getYear());
            record.setCompanyId(bizFinancialSalary.getCompanyId());
            record.setTenantId(fromRecord.getTenantId());
            record.setWorkOrderId(fromRecord.getWorkOrderId());
            record.setStatus(fromRecord.getStatus());
            record.setStatusDescript(fromRecord.getStatusDescript());
            record.setRecorderId(fromRecord.getRecorderId());

            fromRecord.setMonth(month);
            fromRecord.setYear(year);
            fromRecord.setTenantId(getTenantId());
            fromRecord.setWorkOrderId(workOrderId);
            fromRecord.setCompanyId(bizFinancialSalary.getCompanyId());
            fromRecord.setStatus(1);
            fromRecord.setStatusDescript(description);
            fromRecord.setRecorderId(recorderId);
            return bizWorkOrderRecordService.save(record) &&
                    bizWorkOrderRecordService.updateById(fromRecord);
        }
    }
}
