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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.SysUser;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
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.LocalDate;
import java.util.Map;


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

    @Autowired
    ITCustomerBigService customerBigService;
    @Autowired
    ITNewsService newsService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITDiscountMallService discountMallService;
    @Autowired
    ITDiscountPayService discountPayService;
    @Autowired
    ITCustomerTemplateService customerTemplateService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ITDiscountRecordService receiveRecordService;

    /**
     * 获取我的大客户列表
     * @return
     */
    @RequestMapping("/get/list")
    public APIEntity getList(){
        SysUser user=getLoginUser();
        //平台账号，默认获取所有大客户
        if(user.getFranId().equals(1)){
            return APIEntity.success(customerBigService.list());
        }
        return APIEntity.success(customerBigService.list(new QueryWrapper<TCustomerBig>().eq("fran_id",user.getFranId())));
    }

    /**
     * 新增和修改还表单提交
     * @return
     */
    @InitLog(value = "增改大客户信息",action = "增改")
    @PostMapping("/model/form")
    public APIEntity modelForm(@RequestParam Map<String,String> params){
        log.info("@@@@@@@@@@@@@@@@@@@@@@走这里了吗@@@@@@@@@@@@@@@@@@@@@@@@");
        TCustomerBig customerBig=crateEntityByMap(params);
        log.error("##############大商户的信息：{}",customerBig);
        if(StringUtils.isBlank(customerBig.getBigNum())){
            params.put("bigNum",NumberUtils.getRandom(6));
        }else {
            params.put("bigNum",params.get("bigNum"));
        }
        if(customerBig.insertOrUpdate()){
            return APIEntity.success();
        }
        return APIEntity.fail("系统繁忙，请稍后再试！");
    }

    /**
     * 从黑名单恢复
     * @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 = "客户认证商户信息审核通过")
    @GetMapping("/customerBig/adopt")
    public APIEntity getAdopt(Integer id) throws Exception {
        TCustomerBig customerBig =customerBigService.getById(id);
        customerBig.setBigStatus("已签约");
        customerBig.setBigSignStartDate(LocalDate.now());
        customerBig.setBigSidnEndDate(LocalDate.now().plusYears(20));
        if(customerBig.updateById()){
            TCustomer customer = customerService.getById(customerBig.getCustomerId());
            customer.setDoorPhoto(customerBig.getStorePhoto());
            customer.setLicensePhoto(customerBig.getBigLicense());
            customer.setIdPhoto(customerBig.getIdPhoto());
            customer.setBigId(customerBig.getBigId());
            customer.setCustomerType("商家用户");
            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(),customer.getCustomerId());
            customer.updateById();
            //receiveRecordService.applyByBigCus(customerBig);
            newsService.pushCustomerMsg1(customer.getCustomerId(), "商家入驻成功通知", "尊敬的客户您好,您提交的商户入驻信息已审核成功，已为您开通半年8.0折优惠卷");
        }else {
            return APIEntity.fail("审核通过失败！");
        }
        return APIEntity.success();
    }
    /**
     * 客户认证商户信息审核驳回
     * @return
     */
    @InitLog(value = "客户认证商户信息审核驳回")
    @PostMapping("/customerBig/reject")
    public APIEntity getReject(Integer id,String desc){
        TCustomerBig customerBig =customerBigService.getById(id);
        customerBig.setBigStatus("已驳回");
        customerBig.setBigRmk(desc);
        if(customerBig.updateById()){
            customerService.updateById(customerService.getById(customerBig.getCustomerId()).setBigId(0));
            newsService.pushCustomerMsg1(customerBig.getCustomerId(),"商家入驻失败通知","尊敬的客户：{0}您好，您提交的材料审核未通过。原因：{1}。"+
                    "如有问题，可搜索关注微信公众号：同城急送  使用对话框进行咨询。",customerBig.getBigName(),desc);
            return  APIEntity.success();
        }
        return  APIEntity.fail("系统繁忙，请稍后再试！");
    }


    /**
     * 根据营销骑手名字和模板名字搜索
     * @return
     */
    @GetMapping("/search/key")
    public APIEntity getSearchByName(String key){
        QueryWrapper<TCustomerTemplate> qu=getFranQueryWrapper();
        TCourier courier = courierService.getOne(new QueryWrapper<TCourier>().eq("courier_phone",key));
        if(courier==null){
            qu.eq("template_status","使用中")
              .eq("template_name",key)
              .groupBy("template_code")
              .orderByDesc("config_sort");
        }else {
            qu.eq("template_status","使用中")
              .eq("create_user",courier.getCourierId())
              .groupBy("template_code")
              .orderByDesc("config_sort");
        }
        return APIEntity.success(customerTemplateService.list(qu));
    }


    /**
     * 绑定提交
     * @param bigId
     * @param templateId
     * @return
     */
    @InitLog("绑定提交")
    @GetMapping("/bind/submit")
    public APIEntity exceptionAssign(Integer bigId, Integer templateId) {
        TCustomerBig customerBig = customerBigService.getById(bigId);
        if(customerBig == null){
            return APIEntity.fail("当前商户信息不存在，请刷新");
        }
        if(customerBigService.list(new QueryWrapper<TCustomerBig>().eq("template_id",templateId)).size()>0){
            return APIEntity.fail("选择的模板已绑定别的商户，请重新选择");
        }
        TCustomer customer  = customerService.getById(customerBig.getCustomerId());
        if(customer == null){
            return APIEntity.fail("需要绑定的账户信息不存在");
        }
        TCustomerTemplate customerTemplate = customerTemplateService.getById(templateId);
        if(customerTemplate == null){
            return APIEntity.fail("当前计费模板不存在，请刷新");
        }
        //营销骑手、计费模板与商户绑定
        customerBig.setCourierId(customerTemplate.getCreateUser());
        customerBig.setTemplateId(customerTemplate.getTemplateId().toString());
        customerBig.setBigStatus("已签约");
        customerBig.updateById();
        //商户、计费模板与客户账号绑定
        customer.setTemplateId(customerTemplate.getTemplateId().toString());
        customer.setBigId(customerBig.getBigId());
        customer.updateById();
        newsService.pushCourierMsg1(customerBig.getCustomerId(),"绑定成功通知","尊敬的客户您好，您提交的商户信息已绑定。如有问题，可搜索关注微信公众号：同城急送  使用对话框进行咨询。");
        return APIEntity.success();
    }

}
