package com.gree.mall.manager.controller.settle;

import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gree.mall.manager.annotation.ZfireList;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.settle.*;
import com.gree.mall.manager.bean.websit.WorkerSettlementVO;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.settle.WorkerSettleExpenseLogic;
import com.gree.mall.manager.plus.entity.SettleExpenseItem;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "工程师费用结算", tags = {"工程师费用结算"})
@RequestMapping(value = "/settle/expense", produces = "application/json; charset=utf-8")
public class WorkerSettleExpenseController {

    @Resource
    private WorkerSettleExpenseLogic workerSettleExpenseLogic;
    @Resource
    private RedisLockRegistry redisLockRegistry;
    @Resource
    private CommonLogic commonLogic;

    @ZfireList
    @PostMapping("/gather/list")
    @ApiOperation(value = " 费用结算汇总列表")
    public ResponseHelper<IPage<SettleExpenseVO>> gatherList(
            @RequestBody ZfireParamBean zfireParamBean
    ) {
        IPage<SettleExpenseVO> page = workerSettleExpenseLogic.gatherList(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<WorkerSettlementVO>() {
        });
    }

    @PostMapping("/gather/list/export")
    @ApiOperation(value = "费用结算汇总导出")
    public void gatherListExport(@RequestBody ZfireParamBean zfireParamBean, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //2.查询要导出的内容
        IPage<SettleExpenseVO> page = workerSettleExpenseLogic.gatherList(zfireParamBean);
        //3.导出
        FieldUtils.exportData(page.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @ZfireList
    @PostMapping("/list")
    @ApiOperation(value = " 费用结算列表")
    public ResponseHelper<IPage<SettleExpenseItemVO>> list(
            @RequestBody ZfireParamBean zfireParamBean
    ) {
        IPage<SettleExpenseItemVO> page = workerSettleExpenseLogic.list(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<SettleExpenseItemVO>() {
        });
    }

    @PostMapping("/list/export")
    @ApiOperation(value = "费用结算导出")
    public void listExport(@RequestBody ZfireParamBean zfireParamBean, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //2.查询要导出的内容
        IPage<SettleExpenseItemVO> page = workerSettleExpenseLogic.list(zfireParamBean);
        //3.导出
        FieldUtils.exportData(page.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @PostMapping("/import")
    @ApiOperation("费用结算导入(下载模板:师傅费用结算导入模板.xlsx)")
    public ResponseHelper importData(
            @ApiParam(value = "附件", required = true) @RequestPart("file") MultipartFile file,
            HttpServletRequest request
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":"
                + (Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : ""));
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("系统繁忙，请稍后再尝试");
        }
        try {
            InputStream inputStream = file.getInputStream();
            workerSettleExpenseLogic.importData(adminUser, inputStream, request);
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增/编辑")
    public ResponseHelper add(
            @RequestBody SettleExpenseItem item
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":"
                + (Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : ""));
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("系统繁忙，请稍后再尝试");
        }
        try {
            workerSettleExpenseLogic.save(adminUser, item);
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/gather/batch/del")
    @ApiOperation(value = "汇总批量删除")
    public ResponseHelper gatherBatchDel(
            @RequestBody List<String> ids
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":"
                + (Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : ""));
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("系统繁忙，请稍后再尝试");
        }
        try {
            workerSettleExpenseLogic.gatherBatchDel(adminUser, ids);
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/batch/del")
    @ApiOperation(value = "明细批量删除")
    public ResponseHelper batchDel(
            @RequestBody List<String> ids
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":"
                + (Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : ""));
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("系统繁忙，请稍后再尝试");
        }
        try {
            workerSettleExpenseLogic.batchDel(adminUser, ids);
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/month/gather")
    @ApiOperation(value = "月度工资汇总")
    public ResponseHelper monthGather(
            @RequestBody MonthGatherBean bean
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":"
                + (Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : ""));
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("系统繁忙，请稍后再尝试");
        }
        try {
            workerSettleExpenseLogic.monthGather(adminUser, bean);
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/data/board")
    @ApiOperation(value = "数据看板")
    public ResponseHelper<DataBoardBean> dataBoard() {
        DataBoardBean bean = workerSettleExpenseLogic.dataBoard();
        return ResponseHelper.success(bean);
    }

    @PostMapping("/month/send/data")
    @ApiOperation(value = "月份已发放数据")
    public ResponseHelper<MonthSendDataBean> monthSendData(
            @ApiParam(value = "开始年月份 格式：yyyy-MM" , required = true) @RequestParam String startMonth,
            @ApiParam(value = "结束年月份 格式：yyyy-MM" , required = true) @RequestParam String endMonth
    ) {
        MonthSendDataBean bean = workerSettleExpenseLogic.monthSendData(startMonth, endMonth);
        return ResponseHelper.success(bean);
    }
}
