package com.ghy.web.controller.customer;

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

import com.ghy.common.enums.PlaceStatus;
import com.ghy.common.utils.CacheUtils;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.ObjectUtils;
import com.ghy.customer.domain.Customer;
import com.ghy.customer.service.CustomerService;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.domain.WorkerBank;
import com.ghy.worker.domain.WorkerCertification;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ghy.common.annotation.Log;
import com.ghy.common.enums.BusinessType;
import com.ghy.customer.domain.CustomerPlace;
import com.ghy.customer.service.ICustomerPlaceService;
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 2022-08-11
 */
@Controller
@RequestMapping("/customer/place")
public class CustomerPlaceController extends BaseController
{
    private String prefix = "customer/place";

    @Autowired
    private ICustomerPlaceService customerPlaceService;

    @Autowired
    private CustomerService customerService;

    @RequiresPermissions("customer:place:view")
    @GetMapping()
    public String place()
    {
        return prefix + "/place";
    }

    /**
     * 查询分销申请列表
     */
    @RequiresPermissions("customer:place:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CustomerPlace customerPlace)
    {
        startPage();
        List<CustomerPlace> list = customerPlaceService.selectCustomerPlaceList(customerPlace);
        return getDataTable(list);
    }

    @PostMapping("/app/myCustomerPlace")
    @ResponseBody
    public AjaxResult myCustomerPlace(@RequestBody CustomerPlace customerPlace){
        Customer param = new Customer();
        param.setCustomerPlace(customerPlace.getCustomerId());
        param.setPlaceStatus(1);
        List<Customer> customerList = customerService.getCustomerList(param);
        List<Long> ids = customerList.stream().map(Customer::getCustomerId).collect(Collectors.toList());
        if(!CollectionUtils.isNotEmpty(ids)){
            return AjaxResult.success(new ArrayList<>());
        }
        return AjaxResult.success(customerPlaceService.getByCustomerIds(ids));
    }

    /**
     * App查询分销申请列表
     */
    @PostMapping("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestBody CustomerPlace customerPlace)
    {
        startPage();
        List<CustomerPlace> list = customerPlaceService.selectCustomerPlaceList(customerPlace);
        return getDataTable(list);
    }


    /**
     * 导出分销申请列表
     */
    @RequiresPermissions("customer:place:export")
    @Log(title = "分销申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CustomerPlace customerPlace)
    {
        List<CustomerPlace> list = customerPlaceService.selectCustomerPlaceList(customerPlace);
        ExcelUtil<CustomerPlace> util = new ExcelUtil<CustomerPlace>(CustomerPlace.class);
        return util.exportExcel(list, "分销申请数据");
    }

    /**
     * 新增分销申请
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存分销申请
     */
    @RequiresPermissions("customer:place:add")
    @Log(title = "分销申请", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CustomerPlace customerPlace)
    {
        return toAjax(customerPlaceService.insertCustomerPlace(customerPlace));
    }

    /**
     * 新增保存分销申请
     */
    @Log(title = "分销申请", businessType = BusinessType.INSERT)
    @PostMapping("/app/add")
    @ResponseBody
    public AjaxResult appAdd(@RequestBody CustomerPlace customerPlace)
    {
        if (CacheUtils.get(customerPlace.getPhone()) == null){
            return AjaxResult.error("验证码无效!");
        }
        // 验证码校验正确
        if(CacheUtils.get(customerPlace.getPhone()).toString().equals(customerPlace.getCode())){
            int result = customerPlaceService.insertCustomerPlace(customerPlace);

            int updateStatusResult = 1;
            if (customerPlace.getType().equals("distribution")) {
                Customer params = new Customer();
                params.setCustomerId(customerPlace.getCustomerId());
                params.setPlaceStatus(PlaceStatus.PLACE_APPLYING.getCode());
                updateStatusResult = customerService.updateCustomer(params);
            }
            if(result > 0 && updateStatusResult > 0){
                CacheUtils.remove(customerPlace.getPhone());
                return AjaxResult.success("申请成功!");
            }else {
                return AjaxResult.error("申请失败!");
            }
        }else {
            return AjaxResult.error("验证码错误!");
        }
    }

    /**
     * 修改分销申请
     */
    @RequiresPermissions("customer:place:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        CustomerPlace customerPlace = customerPlaceService.selectCustomerPlaceById(id);
        mmap.put("customerPlace", customerPlace);
        return prefix + "/edit";
    }

    /**
     * 修改保存分销申请
     */
    @RequiresPermissions("customer:place:edit")
    @Log(title = "分销申请", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CustomerPlace customerPlace)
    {
        return toAjax(customerPlaceService.updateCustomerPlace(customerPlace));
    }

    @PostMapping("/app/edit")
    @ResponseBody
    public AjaxResult appEdit(@RequestBody CustomerPlace customerPlace)
    {
        return toAjax(customerPlaceService.updateCustomerPlace(customerPlace));
    }

    /**
     * 删除分销申请
     */
    @RequiresPermissions("customer:place:remove")
    @Log(title = "分销申请", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(customerPlaceService.deleteCustomerPlaceByIds(ids));
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(String ids,Integer status){
        try {
            int result = customerPlaceService.changeStatus(ids, status);
            if(result > 0){
                String [] idArray = ids.split(",");
                for (String id : idArray){
                    CustomerPlace customerPlace = customerPlaceService.selectCustomerPlaceById(id);
                    Customer customer = new Customer();
                    customer.setCustomerId(customerPlace.getCustomerId());
                    customer.setPlaceStatus(status);
                    customerService.updateCustomer(customer);
                }
                return AjaxResult.success("操作成功!");
            }else {
                return AjaxResult.warn("操作失败!");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error("操作失败!");
        }
    }
}
