package com.bohuikeji.delivery.backstage.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.SerializationUtils;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountMall;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.annotation.InitLog;
import com.bohuikeji.frame.module.admin.base.ControllerBase;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 客户信息
 * @author 10552
 */
@Controller
@ResponseBody
@RequestMapping("/customer")
@RequiredArgsConstructor
@Slf4j
public class CustomerController extends ControllerBase {


    final ITCustomerService customerService;
    final ITConfigService configService;
    final ITCustomerTemplateService templateService;
    final ITNewsService newsService;
    final ITDiscountMallService discountMallService;
    final ITDiscountPayService discountPayService;

    /**
     * 拉入黑名单
     * @param ids
     * @return
     */
    @RequestMapping("/blacklist")
    @InitLog("客户拉黑")
    public APIEntity blacklist(Integer ids[]){
        for (Integer id: ids) {
            TCustomer customer = new TCustomer();
            customer.setCustomerId(id);
            customer.setCustomerStatus("已拉黑");
            customerService.updateById(customer);
        }
        return APIEntity.success();
    }

    /**
     * 从黑名单恢复
     * @return
     */
    @InitLog("客户恢复")
    @RequestMapping("/recovery")
    public APIEntity recovery(Integer ids[]){
        for (Integer id: ids) {
            TCustomer customer = new TCustomer();
            customer.setCustomerId(id);
            customer.setCustomerStatus("已激活");
            customerService.updateById(customer);
        }
        return APIEntity.success();
    }

    /**
     * 派送员认证审核通过
     * @param id
     */
   /* @InitLog(value = "商家入审核通过")
    @RequestMapping("/business/adopt")
    public APIEntity getEditStatus(Integer id) throws Exception {
        TCustomer customer=customerService.getById(id);
        customer.setCustomerType("商家用户");
        customer.setCustomerStatus("已激活");
        TDiscountMall discountMall = discountMallService.getOne(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("dis_type","会员卡").eq("receive_method","后台发放").eq("dis_name","半年VIP"));
        discountPayService.handleDiscountService(null,null,null,discountMall.getDisId(),id);
        customer.updateById();
        newsService.pushCustomerMsg1(customer.getCustomerId(), "商家入驻成功通知", "尊敬的客户您好,您提交的商户入驻信息已审核成功，已为您开通半年8.0折优惠卷");
        return APIEntity.success();
    }*/

    /**
     * 商家入驻申请驳回
     * @return
     */
    /*@PostMapping("/business/getReject")
    public APIEntity getReject(Integer id,String desc){
        TCustomer customer=customerService.getById(id);
        customer.setCustomerStatus("已激活");
        customer.setIdPhoto("");
        customer.setDoorPhoto("");
        customer.setLicensePhoto("");
        customer.updateById();
        newsService.pushCustomerMsg1(customer.getCustomerId(),"商家入驻失败通知","尊敬的客户：{0}您好，您提交的材料审核未通过。原因：{1}。"+
                "如有问题，可搜索关注微信公众号：同城急送  使用对话框进行咨询。",customer.getCustomerName(),desc);
        return  APIEntity.success();
    }*/


    /**
     * 搜索用户
     * @param key
     * @return
     */
    @GetMapping("/search/list")
    public APIEntity searchCustormerList(String key){
        return APIEntity.success(customerService.list(new QueryWrapper<TCustomer>().likeRight("customer_name",key).or().likeRight("customer_phone",key)));

    }
    @GetMapping("/get/id")
    public APIEntity getCustomerId(Integer id){
        return APIEntity.success(customerService.getById(id));

    }

    /**
     * 新增和修改客户模板
     * @return
     */
    @InitLog(value = "新增/修改客户计费模板",action = "增改")
    @PostMapping("/template/model/form")
    public APIEntity modelForm(@RequestParam Map<String,String> params){
        SysUser loginUser=getLoginUser();
        params.forEach((key,val)->{
            log.info("KEY={}",key);
            log.info("VAL={}",val);
        });
        TCustomerTemplate template=crateEntityByMap(params);
        log.info("初始化实体之后={}",template);
        if(template != null){
            TCustomerTemplate tCustomerTemplate = templateService.getById(template.getTemplateId());
            List<TCustomerTemplate> templates=templateService.list(new QueryWrapper<TCustomerTemplate>().eq("template_code",tCustomerTemplate.getTemplateCode()));
            log.info("@@@@@@@@@@@@@@@@@@@@@@@@@:{}",templates.size());
            for (TCustomerTemplate customerTemplate : templates){
                customerTemplate.setTemplateName(template.getTemplateName());
                customerTemplate.setTemplateDesc(template.getTemplateDesc());
                templateService.updateById(customerTemplate);
            }
            return APIEntity.success("修改成功");
        }
        List<TConfig> configList=configService.list(
                new QueryWrapper<TConfig>()
                        .eq("fran_id",template.getFranId())
                        .in("config_group","cargo_type","car_type","car_type_xshc","car_type_mbc","car_type_ddc","service_type","cargo_value","payment_method"));
        List<TConfig> superList=configService.list(new QueryWrapper<TConfig>()
                .eq("fran_id",template.getFranId())
                .in("config_key","cargo_type","car_type","service_type","cargo_value","payment_method"));
        configList.addAll(superList);
        List<TCustomerTemplate> templates=new ArrayList<>(configList.size());
        configList.forEach(config->{
            TCustomerTemplate cloneTemplate=SerializationUtils.clone(template);
            cloneTemplate.setConfigGroup(config.getConfigGroup());
            cloneTemplate.setConfigValue(config.getConfigValue());
            cloneTemplate.setConfigId(config.getId());
            cloneTemplate.setConfigName(config.getConfigName());
            cloneTemplate.setConfigKey(config.getConfigKey());
            cloneTemplate.setDeletePolicy(config.getDeletePolicy());
            cloneTemplate.setConfigSort(config.getConfigSort());
            cloneTemplate.setFranId(config.getFranId());
            if(loginUser.getRoleId().equals(7)){
                cloneTemplate.setCreateUser(loginUser.getUserId());
                cloneTemplate.setCreateType("加盟商");
            }else {
                cloneTemplate.setCreateUser(loginUser.getUserId());
                cloneTemplate.setCreateType("平台");
            }
            templates.add(cloneTemplate);
        });
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@:{}",templates);
        return APIEntity.success(templateService.saveBatch(templates));
    }

    /**
     * 新增和修改客户模板
     * @return
     */
    @InitLog(value = "删除客户计费模板",action = "删除")
    @PostMapping("/template/config/del/id")
    public APIEntity delTemplate(Integer id){
        log.info("删除模板的ID:{}",id);
        TCustomerTemplate customerTemplate = templateService.getById(id);
        log.info("删除模板的详细信息:{}",customerTemplate);
        if(customerTemplate == null){
            return APIEntity.fail("该计费模板不存在");
        }
        List<TCustomerTemplate> templates= templateService.list(new QueryWrapper<TCustomerTemplate>().eq("template_code",customerTemplate.getTemplateCode()));
        log.info("删除模板的数量:{}",templates.size());
        if(templates.size()<1){
            return APIEntity.fail("该计费模板不存在");
        }
        if(customerService.list(new QueryWrapper<TCustomer>().eq("template_id",customerTemplate.getTemplateId())).size()>0){
            return APIEntity.fail("该计费模板绑定中请解绑后删除！");
        }
        templates.forEach(templateService::removeById);
        return APIEntity.success();
    }
}
