package com.limap.controller.manager;

import java.util.List;
import java.util.Arrays;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.limap.common.core.domain.entity.SysUser;
import com.limap.common.core.domain.entity.SysRole;
import com.limap.common.utils.StringUtils;
import com.limap.core.basic.service.IBasicUserWithdrawService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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 com.limap.common.log.annotation.Log;
import io.swagger.annotations.Api;
import com.limap.common.core.controller.BaseController;
import com.limap.common.core.domain.AjaxResult;
import com.limap.common.enums.BusinessType;
import io.swagger.annotations.ApiOperation;
import com.limap.core.basic.domain.BasicProfitSharingRecord;
import com.limap.core.basic.service.IBasicProfitSharingRecordService;
import com.limap.common.utils.poi.ExcelUtil;
import com.limap.common.core.page.TableDataInfo;
import com.limap.core.basic.vo.SharingRecordSearchVo;

/**
 * 分润记录Controller
 *
 * @author jjb
 * @date 2025-04-11
 */
@Api(tags = "分润记录")
@RestController
@RequestMapping("/basic/sharingRecord")
public class BasicProfitSharingRecordController extends BaseController {
    private static final String DATA_SCOPE_ALL = "1";
    private static final String DATA_SCOPE_DEPT = "3";
    private static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    @Autowired
    private IBasicProfitSharingRecordService basicProfitSharingRecordService;
    @Autowired
    private IBasicUserWithdrawService basicUserWithdrawService;

    /**
     * 查询分润记录列表
     */
    @ApiOperation("查询分润记录列表")
    @PreAuthorize("@ss.hasPermi('basic:sharingRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(BasicProfitSharingRecord basicProfitSharingRecord) {
        startPage();
        applySharingRecordDataScope(basicProfitSharingRecord);
        List<BasicProfitSharingRecord> list = basicProfitSharingRecordService.selectBasicProfitSharingRecordList(basicProfitSharingRecord);
        return getDataTable(list);
    }


    @ApiOperation("报表统计")
    @PreAuthorize("@ss.hasPermi('basic:sharingRecord:list')")
    @GetMapping("/report")
    public AjaxResult reportData(SharingRecordSearchVo searchVo) {
        applySharingRecordDataScope(searchVo);
        Map<String, Object> resultMap = basicProfitSharingRecordService.getReportData(searchVo);
        return success(resultMap);
    }

    /**
     * 导出分润记录列表
     */
    @ApiOperation("导出分润记录列表")
    @PreAuthorize("@ss.hasPermi('basic:sharingRecord:export')")
    @Log(title = "分润记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BasicProfitSharingRecord basicProfitSharingRecord) {
        applySharingRecordDataScope(basicProfitSharingRecord);
        List<BasicProfitSharingRecord> list = basicProfitSharingRecordService.selectBasicProfitSharingRecordList(basicProfitSharingRecord);
        ExcelUtil<BasicProfitSharingRecord> util = new ExcelUtil<BasicProfitSharingRecord>(BasicProfitSharingRecord.class);
        util.exportExcel(response, list, "分润记录数据");
    }

    /**
     * 获取分润记录详细信息
     */
    @ApiOperation("获取分润记录详细信息")
    @PreAuthorize("@ss.hasPermi('basic:sharingRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(basicProfitSharingRecordService.getById(id));
    }

    /**
     * 新增分润记录
     */
    @ApiOperation("新增分润记录")
    @PreAuthorize("@ss.hasPermi('basic:sharingRecord:add')")
    @Log(title = "分润记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BasicProfitSharingRecord basicProfitSharingRecord) {
        return toAjax(basicProfitSharingRecordService.save(basicProfitSharingRecord));
    }

    /**
     * 修改分润记录
     */
    @ApiOperation("修改分润记录")
    @PreAuthorize("@ss.hasPermi('basic:sharingRecord:edit')")
    @Log(title = "分润记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BasicProfitSharingRecord basicProfitSharingRecord) {
        if(basicProfitSharingRecord.getStatus().equals(9) || basicProfitSharingRecord.getPaymentStatus().equals(9)){
            basicProfitSharingRecord.setStatus(9);
            basicProfitSharingRecord.setPaymentStatus(9);
            if(basicProfitSharingRecord.getWithdrawId() != null){
                basicUserWithdrawService.updatePayment(basicProfitSharingRecord.getWithdrawId(),basicProfitSharingRecord.getAmount());
            }
        }
        return toAjax(basicProfitSharingRecordService.updateById(basicProfitSharingRecord));
    }

    @ApiOperation("退款处理")
    @PreAuthorize("@ss.hasPermi('basic:sharingRecord:edit')")
    @Log(title = "退款处理", businessType = BusinessType.UPDATE)
    @PutMapping("/refund")
    public AjaxResult refund(@RequestBody BasicProfitSharingRecord basicProfitSharingRecord) {
        if(StringUtils.isNotBlank(basicProfitSharingRecord.getOrderNo())){
            return AjaxResult.error("订单号不能为空");
        }
        return basicProfitSharingRecordService.dealRefund(basicProfitSharingRecord);
    }

    /**
     * 删除分润记录
     */
    @ApiOperation("删除分润记录")
    @PreAuthorize("@ss.hasPermi('basic:sharingRecord:remove')")
    @Log(title = "分润记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(basicProfitSharingRecordService.removeByIds(Arrays.asList(ids)));
    }

    private void applySharingRecordDataScope(BasicProfitSharingRecord record) {
        SysUser user = getLoginUser().getUser();
        if (user == null || user.isAdmin() || hasDataScope(user.getRoles(), DATA_SCOPE_ALL)) {
            return;
        }
        if (hasDataScope(user.getRoles(), DATA_SCOPE_DEPT_AND_CHILD)) {
            record.getParams().put("scopeType", "deptAndChild");
            record.getParams().put("scopeDeptId", getDeptId());
        } else if (hasDataScope(user.getRoles(), DATA_SCOPE_DEPT)) {
            record.getParams().put("scopeType", "dept");
            record.getParams().put("scopeDeptId", getDeptId());
        } else {
            record.setUserId(getUserId());
        }
    }

    private void applySharingRecordDataScope(SharingRecordSearchVo searchVo) {
        SysUser user = getLoginUser().getUser();
        if (user == null || user.isAdmin() || hasDataScope(user.getRoles(), DATA_SCOPE_ALL)) {
            return;
        }
        if (hasDataScope(user.getRoles(), DATA_SCOPE_DEPT_AND_CHILD)) {
            searchVo.setDeptId(getDeptId());
            searchVo.getParams().put("scopeType", "deptAndChild");
        } else if (hasDataScope(user.getRoles(), DATA_SCOPE_DEPT)) {
            searchVo.setDeptId(getDeptId());
            searchVo.getParams().put("scopeType", "dept");
        } else {
            searchVo.setUserId(getUserId());
        }
    }

    private boolean hasDataScope(List<SysRole> roles, String dataScope) {
        return roles != null && roles.stream().anyMatch(role -> dataScope.equals(role.getDataScope()));
    }
}
