package com.ghy.web.controller.customer;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.ghy.common.exception.base.BaseException;
import com.ghy.customer.domain.Customer;
import com.ghy.customer.domain.CustomerSelection;
import com.ghy.customer.service.CustomerService;
import com.ghy.customer.service.ICustomerSelectionService;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.service.WorkerService;
import com.huifu.adapay.core.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.ghy.common.annotation.Log;
import com.ghy.common.enums.BusinessType;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.utils.poi.ExcelUtil;
import com.ghy.common.core.page.TableDataInfo;

/**
 * 消费者选品Controller
 *
 * @author clunt
 * @date 2023-01-15
 */
@Controller
@RequestMapping("/customer/selection")
public class CustomerSelectionController extends BaseController
{
    private String prefix = "customer/selection";

    @Autowired
    private ICustomerSelectionService customerSelectionService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private WorkerService workerService;

    @GetMapping()
    public String selection()
    {
        return prefix + "/selection";
    }

    /**
     * 查询消费者选品列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CustomerSelection customerSelection)
    {
        startPage();
        List<CustomerSelection> list = customerSelectionService.selectCustomerSelectionList(customerSelection);
        return getDataTable(list);
    }

    /**
     * 查询消费者选品列表
     */
    @PostMapping("/listNoPage")
    @ResponseBody
    public AjaxResult listNoPage(@RequestBody CustomerSelection customerSelection)
    {
        // 判断是否有上级，有上级则取上级的 -- 没有则就是自身
        Customer customer = customerService.selectByCustomerId(customerSelection.getCustomerId());
        if(customer.getPlaceStatus() != 2 && customer.getCustomerPlace() != null){
            customerSelection.setCustomerId(customer.getCustomerPlace());
        }
        List<CustomerSelection> list = customerSelectionService.selectCustomerSelectionList(customerSelection);
        return AjaxResult.success(list.stream().map(CustomerSelection::getDeptCategoryId).collect(Collectors.toList()));
    }

    /**
     * App查询消费者选品列表
     */
    @PostMapping("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestBody CustomerSelection customerSelection)
    {
        startPage();
        List<CustomerSelection> list = customerSelectionService.selectCustomerSelectionList(customerSelection);
        return getDataTable(list);
    }


    /**
     * 导出消费者选品列表
     */
    @Log(title = "消费者选品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CustomerSelection customerSelection)
    {
        List<CustomerSelection> list = customerSelectionService.selectCustomerSelectionList(customerSelection);
        ExcelUtil<CustomerSelection> util = new ExcelUtil<CustomerSelection>(CustomerSelection.class);
        return util.exportExcel(list, "消费者选品数据");
    }

    /**
     * 新增消费者选品
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存消费者选品
     */
    @Log(title = "消费者选品", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CustomerSelection customerSelection)
    {
        return toAjax(customerSelectionService.insertCustomerSelection(customerSelection));
    }

    /**
     * 新增保存消费者选品
     */
    @PostMapping("/app/add")
    @ResponseBody
    public AjaxResult appAddSave(@RequestBody CustomerSelection customerSelection)
    {
        try {
            Customer customer = customerService.selectByCustomerId(customerSelection.getCustomerId());
            if(StringUtil.isEmpty(customer.getPhone())){
                throw new BaseException("手机号为空，无法关联师傅!");
            }
            Worker worker = new Worker();
            worker.setPhone(customer.getPhone());
            Long workId;
            List<Worker> workList = workerService.getWorkList(worker);
            if(CollectionUtils.isEmpty(workList)){
                throw new BaseException("消费者没有对应的师傅，无需配置选品!");
            }else {
                workId = workList.get(0).getWorkerId();
            }
            // 删除历史的
            CustomerSelection hisParam = new CustomerSelection();
            hisParam.setCustomerId(customerSelection.getCustomerId());
            hisParam.setSelectionType(customerSelection.getSelectionType());
            List<CustomerSelection> hisList = customerSelectionService.selectCustomerSelectionList(hisParam);
            if(!CollectionUtils.isEmpty(hisList)){
                List<String> hisIds = hisList.stream()
                        .filter(customerSelection1 -> Objects.equals(customerSelection1.getType(), customerSelection.getType())).map(CustomerSelection::getId).collect(Collectors.toList());
                StringBuilder ids = new StringBuilder();
                hisIds.forEach(model->{
                    ids.append(model.trim()).append(",");
                });
                if(!StringUtil.isEmpty(ids)&&ids.length()>0){
                    String idString = ids.substring(0, ids.length()-1);
                    customerSelectionService.deleteCustomerSelectionByIds(idString);
                }
            }
            // 判断是否有历史数据 - 有则删除
            customerSelection.getDeptCategoryIds().forEach(selection->{
                customerSelection.setWorkId(workId);
                customerSelection.setDeptCategoryId(selection);
                customerSelectionService.insertCustomerSelection(customerSelection);
            });
            return AjaxResult.success("新增成功");
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 修改消费者选品
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        CustomerSelection customerSelection = customerSelectionService.selectCustomerSelectionById(id);
        mmap.put("customerSelection", customerSelection);
        return prefix + "/edit";
    }

    /**
     * 修改保存消费者选品
     */
    @Log(title = "消费者选品", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CustomerSelection customerSelection)
    {
        return toAjax(customerSelectionService.updateCustomerSelection(customerSelection));
    }

    /**
     * 删除消费者选品
     */
    @Log(title = "消费者选品", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(customerSelectionService.deleteCustomerSelectionByIds(ids));
    }
}
