package com.zfire.mall.manager.controller.customer;

import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zfire.mall.manager.annotation.ZfireList;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.invoice.InvoiceRequestJson;
import com.zfire.mall.manager.bean.k3.K3CustomerBean;
import com.zfire.mall.manager.bean.listV2.ComListVO;
import com.zfire.mall.manager.bean.listV2.K3CustomerJiaXianVO;
import com.zfire.mall.manager.bean.listV2.K3CustomerVO;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.helper.ResponseHelper;
import com.zfire.mall.manager.logic.k3.K3CustomerLogic;
import com.zfire.mall.manager.plus.entity.InvoiceApplication;
import com.zfire.mall.manager.plus.entity.KingDeeCustomer;
import com.zfire.mall.manager.utils.CommonUtils;
import com.zfire.mall.manager.utils.excel.ExcelUtils;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "经销商API", tags ={"经销商API"} )
@RequestMapping(value = "/customer", produces = "application/json; charset=utf-8")
public class CustomerController {

    @Autowired
    K3CustomerLogic k3CustomerLogic;
    @Autowired
    RedisLockRegistry redisLockRegistry;


    @ZfireList
    @PostMapping("/list/v2")
    @ApiOperation(value = "经销商列表V2")
    public ResponseHelper<K3CustomerVO> listV2(
            @RequestBody ZfireParamBean zfireParamBean
    ){
        IPage<K3CustomerVO> k3CustomerVOIPage = k3CustomerLogic.listV2(zfireParamBean);
        return ResponseHelper.success(k3CustomerVOIPage, new TypeReference<K3CustomerVO>() {});
    }

    @PostMapping("/user/export/v2")
    @ApiOperation("经销商列表V2-导出")
    public void listExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<K3CustomerVO> stockBeanIPage = k3CustomerLogic.listV2(zfireParam);
        //3.导出
        FieldUtils.exportData(stockBeanIPage.getRecords(),zfireParam.getExportFields(),request,response);
    }


    @PostMapping("/user/export/jiaXianV2")
    @ApiOperation("经销商列表自提物流V2-导出")
    public void listExportJiaXian(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<K3CustomerJiaXianVO> stockBeanIPage = k3CustomerLogic.jiaXianV2(zfireParam);
        //3.导出
        FieldUtils.exportData(stockBeanIPage.getRecords(),zfireParam.getExportFields(),request,response);
    }



    @ApiOperation(value = "经销商列表")
    @GetMapping("/list")
    public ResponseHelper<IPage<KingDeeCustomer>> list(
            @ApiParam(required = false, value = "经销商名称/经销商编号/id") @RequestParam(required = false) String keyword,
            @ApiParam(required = false, value = "地区") @RequestParam(required = false) String region,
            @ApiParam(required = false, value = "KING 金蝶经销商  JIAXIAN嘉贤二级经销商 GONGCHENG 商用经销商") @RequestParam(required = false) String jiaxianType,
            @ApiParam(required = false, value = "未被绑定的经销商列表 true=已绑定 false=未绑定") @RequestParam(required = false) Boolean bindUser,
            @ApiParam(required = false, value = "是否为集团客户 true=是 false=否") @RequestParam(required = false) Boolean isGroupCompany,
            @ApiParam(required = false, value = "GZ=广州  FS=佛山") @RequestParam(required = false) String websitNumber,
            @ApiParam(required = false, value = "和bindUser一起传，指定不需要过滤哪个帐号的经销商") @RequestParam(required = false) String adminUserId,
            @ApiParam(value = "页号",required = true)@RequestParam Integer pageNum,
            @ApiParam(value = "页大小",required = true)@RequestParam Integer pageSize
    ) throws Exception {
        IPage<KingDeeCustomer> list = k3CustomerLogic.list(keyword, region,bindUser,isGroupCompany,websitNumber,adminUserId,pageNum, pageSize,jiaxianType);
        return ResponseHelper.success(list);
    }

    @ApiOperation(value = "经销商列表-导出")
    @GetMapping("/export")
    public void export(
            @ApiParam(required = false, value = "搜索内容") @RequestParam(required = false) String keyword,
            @ApiParam(required = false, value = "地区") @RequestParam(required = false) String region,
            @ApiParam(required = false, value = "KING 金蝶经销商  JIAXIAN嘉贤二级经销商 GONGCHENG 商用经销商") @RequestParam(required = false) String jiaxianType,
            @ApiParam(required = false, value = "未被绑定的经销商列表 true=已绑定 false=未绑定") @RequestParam(required = false) Boolean bindUser,
            @ApiParam(required = false, value = "是否为集团客户 true=是 false=否") @RequestParam(required = false) Boolean isGroupCompany,
            HttpServletRequest request, HttpServletResponse response
    ) throws Exception {
        IPage<KingDeeCustomer> list = k3CustomerLogic.list(keyword, region,bindUser,isGroupCompany,null,null,1, -1,jiaxianType);
        ExcelData excelData = k3CustomerLogic.export(list.getRecords());
        ExcelUtils.exportExcel(request,response,"经销商列表.xlsx",excelData);
    }



    @ApiOperation(value = "经销商详情")
    @PostMapping("/detail")
    public ResponseHelper<K3CustomerBean> detail(
            @ApiParam(required = true, value = "id") @RequestParam(required = true) String id
    ) throws Exception {
        K3CustomerBean detail = k3CustomerLogic.detail(id);
        return ResponseHelper.success(detail);
    }


    @ApiOperation(value = "新增经销商")
    @PostMapping("/add")
    public ResponseHelper add(
            @RequestBody KingDeeCustomer kingDeeCustomer
    ) throws Exception {
        k3CustomerLogic.add(kingDeeCustomer);
        return ResponseHelper.success();
    }

    @ApiOperation(value = "修改经销商")
    @PostMapping("/updateCustomer")
    public ResponseHelper updateCustomer(
            @RequestBody KingDeeCustomer kingDeeCustomer
    ) throws Exception {
        k3CustomerLogic.updateCustomer(kingDeeCustomer);
        return ResponseHelper.success();
    }


    @PostMapping("/downloadCustomer")
    @ApiOperation("下载经销商导入模板")
    public void download(
            HttpServletResponse response
    ) throws IOException {
        CommonUtils.downloadFile("经销商导入.xlsx",response);
    }


    @PostMapping("/importCustomer")
    @ApiOperation("导入经销商")
    public ResponseHelper importData(
            @RequestPart("file") MultipartFile file
    ) throws IOException {
        List<Object> objects = ExcelUtils.importExcel(file);
        k3CustomerLogic.importData(objects);
        return ResponseHelper.success();
    }



    @ApiOperation(value = "查询同个集团的经销商")
    @GetMapping("/group/list")
    public ResponseHelper<IPage<KingDeeCustomer>> groupCompany(
    ) throws Exception {
        List<KingDeeCustomer> kingDeeCustomers = k3CustomerLogic.groupCompanyList();
        return ResponseHelper.success(kingDeeCustomers);
    }


    @PostMapping("/update")
    @ApiOperation("基础上设置前置仓或商家仓")
    public ResponseHelper update(@ApiParam(required = true, value = "经销商id") @RequestParam(required = true) String id,
                                 @ApiParam(required = true, value = "true前置仓 false商家仓") @RequestParam(required = true) Boolean isFront) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_CUSTOMER + id);
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            k3CustomerLogic.update(id,isFront);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }


    @PostMapping("/import")
    @ApiOperation("经销商导入提货类别")
    public ResponseHelper importLimit(
            MultipartFile file
    ) throws IOException {
        List<Object> objects = ExcelUtils.importExcel(file);
        k3CustomerLogic.importCustomer(objects);
        return ResponseHelper.success();
    }


    @PostMapping("/updatePick")
    @ApiOperation("基础上设置自提和物流")
    public ResponseHelper updatePick(@ApiParam(required = true, value = "经销商id") @RequestParam(required = true) String id,
                                 @ApiParam(required = true, value = "是否物流") @RequestParam(required = true) Boolean isFront,
                                 @ApiParam(required = true, value = "是否自提") @RequestParam(required = true) Boolean isPick,
                                 @ApiParam(required = false, value = "是否自提品类id") @RequestParam(required = false) List<String> pickCategory,
                                     @ApiParam(required = false, value = "是否物流品类id") @RequestParam(required = false) List<String> frontCategory) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_CUSTOMER + id);
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            k3CustomerLogic.updatePick(id,isFront,isPick,pickCategory,frontCategory);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }


    @PostMapping("/updateSystem")
    @ApiOperation("经销商绑定售后系统")
    public ResponseHelper updateSystem(@ApiParam(required = true, value = "经销商id") @RequestParam(required = true) String id,
                                     @ApiParam(required = true, value = "销售编号") @RequestParam(required = true) String afterNumber
                              ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_CUSTOMER + id);
        try {
            if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                throw new RemoteServiceException("系统繁忙，请稍后再试");
            }
            k3CustomerLogic.updateSystem(id,afterNumber);
        } finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

}
