package com.yc.ship.module.ota.controller.admin.distributor;

import com.yc.ship.framework.common.exception.ServiceException;
import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.pojo.PageParam;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.excel.core.util.ExcelUtils;
import com.yc.ship.framework.operatelog.core.annotations.OperateLog;
import com.yc.ship.module.ota.controller.admin.distributor.vo.*;
import com.yc.ship.module.ota.dal.dataobject.distributor.DistributorDO;
import com.yc.ship.module.ota.enums.ErrorCodeConstants;
import com.yc.ship.module.ota.service.distributor.DistributorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.yc.ship.framework.common.pojo.CommonResult.error;
import static com.yc.ship.framework.common.pojo.CommonResult.success;
import static com.yc.ship.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.yc.ship.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 分销商信息")
@RestController
@RequestMapping("/distributor")
@Validated
public class DistributorController {

    @Resource
    private DistributorService distributorService;

    @PostMapping("/create")
    @Operation(summary = "创建分销商信息")
    @PreAuthorize("@ss.hasPermission('ota:distributor:create')")
    public CommonResult<Long> createDistributor(@Valid @RequestBody DistributorSaveReqVO createReqVO) {
        return success(distributorService.createDistributor(createReqVO));
    }

    @GetMapping("/createCardNo")
    @Operation(summary = "创建分销商子账户")
    @PreAuthorize("@ss.hasPermission('ota:distributor:create')")
    public CommonResult<String> createCardNo(@RequestParam("id") Long id) {
        return success(distributorService.createCardNo(id));
    }

    @PostMapping("/import")
    @Operation(summary = "导入分销商")
    @Parameters({@Parameter(name = "file", description = "Excel 文件", required = true)})
    @PreAuthorize("@ss.hasPermission('ota:distributor:create')")
    public CommonResult<DistributorImportRespVO> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        List<DistributorImportExcelVO> list = ExcelUtils.read(file, DistributorImportExcelVO.class);
        return success(distributorService.importDistributorList(list));
    }

    @PutMapping("/update")
    @Operation(summary = "更新分销商信息")
    @PreAuthorize("@ss.hasPermission('ota:distributor:update')")
    public CommonResult<Boolean> updateDistributor(@Valid @RequestBody DistributorSaveReqVO updateReqVO) {
        distributorService.updateDistributor(updateReqVO);
        return success(true);
    }

    @PutMapping("/updatePassword")
    @Operation(summary = "更新分销商登录密码")
    @PreAuthorize("@ss.hasPermission('ota:distributor:update')")
    public CommonResult<Boolean> updatePassword(@Valid @RequestBody DistributorUpdatePasswordReqVO updateReqVO) {
        distributorService.updatePassword(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除分销商信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('ota:distributor:delete')")
    public CommonResult<Boolean> deleteDistributor(@RequestParam("id") Long id) {
        distributorService.deleteDistributor(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得分销商信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('ota:distributor:query')")
    public CommonResult<DistributorRespVO> getDistributor(@RequestParam("id") Long id) {
        DistributorDO distributor = distributorService.getDistributor(id);
        if(distributor==null){
            return error(500,"分销商不存在");
        }
        DistributorRespVO DistributorRespVO = BeanUtils.toBean(distributor, DistributorRespVO.class);
        String functions = distributor.getFunctions();
        if(StringUtils.isNoneBlank(functions)){
            DistributorRespVO.setFunctions(Arrays.asList(functions.split(",")));
        }
        String teamType = distributor.getTeamType();
        if(StringUtils.isNoneBlank(teamType)){
            DistributorRespVO.setTeamType(Arrays.asList(teamType.split(",")));
        }
        return success(DistributorRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得分销商信息分页")
//    @PreAuthorize("@ss.hasPermission('ota:distributor:query')")
    public CommonResult<PageResult<DistributorRespVO>> getDistributorPage(@Valid DistributorPageReqVO pageReqVO) {
        PageResult<DistributorDO> pageResult = distributorService.getDistributorPage(pageReqVO);
        PageResult<DistributorRespVO> distributorPage = BeanUtils.toBean(pageResult, DistributorRespVO.class);
        // 查询累计余额充值和授信充值金额
        distributorPage.getList().forEach(distributorDO -> {
            DistributorRespVO vo = distributorService.queryDistributorMoneyTotal(distributorDO.getId());
            distributorDO.setPayCreditTotal(vo == null ? BigDecimal.ZERO : vo.getPayCreditTotal());
            distributorDO.setBalanceTotal(vo == null ? BigDecimal.ZERO : vo.getBalanceTotal());
        });
        return success(distributorPage);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出分销商信息 Excel")
    @PreAuthorize("@ss.hasPermission('ota:distributor:export')")
    @OperateLog(type = EXPORT,enable = false)
    public void exportDistributorExcel(@Valid DistributorPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DistributorDO> list = distributorService.getDistributorPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "分销商信息.xls", "数据", DistributorRespVO.class,
                        BeanUtils.toBean(list, DistributorRespVO.class));
    }


    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取分销商精简信息列表", description = "只包含被开启的类型，主要用于前端的下拉选项")
    public CommonResult<List<DistributorSimpleRespVO>> getSimpleList(DistributorListReqVO reqVO) {

        reqVO.setIsUse(1);
        List<DistributorDO> list= distributorService.getSimpleList(reqVO);

        return success(BeanUtils.toBean(list, DistributorSimpleRespVO.class));
    }

    @PutMapping("/update-status")
    @Operation(summary = "更改状态")
    @PreAuthorize("@ss.hasPermission('ota:distributor:update')")
    public CommonResult<Boolean> updateStatus(@Valid @RequestBody DistributorSaveReqVO updateReqVO) {
        distributorService.updateStatus(updateReqVO.getId(),updateReqVO.getIsUse());
        return success(true);
    }

    @PostMapping({"/list-otc-simple"})
    @Operation(summary = "获取挂靠旅行社列表", description = "只包含被开启的类型，主要用于前端的下拉选项")
    public CommonResult<List<Map>> getSimpleList(@RequestBody DistributorSaveReqVO params) {
        List<Map> list= distributorService.getOtcSimpleList(params);
        return success(list);
    }



    @GetMapping({"/get-by-name"})
    @Operation(summary = "获取分销商信息")
    public CommonResult<DistributorRespVO> getDistributorByName(@RequestParam("name") String name) {
        DistributorDO distributorDO = distributorService.getDistributorByName(name);
        DistributorDO distributorCopy = new DistributorDO();
        distributorCopy.setId(distributorDO.getId());
        distributorCopy.setName(distributorDO.getName());
        return success(BeanUtils.toBean(distributorCopy, DistributorRespVO.class));
    }

    @GetMapping("/getLoginType")
    @Operation(summary = "获取用户类型")
    public CommonResult<LoginTypeRespVO> getLoginType() {
        return success(distributorService.getLoginType());
    }

    @GetMapping("/getOtcDistributor")
    @Operation(summary = "获取分销商")
    public CommonResult<List<DistributorRespVO>> getOtcDistributor(@RequestParam("type") Integer type) {
        return success(distributorService.getOtcDistributor(type));
    }

    @GetMapping("/getOtcDistributorWithId")
    @Operation(summary = "获取分销商及产品id")
    public CommonResult<List<DistributorRespVO>> getOtcDistributorWithId(@RequestParam("type") Integer type, @RequestParam("productId") Long productId) {
        return success(distributorService.getOtcDistributor(type, productId));
    }

    @GetMapping("/getAllDistributor")
    @Operation(summary = "获取分销商")
    public CommonResult<List<DistributorRespVO>> getAllDistributor() {
        return success(distributorService.getOtcDistributor(null));
    }

    @GetMapping("/getDistributorByUserId")
    @Operation(summary = "获取当前登录用户的分销商信息")
    public CommonResult<DistributorRespVO> getDistributorByUserId() {
        DistributorDO distributor = distributorService.getDistributorByLoginUserId(getLoginUserId());
        if(distributor == null){
            throw new ServiceException(ErrorCodeConstants.DISTRIBUTOR_USER_NOT_EXISTS);
        }
        DistributorRespVO DistributorRespVO = BeanUtils.toBean(distributor, DistributorRespVO.class);
        String functions = distributor.getFunctions();
        if(StringUtils.isNoneBlank(functions)){
            DistributorRespVO.setFunctions(Arrays.asList(functions.split(",")));
        }
        String teamType = distributor.getTeamType();
        if(StringUtils.isNoneBlank(teamType)){
            DistributorRespVO.setTeamType(Arrays.asList(teamType.split(",")));
        }
        return success(DistributorRespVO);
    }
}
