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

import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.common.utils.poi.ExcelUtil;
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;
import cn.ezhizao.project.business.deduction.domain.BizDeduction;
import cn.ezhizao.project.business.deduction.service.IBizDeductionService;
import cn.ezhizao.project.business.finance.IndividualIncomeTax.domain.BizFinancialIndividualIncomeTaxDetail;
import cn.ezhizao.project.business.finance.IndividualIncomeTax.service.IBizFinancialIndividualIncomeTaxDetailService;
import cn.ezhizao.project.business.finance.IndividualIncomeTaxIsZero.domain.BizFinancialIndividualIncomeTaxDetailIsZero;
import cn.ezhizao.project.business.finance.IndividualIncomeTaxIsZero.service.IBizFinancialIndividualIncomeTaxDetailIsZeroService;
import cn.ezhizao.project.business.financialBase.domain.BizFinancialMerge;
import cn.ezhizao.project.business.financialBase.service.IBizFinancialMergeService;
import cn.ezhizao.project.business.housingFund.domain.BizHousingFundDeclareDetail;
import cn.ezhizao.project.business.housingFund.service.IBizHousingFundDeclareDetailService;
import cn.ezhizao.project.business.receiveTicket.domain.BizFinancialReceiveTicket;
import cn.ezhizao.project.business.receiveTicket.domain.BizFinancialReceiveTicketDetail;
import cn.ezhizao.project.business.reportTaxIsZero.domain.BizFinancialReportTaxDetail;
import cn.ezhizao.project.business.reportTaxIsZero.service.IBizFinancialReportTaxDetailService;
import cn.ezhizao.project.business.socialSecurity.domain.BizSocialSecurityDeclareDetail;
import cn.ezhizao.project.business.socialSecurity.service.IBizSocialSecurityDeclareDetailService;
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.service.ISysFileStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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


/**
 * @author 王建
 */
@RestController
@Api(tags = "Deduction数据接口")
@RequestMapping(value = "/business/deduction")
public class DeductionController extends BaseController {

    @Resource
    IBizDeductionService deductionService;


    @Resource
    ISysFileStorageService fileStorageService;

    @Resource
    IBizWorkOrderRecordService bizWorkOrderRecordService;

    @Resource
    IBizHousingFundDeclareDetailService housingFundDeclareDetailService;
    @Resource
    IBizSocialSecurityDeclareDetailService socialSecurityDeclareDetailService;

    @Resource
    IBizFinancialReportTaxDetailService financialReportTaxDetailService;
    @Resource
    IBizFinancialIndividualIncomeTaxDetailService individualIncomeTaxDetailService;

    @Resource
    IBizFinancialMergeService bizFinancialMergeService;

    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @PreAuthorize("@ss.hasPermi('business:deduction:query')")
    @GetMapping("/getById/{id}")
    @ResponseBody
    public AjaxResult getById(@PathVariable Long id) {
        return success(deductionService.getById(id));
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存", notes = "保存")
    @PreAuthorize("@ss.hasAnyPermi('business:deduction:confirm,business:deduction:deduction')")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult save(@RequestBody BizDeduction deduction) {
        boolean result = (deduction.getId() == null ? deductionService.save(deduction) : deductionService.updateById(deduction));
        switch (deduction.getStatus()) {
            case 1:
                result = result && addRecord(deduction.getWorkOrderId(), deduction.getYear(), deduction.getMonth(), SecurityUtils.getUserId(), "确认扣款", 1);
                break;
            case 2:
                result = result && addRecord(deduction.getWorkOrderId(), deduction.getYear(), deduction.getMonth(), SecurityUtils.getUserId(), "已扣款", 3);
                break;
            case 4:
                result = result && addRecord(deduction.getWorkOrderId(), deduction.getYear(), deduction.getMonth(), SecurityUtils.getUserId(), "扣款失败", 1);
                break;
            case 5:
                result = result && addRecord(deduction.getWorkOrderId(), deduction.getYear(), deduction.getMonth(), SecurityUtils.getUserId(), "公积金申报成功", 1);
                break;

        }
        return result ? success() : error();
    }

    @PostMapping("/saveBatch")
    @ApiOperation(value = "批量保存", notes = "批量保存")
    @ResponseBody
    public AjaxResult saveBatch(@RequestBody List<BizDeduction> list) {
        return deductionService.saveOrUpdateBatch(list) ? success() : error();
    }
    @PostMapping("/update")
    @ResponseBody
    public AjaxResult update(@RequestBody BizDeduction deduction) {
        return deductionService.updateById(deduction) ? success() : error();
    }
    @ApiOperation(value = "删除", notes = "删除")
    @GetMapping("/deleteById/{id}")
    @ResponseBody
    public AjaxResult deleteById(@PathVariable Long id) {
        return deductionService.removeById(id) ? success() : error();
    }

    @ApiOperation(value = "批量删除", notes = "批量删除")
    @PostMapping("/batchDelete")
    @ResponseBody
    public AjaxResult batchDelete(@RequestBody List<Long> list) {
        return deductionService.removeBatchByIds(list) ? success() : error();
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PreAuthorize("@ss.hasPermi('business:deduction:list')")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo getList(BizDeduction conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startPage();
        startOrderBy();
        List<BizDeduction> list = deductionService.getListByBean(conditions);
        //分页数据
        return getDataTable(list);
    }

    @ApiOperation(value = "整体保存", notes = "整体保存")
    @PostMapping("/saveFile")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult saveFile(@RequestBody List<SysFileStorage> fileStorageList) {
        boolean bool = fileStorageService.saveBatch(fileStorageList);
        return bool ? success(fileStorageList) : error();
    }

    @ApiOperation(value = "删除", notes = "删除")
    @PostMapping("/delFile")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult delFile(@RequestBody SysFileStorage fileStorage) {
        boolean bool = fileStorageService.removeById(fileStorage);
        return bool ? success(fileStorage) : error();
    }

    private boolean addRecord(Long workOrderId, String year, String month, Long recorderId, String description, Integer status) {
        // 没拆分合同单价
        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.setWorkOrderId(workOrderId);
            record.setStatus(status);
            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.setYear(fromRecord.getYear());
            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.setStatus(status);
            fromRecord.setStatusDescript(description);
            fromRecord.setRecorderId(recorderId);
            return bizWorkOrderRecordService.save(record) &&
                    bizWorkOrderRecordService.updateById(fromRecord);
        }
    }

    @PostMapping("/saveFiles")
    public AjaxResult saveFiles(@RequestBody SysFileStorage fileStorageList) {

        return fileStorageService.save(fileStorageList) ? success() : error();
    }


    /**
     * 导出划款列表
     */
    @PreAuthorize("@ss.hasPermi('business:deduction:export')")
    @Log(title = "划款任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizDeduction bizDeduction) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizDeduction);
        startOrderBy();
        List<BizDeduction> list = deductionService.getListByBean(bizDeduction);
        for (BizDeduction l : list) {
            l.setCurrentMonth(l.getYear() + "-" + l.getMonth());
            //设置状态
            switch (l.getStatus()) {
                case 0:
                    l.setStatusType("待确认扣款");
                    break;
                case 1:
                    l.setStatusType("可扣款");
                    break;
                case 3:
                    l.setStatusType("已扣款");
                    break;
                case 5:
                    l.setStatusType("已申报");
                    break;
                case 4:
                    l.setStatusType("扣款失败");
                    break;
                default:
                    break;
            }

        }
        ExcelUtil<BizDeduction> util = new ExcelUtil<BizDeduction>(BizDeduction.class);
        util.exportExcel(response, list, "划款数据");
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PostMapping("/getAmountView")
    @ResponseBody
    public AjaxResult getAmountView(@RequestBody BizDeduction deduction) {
        Map<String, Object> map = new HashMap<>(4);
        switch (deduction.getSourceName()) {
            case "税款":
                BizFinancialMerge merge = bizFinancialMergeService.getById(deduction.getSourceId());
                BizFinancialReportTaxDetail taxCondition = new BizFinancialReportTaxDetail();
                BizFinancialIndividualIncomeTaxDetail individualCondition = new BizFinancialIndividualIncomeTaxDetail();
                taxCondition.setId(merge.getFinancialReportTaxDetailId());
                BizFinancialReportTaxDetail bizFinancialReportTaxDetail = financialReportTaxDetailService.getList(taxCondition).stream().findFirst().orElse(new BizFinancialReportTaxDetail());
                map.put("reportTax", bizFinancialReportTaxDetail);
                individualCondition.setId(merge.getFinancialIndividualIncomeTaxDetailId());
                BizFinancialIndividualIncomeTaxDetail financialIndividualIncomeTaxDetail = individualIncomeTaxDetailService.getList(individualCondition).stream().findFirst().orElse(new BizFinancialIndividualIncomeTaxDetail());
                map.put("individualTax", financialIndividualIncomeTaxDetail);
                map.put("form", deduction);
                break;
            case "社保":
                BizSocialSecurityDeclareDetail conditions = new BizSocialSecurityDeclareDetail();
                conditions.setId(deduction.getSourceId());
                BizSocialSecurityDeclareDetail bizSocialSecurityConfirmDetail = socialSecurityDeclareDetailService.getListByBean(conditions).stream().findFirst().orElse(new BizSocialSecurityDeclareDetail());
                map.put("socialSecurity", bizSocialSecurityConfirmDetail);
                break;
            case "公积金":
                BizHousingFundDeclareDetail housingFundConditions = new BizHousingFundDeclareDetail();
                housingFundConditions.setId(deduction.getSourceId());
                BizHousingFundDeclareDetail bizHousingFundDeclareDetail = housingFundDeclareDetailService.getListByBean(housingFundConditions).stream().findFirst().orElse(new BizHousingFundDeclareDetail());
                map.put("housingFund", bizHousingFundDeclareDetail);
                break;
            default:
                break;
        }
        return success(map);
    }
}
