package com.fuint.module.backendApi.controller;

import com.fuint.common.dto.AccountInfo;
import com.fuint.common.dto.TaskDto;
import com.fuint.common.enums.StatusEnum;
import com.fuint.common.param.TaskPage;
import com.fuint.common.param.TaskRecordPage;
import com.fuint.common.service.StoreService;
import com.fuint.common.service.TaskService;
import com.fuint.common.util.TokenUtil;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.framework.pagination.PaginationResponse;
import com.fuint.framework.web.BaseController;
import com.fuint.framework.web.ResponseObject;
import com.fuint.repository.model.MtStore;
import com.fuint.repository.model.MtTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 任务中心管理 controller
 *
 * Created by Codex
 */
@Api(tags = "管理端-任务中心相关接口")
@RestController
@AllArgsConstructor
@RequestMapping(value = "/backendApi/task")
public class BackendTaskController extends BaseController {

    private TaskService taskService;

    private StoreService storeService;

    @ApiOperation(value = "任务列表查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('content:task:index')")
    public ResponseObject list(@ModelAttribute TaskPage taskPage) throws BusinessCheckException {
        AccountInfo accountInfo = TokenUtil.getAccountInfo();
        if (accountInfo.getMerchantId() != null && accountInfo.getMerchantId() > 0) {
            taskPage.setMerchantId(accountInfo.getMerchantId());
        }
        if (accountInfo.getStoreId() != null && accountInfo.getStoreId() > 0) {
            taskPage.setStoreId(accountInfo.getStoreId());
        }

        PaginationResponse<MtTask> paginationResponse = taskService.queryTaskListByPagination(taskPage);
        List<MtStore> storeList = storeService.getMyStoreList(accountInfo.getMerchantId(), accountInfo.getStoreId(), StatusEnum.ENABLED.getKey());

        Map<String, Object> result = new HashMap<>();
        result.put("dataList", paginationResponse);
        result.put("storeList", storeList);

        return getSuccessResult(result);
    }

    @ApiOperation(value = "公共任务列表查询")
    @RequestMapping(value = "/publicList", method = RequestMethod.GET)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('content:task:index')")
    public ResponseObject publicList(@ModelAttribute TaskPage taskPage) throws BusinessCheckException {
        taskPage.setMerchantId(0);
        taskPage.setStoreId(0);
        PaginationResponse<MtTask> paginationResponse = taskService.queryTaskListByPagination(taskPage);

        Map<String, Object> result = new HashMap<>();
        result.put("dataList", paginationResponse);
        return getSuccessResult(result);
    }

    @ApiOperation(value = "任务完成记录列表查询")
    @RequestMapping(value = "/recordList", method = RequestMethod.GET)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('content:task:index')")
    public ResponseObject recordList(@ModelAttribute TaskRecordPage taskRecordPage) throws BusinessCheckException {
        AccountInfo accountInfo = TokenUtil.getAccountInfo();
        if (accountInfo.getMerchantId() != null && accountInfo.getMerchantId() > 0) {
            taskRecordPage.setMerchantId(accountInfo.getMerchantId());
        }
        if (accountInfo.getStoreId() != null && accountInfo.getStoreId() > 0) {
            taskRecordPage.setStoreId(accountInfo.getStoreId());
        }

        PaginationResponse<Map<String, Object>> paginationResponse = taskService.queryTaskRecordListByPagination(taskRecordPage);
        Map<String, Object> result = new HashMap<>();
        result.put("dataList", paginationResponse);
        return getSuccessResult(result);
    }

    @ApiOperation(value = "获取任务详情")
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('content:task:index')")
    public ResponseObject info(@PathVariable("id") Integer id) throws BusinessCheckException {
        AccountInfo accountInfo = TokenUtil.getAccountInfo();
        MtTask taskInfo = taskService.queryTaskById(id);
        if (taskInfo == null) {
            return getFailureResult(201);
        }
        if (accountInfo.getMerchantId() != null && accountInfo.getMerchantId() > 0
                && !taskInfo.getMerchantId().equals(accountInfo.getMerchantId())) {
            return getFailureResult(1004);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("taskInfo", taskInfo);
        return getSuccessResult(result);
    }

    @ApiOperation(value = "保存任务")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('content:task:add') or @pms.hasPermission('content:task:edit')")
    public ResponseObject saveHandler(@RequestBody TaskDto taskDto) throws BusinessCheckException {
        AccountInfo accountInfo = TokenUtil.getAccountInfo();
        taskDto.setOperator(accountInfo.getAccountName());
        if (accountInfo.getMerchantId() != null && accountInfo.getMerchantId() > 0) {
            taskDto.setMerchantId(accountInfo.getMerchantId());
        }
        if (accountInfo.getStoreId() != null && accountInfo.getStoreId() > 0) {
            taskDto.setStoreId(accountInfo.getStoreId());
        }

        if (taskDto.getId() != null && taskDto.getId() > 0) {
            taskService.updateTask(taskDto);
        } else {
            taskService.addTask(taskDto);
        }
        return getSuccessResult(true);
    }

    @ApiOperation(value = "更新任务状态")
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('content:task:edit')")
    public ResponseObject updateStatus(@RequestBody Map<String, Object> params) throws BusinessCheckException {
        String status = params.get("status") != null ? params.get("status").toString() : StatusEnum.ENABLED.getKey();
        Integer id = params.get("id") == null ? 0 : Integer.parseInt(params.get("id").toString());

        AccountInfo accountInfo = TokenUtil.getAccountInfo();
        MtTask taskInfo = taskService.queryTaskById(id);
        if (taskInfo == null) {
            return getFailureResult(201);
        }

        TaskDto taskDto = new TaskDto();
        taskDto.setId(id);
        taskDto.setOperator(accountInfo.getAccountName());
        taskDto.setStatus(status);
        taskService.updateTask(taskDto);

        return getSuccessResult(true);
    }

    @ApiOperation(value = "导入公共任务")
    @RequestMapping(value = "/importPublic", method = RequestMethod.POST)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('content:task:add')")
    public ResponseObject importPublic(@RequestBody Map<String, Object> params) throws BusinessCheckException {
        AccountInfo accountInfo = TokenUtil.getAccountInfo();
        Integer merchantId = accountInfo.getMerchantId();
        if (merchantId == null || merchantId <= 0) {
            throw new BusinessCheckException("当前账号未绑定商户，无法导入");
        }

        Integer storeId = accountInfo.getStoreId() == null ? 0 : accountInfo.getStoreId();
        if (storeId <= 0 && params.get("storeId") != null) {
            storeId = Integer.parseInt(params.get("storeId").toString());
        }

        List<Integer> taskIds = new ArrayList<>();
        Object taskIdsObj = params.get("taskIds");
        if (taskIdsObj instanceof List) {
            List<?> sourceList = (List<?>) taskIdsObj;
            for (Object item : sourceList) {
                if (item == null) {
                    continue;
                }
                taskIds.add(Integer.parseInt(item.toString()));
            }
        }

        Map<String, Object> importResult = taskService.importPublicTask(merchantId, storeId, taskIds, accountInfo.getAccountName());
        return getSuccessResult(importResult);
    }
}
