package com.ics.admin.controller.meeting;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import com.ics.admin.domain.Customer;
import com.ics.admin.domain.meeting.CustomerTicket;
import com.ics.admin.domain.meeting.vo.TicketCustomerVo;
import com.ics.admin.service.ICustomerService;
import com.ics.admin.service.meeting.ICustomerTicketService;
import com.ics.common.core.domain.IcsCustomerStaff;
import com.ics.system.domain.User;
import com.ics.system.service.ICurrentUserService;
import com.ics.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ics.common.core.domain.R;
import com.ics.common.core.controller.BaseController;
import com.ics.admin.domain.meeting.Ticket;
import com.ics.admin.service.meeting.ITicketService;
import org.wf.jwtp.annotation.Ignore;
import org.wf.jwtp.annotation.RequiresPermissions;
import org.wf.jwtp.util.SubjectUtil;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
/**
 * 优惠卷 提供者
 *
 * @author chen
 * @date 2024-02-25
 */
@RestController
@RequestMapping("/meeting/ticket")
public class TicketController extends BaseController {

    @Autowired
    private ITicketService ticketService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICustomerTicketService customerTicketService;

    @Autowired
    private ICurrentUserService currentUserService;



    /**
     * 查询优惠卷
     */
    @Ignore
    @GetMapping("get/{id}")
    public Ticket get(@PathVariable("id") Long id) {
        Ticket ticket = ticketService.selectTicketById(id);

        List<Customer> customers = customerService.selectCustomerList(new Customer());

        List<Customer> customerList = new ArrayList<>();
        List<Customer> selectList = new ArrayList<>();
        List<CustomerTicket> customerTickets = customerTicketService.selectListByTicketId(id);
        Optional<CustomerTicket> min = customerTickets.stream()
                .min(Comparator.comparing(CustomerTicket::getNum));
        Map<Long, CustomerTicket> customerMap = customerTickets.stream().collect(Collectors.toMap(CustomerTicket::getCustomerId, Function.identity()));
        for (Customer customer : customers) {
            //根据外层遍历的学信息id get学生住宿信息Map中的Key
            CustomerTicket customerTicket = customerMap.get(customer.getId());
            //如果能get到数据!=null 说明id一样
            if (customerTicket != null) {
                selectList.add(customer);
            }else {
                customerList.add(customer);
            }
        }
        ticket.setSelectCustomerList(selectList);
        for (Customer customer : selectList) {
            int count = customerTicketService.selectByTicketIdAndCustomer(id,customer.getId());
            customer.setSumNum(count);
        }
        ticket.setNotSelectCustomerList(customerList);

        return ticket;
    }

    /**
     * 查询优惠卷列表
     */
    @RequiresPermissions("meeting:ticket:list")
    @GetMapping("list")
    public R list(Ticket ticket) {
        startPage();
        boolean isAdmin = SubjectUtil.hasRole(getRequest(),"manager");
        if (isAdmin){
            Long parkId = currentUserService.getParkId();
            Long tenantId = currentUserService.getTenantId();
            ticket.setParkId(parkId);
//            ticket.setTenantId(tenantId);
        }

        List<Ticket> tickets = ticketService.selectTicketList(ticket);

        return result(tickets);
    }


    /**
     * 新增保存优惠卷
     */
    @RequiresPermissions("meeting:ticket:add")
    @PostMapping("save")
    public R addSave(@RequestBody Ticket ticket) {
        System.out.println(ticket);
        int i = ticketService.insertTicket(ticket);

        CustomerTicket customerTicket = customerTicketService.selectCustomerTicketById(ticket.getId());

        if (customerTicket ==null){
            if (ticket.getType()  == 1) {
                for (TicketCustomerVo ticketCustomerVo : ticket.getTicketCustomerVo()) {
                    for (int j = 0; j < ticketCustomerVo.getSumNum(); j++) {
                        CustomerTicket customerTicket1 = new CustomerTicket();
                        customerTicket1.setTicketId(ticket.getId());
                        customerTicket1.setCustomerId(ticketCustomerVo.getId());
                        customerTicket1.setIsVerification(0);
                        customerTicket1.setType(ticket.getType());
                        customerTicketService.insertCustomerTicket(customerTicket1);
                    }
                }
            }else {
                for (TicketCustomerVo ticketCustomerVo : ticket.getTicketCustomerVo()) {

                    for (int j = 0; j < ticketCustomerVo.getSumNum(); j++) {
                        CustomerTicket customerTicket1 = new CustomerTicket();
                        customerTicket1.setTicketId(ticket.getId());
                        customerTicket1.setCustomerId(ticketCustomerVo.getId());
                        customerTicket1.setIsVerification(0);
                        customerTicket1.setType(ticket.getType());
                        customerTicketService.insertCustomerTicket(customerTicket1);
                    }
                }
            }
        }
        return toAjax(i);
    }

    /**
     * 修改保存优惠卷
     */
    @RequiresPermissions("meeting:ticket:edit")
    @PostMapping("update")
    public R editSave(@RequestBody Ticket ticket) {
//        ticket.get
        int i = ticketService.updateTicket(ticket);
        Assert.isTrue(i == 1, "修改失败");
        //修改企业和优惠卷数据  如果类型是 抵用卷，循环添加，如果是优惠卷，添加一条

        CustomerTicket customerTicket = customerTicketService.selectCustomerTicketById(ticket.getId());
        if (customerTicket ==null){
            if (ticket.getType()  == 1) {
                if (CollUtil.isNotEmpty(ticket.getTicketCustomerVo())){

                    List<CustomerTicket> customers = customerTicketService.selectCustomerByTicketId(ticket.getId());
                    List<Long> collect1 = customers.stream().map(CustomerTicket::getCustomerId).collect(toList());

                    List<TicketCustomerVo> ticketCustomerVo1 = ticket.getTicketCustomerVo();

                    List<Long> collect3 = ticketCustomerVo1.stream().map(TicketCustomerVo::getId).collect(toList());


                    List<Long> collect2 = collect1.stream().filter(item -> !collect3.contains(item)).collect(toList());
                    System.out.println(collect2);

                    for (Long aLong : collect2) {
                        customerTicketService.deleteCustomerTicketByTicketIdAndCustomer(ticket.getId(),aLong);

                    }



                    for (TicketCustomerVo ticketCustomerVo : ticket.getTicketCustomerVo()) {
                        //查询出所有的 id
                        CustomerTicket customerTicket2 = new CustomerTicket();
                        customerTicket2.setTicketId(ticket.getId());
                        customerTicket2.setCustomerId(ticketCustomerVo.getId());
                        customerTicket2.setIsVerification(0);
                        List<CustomerTicket> customerTickets = customerTicketService.selectCustomerTicketList(customerTicket2);
                        List<Long> collect = customerTickets.stream().map(CustomerTicket::getId).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(collect)){
                            String ids = CollUtil.join(collect, ",");
                            int i1 = customerTicketService.deleteCustomerTicketByIds(ids);
                        }
                        for (int j = 0; j < ticketCustomerVo.getSumNum(); j++) {
                            CustomerTicket customerTicket1 = new CustomerTicket();
                            customerTicket1.setTicketId(ticket.getId());
                            customerTicket1.setCustomerId(ticketCustomerVo.getId());
                            customerTicket1.setIsVerification(0);
                            customerTicket1.setType(ticket.getType());
                            customerTicketService.insertCustomerTicket(customerTicket1);
                        }
                    }
                }else {
                    customerTicketService.deleteCustomerTicketByTicketId(ticket.getId());
                }

            }else {
                if (ticket.getTicketCustomerVo()!=null){
                    for (TicketCustomerVo ticketCustomerVo : ticket.getTicketCustomerVo()) {
                        for (int j = 0; j < ticketCustomerVo.getSumNum(); j++) {
                            CustomerTicket customerTicket1 = new CustomerTicket();
                            customerTicket1.setTicketId(ticket.getId());
                            customerTicket1.setCustomerId(ticketCustomerVo.getId());
                            customerTicket1.setIsVerification(0);
                            customerTicket1.setType(ticket.getType());
                            customerTicketService.insertCustomerTicket(customerTicket1);
                        }

                    }
                }


            }
            
        }
        return toAjax(i);
    }

    /**
     * 删除优惠卷
     */
    @RequiresPermissions("meeting:ticket:remove")
    @PostMapping("remove")
    public R remove(String ids) {
        int i = ticketService.deleteTicketByIds(ids);

        String[] split = ids.split(",");
        for (String id : split) {

            List<CustomerTicket> customerTickets = customerTicketService.selectCustomerTicketByTicketId(Long.valueOf(id));
            if (CollUtil.isNotEmpty(customerTickets)){
                for (CustomerTicket customerTicket : customerTickets) {
                    if (null !=customerTicket){
                        customerTicketService.deleteCustomerTicketById(customerTicket.getId());

                    }
                }
            }
        }
        return toAjax(i);
    }


    /**
     *  企业名称，企业负责人，联系电话，优惠劵数量
     */

    @Ignore
    @GetMapping("getTicketByCompany")
    public R getTicketByCompany(Customer customer) {
        startPage();

        List<Customer> customers = customerService.selectCustomerList(customer);

        return result(customers);
    }



}
