package co.yixiang.yshop.module.mp.controller.admin.customerservice;

import co.yixiang.yshop.framework.common.pojo.CommonResult;
import co.yixiang.yshop.framework.common.pojo.PageParam;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.module.mp.controller.admin.customerservice.vo.AddServicerDTO;
import co.yixiang.yshop.module.mp.controller.admin.customerservice.vo.CustomerServiceVO;
import co.yixiang.yshop.module.mp.controller.admin.customerservice.vo.ServicerVO;
import co.yixiang.yshop.module.mp.framework.cp.config.WxCpConfiguration;
import co.yixiang.yshop.module.mp.service.customerservice.CustomerServiceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpDepartmentService;
import me.chanjar.weixin.cp.api.WxCpKfService;
import me.chanjar.weixin.cp.api.WxCpMediaService;
import me.chanjar.weixin.cp.api.WxCpUserService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.kf.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author pepis
 * @apiNote
 **/
@Tag(name = "管理后台 - 客服管理")
@RestController
@RequestMapping("/cp/kf")
@Validated
@Slf4j
public class CustomerServiceController {
    @Resource
    private CustomerServiceService customerServiceService;

    @SneakyThrows
    @GetMapping("page")
    @Operation(summary = "获取客服列表")
    public CommonResult<PageResult<CustomerServiceVO>> getAll(PageParam pageParam) {
        PageResult<CustomerServiceVO> pageResult = customerServiceService.page(pageParam);
        return CommonResult.success(pageResult);
    }

    @SneakyThrows
    @PostMapping
    @Operation(summary = "新增客服")
    public CommonResult<WxCpKfAccountAddResp> save(@RequestBody WxCpKfAccountAdd add) {
        WxCpKfAccountAddResp wxCpKfAccountAddResp = customerServiceService.save(add);
        return CommonResult.success(wxCpKfAccountAddResp);
    }

    @SneakyThrows
    @PutMapping
    @Operation(summary = "编辑客服")
    public CommonResult<Boolean> update(@RequestBody WxCpKfAccountUpd upd) {
        customerServiceService.update(upd);
        return CommonResult.success(true);
    }

    @SneakyThrows
    @DeleteMapping
    @Operation(summary = "删除客服")
    public CommonResult<Boolean> delete(@RequestBody WxCpKfAccountDel del) {
        customerServiceService.delete(del);
        return CommonResult.success(true);
    }

    @SneakyThrows
    @GetMapping("listServicer")
    @Operation(summary = "客服接待人")
    public CommonResult<List<ServicerVO>> listServicer(String openKfid) {
        WxCpKfService kfService = WxCpConfiguration.getCpService().getKfService();
        WxCpUserService userService = WxCpConfiguration.getCpService().getUserService();

        WxCpKfServicerListResp resp = kfService.listServicer(openKfid);
        List<ServicerVO> list = resp.getServicerList().stream().map(item -> {
            ServicerVO servicerVO = new ServicerVO();
            servicerVO.setUserId(item.getUserId());
            servicerVO.setStatus(item.getStatus());
            //获取用户
            try {
                WxCpUser user = userService.getById(item.getUserId());
                servicerVO.setName(user.getName());
            } catch (WxErrorException e) {
                log.warn("获取接待人信息失败:{}", item.getUserId());
                throw new RuntimeException(e);
            }
            return servicerVO;
        }).collect(Collectors.toList());
        return CommonResult.success(list);
    }

    @SneakyThrows
    @PostMapping("addServicer")
    @Operation(summary = "保存接待人")
    public CommonResult<Boolean> addServicer(@RequestBody AddServicerDTO dto) {
        WxCpKfService kfService = WxCpConfiguration.getCpService().getKfService();
        kfService.addServicer(dto.getOpenKfid(), dto.getUserIdList());
        return CommonResult.success(true);
    }

    @SneakyThrows
    @DeleteMapping("delServicer")
    @Operation(summary = "删除接待人")
    public CommonResult<Boolean> delServicer(@RequestBody AddServicerDTO dto) {
        WxCpKfService kfService = WxCpConfiguration.getCpService().getKfService();
        kfService.delServicer(dto.getOpenKfid(), dto.getUserIdList());
        return CommonResult.success(true);
    }

    @SneakyThrows
    @GetMapping("departmentList")
    @Operation(summary = "部门列表")
    public CommonResult<List<WxCpDepart>> departmentList() {
        WxCpDepartmentService departmentService = WxCpConfiguration.getCpService().getDepartmentService();
        List<WxCpDepart> list = departmentService.list(null);
        return CommonResult.success(list);
    }

    @SneakyThrows
    @GetMapping("listUser")
    @Operation(summary = "查询部门下用户")
    public CommonResult<List<WxCpUser>> listUser(Long departId) {
        WxCpUserService userService = WxCpConfiguration.getCpService().getUserService();
        List<WxCpUser> wxCpUsers = userService.listByDepartment(departId, true, 0);
        return CommonResult.success(wxCpUsers);
    }

    @SneakyThrows
    @PostMapping("uploadMaterial")
    @Operation(summary = "上传素材")
    public CommonResult<WxMediaUploadResult> uploadMaterial(@RequestParam(value = "file") MultipartFile file) {
        WxCpMediaService mediaService = WxCpConfiguration.getCpService().getMediaService();
        WxMediaUploadResult upload = mediaService.upload(WxConsts.MediaFileType.IMAGE, file.getOriginalFilename(), file.getInputStream());
        return CommonResult.success(upload);
    }

}
