package com.qmth.sop.server.api;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.sop.business.bean.result.SysCustomResult;
import com.qmth.sop.business.entity.SysCustom;
import com.qmth.sop.business.entity.SysCustomAddr;
import com.qmth.sop.business.entity.TBTask;
import com.qmth.sop.business.service.SysCustomAddrService;
import com.qmth.sop.business.service.SysCustomService;
import com.qmth.sop.business.service.TBTaskService;
import com.qmth.sop.business.templete.execute.AsyncSysCustomImportService;
import com.qmth.sop.common.annotation.OperationLog;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.LogTypeEnum;
import com.qmth.sop.common.enums.ProductTypeEnum;
import com.qmth.sop.common.enums.TaskTypeEnum;
import com.qmth.sop.common.util.Result;
import com.qmth.sop.common.util.ResultUtil;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.Map;
import java.util.Objects;

/**
 * 客户表 控制器.
 *
 * @author: shudonghui
 * @date: 2023-08-02 11:55:19
 * @version: 1.0
 * @email: shudonghui@qmth.com.cn
 * @Company: www.qmth.com.cn
 */
@Api(tags = "客户表 Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_CUSTOM)
public class SysCustomController {


    @Resource
    SysCustomService sysCustomService;

    @Resource
    AsyncSysCustomImportService asyncSysCustomImportService;

    @Resource
    TBTaskService tbTaskService;

    @Resource
    SysCustomAddrService sysCustomAddrService;


    @ApiOperation(value = "客户表查询接口")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "客户表列表信息", response = SysCustomResult.class)})
    public Result query(
            @ApiParam(value = "客户类型", required = false) @RequestParam(required = false) ProductTypeEnum type,
            @ApiParam(value = "客户经理id", required = false) @RequestParam(required = false) Long managerId,
            @ApiParam(value = "客户名称", required = false) @RequestParam(required = false) String name,
            @ApiParam(value = "服务档位id", required = false) @RequestParam(required = false) Long levelId,
            @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
            @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        IPage<SysCustomResult> resultIPage = sysCustomService.query(new Page<>(pageNumber, pageSize), type, managerId, name, levelId);
        return ResultUtil.ok(resultIPage);
    }


    @ApiOperation(value = "新增客户表接口")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "新增客户表信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.ADD)
    public Result add(@Valid @ApiParam(value = "客户信息", required = true) @RequestBody(required = true) SysCustomResult sysCustom, BindingResult bindingResult) throws InterruptedException {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        sysCustomService.saveCustom(sysCustom);
        return ResultUtil.ok();
    }


    @ApiOperation(value = "修改客户表接口")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "修改客户表信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.UPDATE)
    public Result update(@Valid @ApiParam(value = "客户信息", required = true) @RequestBody(required = true) SysCustomResult sysCustom, BindingResult bindingResult) throws InterruptedException {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        sysCustomService.saveCustom(sysCustom);
        return ResultUtil.ok();
    }

    @ApiOperation(value = "删除客户表接口")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "删除客户表信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.DELETE)
    public Result delete(@ApiParam(value = "客户id", required = true) @RequestParam(required = true) long id) {
        sysCustomService.delete(id);
        return ResultUtil.ok();
    }

    /**
     * 获取单个客户
     *
     * @param id
     * @return
     */

    @ApiOperation(value = "获取单个客户")
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "获取单个客户", response = SysCustomResult.class)})
    public Result detail(@ApiParam(value = "客户id", required = true) @RequestParam(required = true) long id) {
        SysCustom sysCustom = sysCustomService.getById(id);
        SysCustomResult sysCustomResult = JSON.toJavaObject((JSON) JSON.toJSON(sysCustom), SysCustomResult.class);
        sysCustomResult.setAddrList(sysCustomAddrService.list(new QueryWrapper<SysCustomAddr>().lambda().eq(SysCustomAddr::getCustomId, sysCustomResult.getId())));
        return ResultUtil.ok(sysCustomResult);
    }

    @ApiOperation(value = "客户表导入")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.IMPORT)
    public Result importCustom(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file) throws Exception {
        Map<String, Object> map = tbTaskService.saveTask(file, TaskTypeEnum.CUSTOM_IMPORT);
        asyncSysCustomImportService.importTask(map);
        TBTask tbTask = (TBTask) map.get(SystemConstant.TASK);
        return ResultUtil.ok(tbTask.getId());
    }

    //按照类型状态查询客户
    @ApiOperation(value = "客户表查询")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = SysCustom.class)})
    public Result list(@ApiParam(value = "是否启用", required = false) @RequestParam(required = false) Boolean enable,
                       @ApiParam(value = "类型", required = false) @RequestParam(required = false) ProductTypeEnum type) {
        return ResultUtil.ok(sysCustomService.list(new QueryWrapper<SysCustom>().lambda().eq(Objects.nonNull(enable), SysCustom::getEnable, enable).eq(Objects.nonNull(type), SysCustom::getType, type)));
    }
}