package com.eleadmin.oa.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.core.utils.CommonUtil;
import com.eleadmin.common.core.web.ApiResult;
import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.core.web.PageParam;
import com.eleadmin.common.core.web.PageResult;
import com.eleadmin.oa.entity.Customer;
import com.eleadmin.oa.param.CustomerParam;
import com.eleadmin.oa.server.CustomerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 客户控制器
 *
 * @author gxwebsoft.com
 * @since 2020-03-14 11:29:03
 */
@Api(tags = "客户管理")
@RestController
@RequestMapping("/api/customer")
public class CustomerController extends BaseController {
    @Resource
    private CustomerService customerService;

    @PreAuthorize("hasAuthority('sys:customer:list')")
    @OperationLog
    @ApiOperation("分页查询客户")
    @GetMapping("/page")
    public ApiResult<PageResult<Customer>> page(CustomerParam param) {
        PageParam<Customer, CustomerParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number,create_time desc");
        return success(customerService.page(page, page.getWrapper()));
    }

    @PreAuthorize("hasAuthority('sys:customer:list')")
    @OperationLog
    @ApiOperation("查询全部客户")
    @GetMapping()
    public ApiResult<List<Customer>> list(CustomerParam param) {
        PageParam<Customer, CustomerParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number,create_time desc");
        return success(customerService.list(page.getOrderWrapper()));
    }

    @PreAuthorize("hasAuthority('sys:customer:list')")
    @OperationLog
    @ApiOperation("根据id查询客户")
    @GetMapping("/{id}")
    public ApiResult<Customer> get(@PathVariable("id") Integer id) {
        return success(customerService.getById(id));
    }

    @PreAuthorize("hasAuthority('sys:customer:save')")
    @ApiOperation("添加客户")
    @PostMapping()
    public ApiResult<?> add(@RequestBody Customer customer) {
        if (customerService.count(new LambdaQueryWrapper<Customer>()
                .eq(Customer::getCustomerCode, customer.getCustomerCode())) > 0) {
            return fail("客户标识已存在");
        }
        if (customerService.count(new LambdaQueryWrapper<Customer>()
                .eq(Customer::getCustomerName, customer.getCustomerName())) > 0) {
            return fail("客户名称已存在");
        }
        customer.setCustomerId(getLoginUserId());
        if (customerService.save(customer)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('sys:customer:update')")
    @OperationLog
    @ApiOperation("修改客户")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Customer customer) {
        if (customerService.count(new LambdaQueryWrapper<Customer>()
                .eq(Customer::getCustomerCode, customer.getCustomerCode())
                .ne(Customer::getCustomerId, customer.getCustomerId())) > 0) {
            return fail("客户标识已存在");
        }
        if (customerService.count(new LambdaQueryWrapper<Customer>()
                .eq(Customer::getCustomerName, customer.getCustomerName())
                .ne(Customer::getCustomerId, customer.getCustomerId())) > 0) {
            return fail("客户名称已存在");
        }
//        customer.setCustomerId(getLoginUserId());
        if (customerService.updateById(customer)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('sys:customer:remove')")
    @OperationLog
    @ApiOperation("删除客户")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (customerService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('sys:customer:save')")
    @OperationLog
    @ApiOperation("批量添加客户")
    @PostMapping("/batch")
    public ApiResult<List<String>> saveBatch(@RequestBody List<Customer> list) {
        if (CommonUtil.checkRepeat(list, Customer::getCustomerId)) {
            return fail("客户标识不能重复", null);
        }
        if (CommonUtil.checkRepeat(list, Customer::getCustomerName)) {
            return fail("客户名称不能重复", null);
        }
        List<Customer> codeExists = customerService.list(new LambdaQueryWrapper<Customer>()
                .in(Customer::getCustomerCode, list.stream().map(Customer::getCustomerCode)
                        .collect(Collectors.toList())));
        if (codeExists.size() > 0) {
            return fail("客户标识已存在", codeExists.stream().map(Customer::getCustomerCode)
                    .collect(Collectors.toList())).setCode(2);
        }
        List<Customer> nameExists = customerService.list(new LambdaQueryWrapper<Customer>()
                .in(Customer::getCustomerName, list.stream().map(Customer::getCustomerName)
                        .collect(Collectors.toList())));
        if (nameExists.size() > 0) {
            return fail("客户名称已存在", nameExists.stream().map(Customer::getCustomerName)
                    .collect(Collectors.toList())).setCode(3);
        }
        if (customerService.saveBatch(list)) {
            return success("添加成功", null);
        }
        return fail("添加失败", null);
    }

    @PreAuthorize("hasAuthority('sys:customer:remove')")
    @OperationLog
    @ApiOperation("批量删除客户")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (customerService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
