package cn.iocoder.yudao.module.custom.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.custom.entity.CustomerMain;
import cn.iocoder.yudao.module.custom.service.CustomerCarService;
import cn.iocoder.yudao.module.custom.service.CustomerMainService;
import cn.iocoder.yudao.module.custom.vo.CustomerExportVO;
import cn.iocoder.yudao.module.custom.vo.CustomerMainPageReqVO;
import cn.iocoder.yudao.module.custom.vo.CustomerMainRespVO;
import cn.iocoder.yudao.module.custom.vo.CustomerMainSaveReqVO;
import cn.iocoder.yudao.module.label.service.BusiLabelService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.common.BaseConstants.*;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 客户管理（每个租户的下的客户信息）
 *
 * @author : http://www.chiner.pro
 * @date : 2024-7-31
 */
@RestController
@RequestMapping("/base/custom")
@Tag(name = "管理后台 - BASE 企业管理")
@Validated
public class CustomerMainController {
    @Resource
    private CustomerMainService customerMainService;
    @Resource
    private BusiLabelService busiLabelService;
    @Resource
    private CustomerCarService customerCarService;

    /**
     * 客户管理分页列表查询
     *
     * @param pageReqVO 客户管理查询条件封装实体
     * @param pageNo    分页参数
     * @param pageSize  分页参数
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<com.baomidou.mybatisplus.core.metadata.IPage < ?>>
     * @author PQZ
     * @date 14:56 2024/8/1
     **/
    @GetMapping("/page")
    @Operation(summary = "获得客户管理分页")
    @PreAuthorize("@ss.hasPermission('base:customer-main:query')")
    public CommonResult<IPage<?>> getCustomerMainPage(CustomerMainPageReqVO pageReqVO,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<CustomerMainRespVO> page = new Page<>(pageNo, pageSize);
        return success(customerMainService.queryListPage(pageReqVO, page));
    }

    /**
     * 新增客户
     *
     * @param saveReqVO 保存客户信息扩展实体
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 15:42 2024/8/1
     **/
    @PostMapping("/create")
    @Operation(summary = "创建客户管理")
    @PreAuthorize("@ss.hasPermission('base:customer-main:create')")
    public CommonResult<Boolean> createCustomerMain(@Valid @RequestBody CustomerMainSaveReqVO saveReqVO) {
        customerMainService.saveCustomer(saveReqVO, SIGN_CREATE);
        return success(true);
    }


    @PostMapping("/saveCustomerAndCar")
    @Operation(summary = "保存客户及车辆信息")
    public CommonResult<?> saveCustomerAndCar(@RequestBody CustomerMainSaveReqVO saveReqVO) throws Exception {
        return CommonResult.success(customerCarService.saveCustomerAndCar(saveReqVO));
    }

    /**
     * 编辑客户
     *
     * @param saveReqVO 保存客户信息扩展实体
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 15:44 2024/8/1
     **/
    @PutMapping("/update")
    @Operation(summary = "更新客户管理")
    @PreAuthorize("@ss.hasPermission('base:customer-main:update')")
    public CommonResult<Boolean> updateCustomerMain(@Valid @RequestBody CustomerMainSaveReqVO saveReqVO) {
        customerMainService.saveCustomer(saveReqVO, SIGN_UPDATE);
        return success(true);
    }

    /**
     * 删除客户
     *
     * @param id 保存客户信息扩展实体
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 15:44 2024/8/1
     **/
    @DeleteMapping("/delete")
    @Operation(summary = "删除客户管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('base:customer-main:delete')")
    public CommonResult<Boolean> deleteCustomerMain(@RequestParam("id") String id) {
        // TODO: 2024/8/4 临时
        customerMainService.removeById(id);
        return success(true);
    }

    /**
     * 通过客户id查询客户信息
     *
     * @param id 客户id
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 15:44 2024/8/1
     **/
    @GetMapping("/get")
    @Operation(summary = "获得客户管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<CustomerMainRespVO> getCustomerMain(@RequestParam("id") String id) {
        return success(customerMainService.getCustomerById(id));
    }


    /**
     * 根据经办人所属企业查询经办人信息
     *
     * @param deptCode 经办人所属企业code
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 16:15 2024/8/2
     **/
    @GetMapping("/getAttn")
    @Operation(summary = "根据deptCode获取经办人信息")
    public CommonResult<List<CustomerMain>> getCustomerMainByDeptCode(@RequestParam("deptCode") String deptCode) {
        return success(customerMainService.getCustomerByDeptCode(deptCode));
    }

    /**
     * 绑定车辆
     *
     * @param saveReqVO CustomerMainSaveReqVO
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 19:21 2024/8/3
     **/
    @PostMapping("/bindCustomerCar")
    @Operation(summary = "绑定车辆")
    @PreAuthorize("@ss.hasPermission('base:customer-main:car')")
    public CommonResult<Boolean> bindCustomerCar(@Valid @RequestBody CustomerMainSaveReqVO saveReqVO) {
        customerMainService.bindCustomAndCar(saveReqVO);
        return success(true);
    }

    /**
     * 设置标签
     *
     * @param saveReqVO CustomerMainSaveReqVO
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 16:35 2024/8/6
     **/
    @PostMapping("/setLabel")
    @Operation(summary = "设置标签")
    public CommonResult<Boolean> setLabel(@Valid @RequestBody CustomerMainSaveReqVO saveReqVO) {
        busiLabelService.saveBusiLable(saveReqVO.getId(), TABLE_BASE_CUSTOMER_MAIN, saveReqVO.getLabelList());
        return success(true);
    }

    /**
     * 根据姓名和电话查询单条记录
     *
     * @param customerMain 查询对象
     * @author 小李
     * @date 11:19 2024/10/8
     **/
    @PostMapping("/getByNameAndMobile")
    @Operation(summary = "根据姓名和电话查询单条记录")
    public CommonResult<?> getByNameAndMobile(@Valid @RequestBody CustomerMain customerMain) {
        List<CustomerMain> list = customerMainService.list(new LambdaQueryWrapper<CustomerMain>().and(item -> {
            item.eq(CustomerMain::getCusName, customerMain.getCusName())
                    .eq(CustomerMain::getPhoneNumber, customerMain.getPhoneNumber());
        }));
        if (CollectionUtil.isNotEmpty(list)) {
            return success(list.get(0));
        }
        throw exception0(500, "系统异常");
    }

    /**
     * 导出数据
     *
     * @author 小李
     * @date 19:33 2024/12/2
     * @param pageReqVO 请求对象
    **/
    @GetMapping("/export")
    @Operation(summary = "导出数据")
    public void exportData(CustomerMainPageReqVO pageReqVO, HttpServletResponse response) throws IOException {
        int pageNo = 1, pageSize = 1000;
        List<CustomerExportVO> list = new ArrayList<>();
        Page<CustomerMainRespVO> page = new Page<>(pageNo, pageSize);
        do {
            IPage<CustomerMainRespVO> customerMainRespVOIPage = customerMainService.queryListPage(pageReqVO, page);
            List<CustomerMainRespVO> records = customerMainRespVOIPage.getRecords();
            if (CollUtil.isEmpty(records)){
                break;
            }
            List<CustomerExportVO> convertedRecords = records.stream().map(item -> BeanUtils.toBean(item, CustomerExportVO.class)).collect(Collectors.toList());
            list.addAll(convertedRecords);
            pageNo++;
            page.setCurrent(pageNo);
        }while (true);
        if (CollUtil.isEmpty(list)){
            throw exception0(500, "没有数据可以导出");
        }
        list.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getIsHangAccount())){
                item.setIsHangAccount(item.getIsHangAccount().equals("0") ? "否" : "是");
            }
        });
        ExcelUtils.write(response, "客户数据.xls", "数据", CustomerExportVO.class, list);
    }
}