package com.gxwebsoft.oa.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.utils.MyQrCodeUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.utils.RequestUtil;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.controller.AliOssController;
import com.gxwebsoft.common.system.entity.DictData;
import com.gxwebsoft.common.system.entity.Role;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.oa.entity.Task;
import com.gxwebsoft.oa.entity.TaskCount;
import com.gxwebsoft.oa.entity.TaskRecord;
import com.gxwebsoft.oa.param.TaskParam;
import com.gxwebsoft.oa.service.TaskCountService;
import com.gxwebsoft.oa.service.TaskRecordService;
import com.gxwebsoft.oa.service.TaskService;
import com.gxwebsoft.shop.entity.Merchant;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.service.MerchantService;
import com.gxwebsoft.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.gxwebsoft.common.core.constants.TaskConstants.*;

/**
 * 任务记录表控制器
 *
 * @author 科技小王子
 * @since 2023-10-23 18:53:01
 */
@Api(tags = "任务记录表管理")
@RestController
@RequestMapping("/api/oa/task")
public class TaskController extends BaseController {
    @Resource
    private TaskService taskService;
    @Resource
    private TaskRecordService taskRecordService;
    @Resource
    private TaskCountService taskCountService;
    @Resource
    private OrderService orderService;
    @Resource
    private MerchantService merchantService;

    @Autowired
    private RequestUtil requestUtil;
    @Autowired
    private AliOssController aliOssController;
    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation("分页查询任务记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<Task>> page(TaskParam param) {
        // 使用关联查询
        param.setLoginUserId(getLoginUserId());
        return success(taskService.pageRel(param));
    }

    @ApiOperation("查询全部任务记录表")
    @GetMapping()
    public ApiResult<List<Task>> list(TaskParam param) {
        PageParam<Task, TaskParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(taskService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(taskService.listRel(param));
    }

    @ApiOperation("根据id查询任务记录表")
    @GetMapping("/{id}")
    public ApiResult<Task> get(@PathVariable("id") Integer id) {
        // 更新阅读状态
        Task task = taskService.getByIdRel(id);
        if (!task.getLastReadUser().equals(getLoginUserId())) {
            task.setIsRead(1);
            taskService.updateById(task);
        }
        return success(task);
    }

    @ApiOperation("添加任务记录表")
    @Transactional(rollbackFor = {Exception.class})
    @PostMapping()
    public ApiResult<?> save(@RequestBody Task task) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
            task.setUserId(loginUser.getUserId());
            Role role = loginUser.getRoles().get(0);
            task.setRoleId(role.getRoleId());
            task.setRoleCode(role.getRoleCode());
            task.setOrganizationId(loginUser.getOrganizationId());
            task.setAvatar(loginUser.getAvatar());
            task.setNickname(loginUser.getNickname());
            task.setLastAvatar(loginUser.getAvatar());
            task.setLastReadUser(loginUser.getUserId());
            task.setLastNickname(loginUser.getNickname());
            if (task.getName() == null) {
                task.setName(task.getContent());
            }
        }
        if (taskService.saveByRel(task)) {
            return success("添加成功", task);
        }
        return fail("添加失败");
    }

    @ApiOperation("修改任务记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Task task) {
        if (taskService.updateById(task)) {
            // 更新统计表
            task.setLoginUserId(getLoginUserId());
            taskService.updateCount(task);
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("删除任务记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (taskService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("批量添加任务记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Task> list) {
        if (taskService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @ApiOperation("批量修改任务记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Task> batchParam) {
        if (batchParam.update(taskService, "task_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("批量删除任务记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (taskService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("统计信息")
    @GetMapping("/count")
    public ApiResult<?> count(TaskParam param) {
        User loginUser = getLoginUser();
        ArrayList<Object> countNum = taskService.getCountNum(loginUser, param);
        return success("操作成功", countNum);
    }

    @ApiOperation("生成邀请加入二维码")
    @GetMapping("/taskJoinQRCode")
    public ApiResult<?> taskJoinQRCode(TaskParam param, HttpServletRequest request) throws IOException {
        User loginUser = getLoginUser();
        String access_token = JwtUtil.getAccessToken(request);
        String url = "https://modules.gxwebsoft.com/passport/register?type=join&dealerId=".concat(loginUser.getUserId().toString()) + "&token=".concat(access_token);
        final String qrCode = MyQrCodeUtil.getUserCode(loginUser.getUserId(), url);
        return success("操作成功", qrCode);
    }


//    @Scheduled(cron = "* * * * * *")
    public void task() {
        // 15分钟未支付取消
        orderService.update(
                new LambdaUpdateWrapper<Order>()
                        .eq(Order::getPayStatus, 0)
                        .eq(Order::getOrderStatus, 0)
                        .apply("now() > DATE_ADD(`create_time`, INTERVAL " + 60 + " MINUTE)")
                        .set(Order::getOrderStatus, 2)
        );

        // 7天自动确认收货
        requestUtil.setTenantId("10559");
        ApiResult<?> dictDataApiResult = requestUtil.getDictData(790);
        Map<String, Object> dictDataApiResultData = (Map<String, Object>) dictDataApiResult.getData();
        List<Object> dictDataList = (List<Object>) dictDataApiResultData.get("list");
        int autoConfirmDay = 0;
        for (Object dictData : dictDataList) {
            Map<String, Object> dictData1 = JSONUtil.parseObject(JSONUtil.toJSONString(dictData), Map.class);
            if (dictData1.get("dictDataName").equals("自动确认收货"))
                autoConfirmDay = Integer.parseInt(dictData1.get("dictDataCode").toString());
        }
//        System.out.println("autoConfirmDay = " + autoConfirmDay);
        if (autoConfirmDay != 0) {
            List<Order> expressOrderList = orderService.list(
                    new LambdaQueryWrapper<Order>()
                            .eq(Order::getType, 0)
                            .eq(Order::getDeliveryType, 0)
                            .eq(Order::getPayStatus, 1)
                            .eq(Order::getOrderStatus, 0)
                            .eq(Order::getDeliveryStatus, 20)
            );
            if (!expressOrderList.isEmpty()) {
                for (Order expressOrder : expressOrderList) {
                    if (expressOrder.getDeliveryTime() != null &&
                            DateUtil.offsetDay(expressOrder.getDeliveryTime(), autoConfirmDay).isBeforeOrEquals(new Date())) {
                        expressOrder.setOrderStatus(1);
                        orderService.updateById(expressOrder);
                        orderService.doSettle(expressOrder.getOrderId());
                    }
                }
            }
        }
    }
}
