package com.jkcredit.invoice.controller.localBussiness;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jkcredit.invoice.annotation.LoginRequired;
import com.jkcredit.invoice.model.entity.customer.Customer;
import com.jkcredit.invoice.model.entity.CustomerRecharge;
import com.jkcredit.invoice.model.entity.customer.CustomerRec;
import com.jkcredit.invoice.model.entity.manager.Param;
import com.jkcredit.invoice.service.customer.CustomerRecService;
import com.jkcredit.invoice.service.customer.CustomerRechargeService;
import com.jkcredit.invoice.service.customer.CustomerService;
import com.jkcredit.invoice.service.lowerService.CustomeLowerService;
import com.jkcredit.invoice.service.manager.ParamService;
import com.jkcredit.invoice.util.DateUtil;
import com.jkcredit.invoice.util.RespR;
import com.jkcredit.invoice.util.WordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 客户操作
 */
@Api(tags = "客户操作")
@RestController
@RequestMapping(value = {"/customer"})
public class CustomerController {
    @Autowired
    CustomerService customerService;
    @Autowired
    CustomerRechargeService customerRechargeService;

    @Autowired
    CustomeLowerService lowerService;

    @Autowired
    CustomerRecService customerRecService;


    @Autowired
    private ParamService paramService;
    /**
     * 分页查询客户
     *
     * @param page    参数集
     * @return 用户集合
     */
    @PostMapping("/findCustomer")
    @ApiOperation(value="分页查询客户", notes="分页查询客户")
    @LoginRequired
    public RespR getCustomersByPage(Page page, Customer customer) {

        return new RespR(customerService.findAllCustomers(page, customer));
    }

    /**
     * 分页查询客户
     *
     * @param page    参数集
     * @return 用户集合
     */
    @PostMapping("/findCustomerRecharge")
    @ApiOperation(value="分页查询客户充值信息", notes="分页查询客户充值信息")
    @LoginRequired
    public RespR findCustomerRecharge(Page page, CustomerRecharge customerRecharge) {

        return new RespR(customerRechargeService.findAllCustomerRecharge(page, customerRecharge));
    }

    /**
     * 分页查询客户注册信息
     *
     * @param page    参数集
     * @return 用户集合
     */
    @PostMapping("/findCustomerRecList")
    @ApiOperation(value="分页查询客户注册信息", notes="分页查询客户注册信息")
    @LoginRequired
    public RespR findCustomerRecList(Page page, CustomerRec customerRec) {

        return new RespR(customerRecService.findAllCustomerRec(page, customerRec));
    }
    /**
     * 添加客户
     * @return 用户集合
     */
    @PostMapping("/addCustomer")
    @ApiOperation(value="添加客户", notes="添加客户")
    @LoginRequired
    public RespR addCustomer(@RequestBody  Customer customer) {
        return new RespR(customerService.addCustomers(customer),"客户添加失败，请查看是否重复");
    }
    /**
     * 修改客户状态
     * @return 用户集合
     */
    @PostMapping("/updateCustomer")
    @ApiOperation(value="更新用户", notes="更新用户")
    @LoginRequired
    public RespR updateCustomer(@RequestBody  Customer customer) {

        return new RespR(customerService.updateCustomer(customer));
    }
    /**
     * 修改客户状态
     * @return 用户集合
     */
    @PostMapping("/customeRecStop")
    @ApiOperation(value="停用备案用户", notes="停用备案用户")
    @LoginRequired
    public RespR customeRecStop(@RequestBody  CustomerRec customerRec) {
        customerRec.setRecStatus(4);
        return customerService.updateCustomerRecStatus(customerRec);
    }
    /**
     * 修改客户状态
     * @return 用户集合customerRecAdd
     */
    @PostMapping("/customerRecAdd")
    @ApiOperation(value="手工添加备案信息", notes="手工添加备案信息")
    @LoginRequired
    public RespR customerRecAdd(@RequestBody  CustomerRec customerRec) {
        customerRec.setInterType(3);
        List<CustomerRec> customerRecList = new ArrayList<>();
        customerRecList.add(customerRec);
        return lowerService.customeRec(customerRecList);
    }
    /**
     * 充值
     * @return 用户集合
     */
    @PostMapping("/customRecharge")
    @ApiOperation(value="账号充值", notes="账号充值")
    @LoginRequired
    public RespR customRecharge(@RequestBody CustomerRecharge customerRecharge) {

        return new RespR(customerService.customRecharge(customerRecharge));
    }

    @PostMapping("/customeRec")
    @ApiOperation(value="用户备案确认", notes="用户备案确认")
    @LoginRequired
    public RespR customeRec(@RequestBody CustomerRec customerRec){
        return customerService.customeRec(customerRec);
    }

    @PostMapping("/contractAdd")
    @ApiOperation(value="协议上传确认", notes="协议上传确认")
    @LoginRequired
    public RespR contractAdd(@RequestBody CustomerRec customerRec){
        return customerService.contractAdd(customerRec);
    }
    @GetMapping("/contractDownload")
    @ApiOperation(value="协议下载", notes="协议下载")
    public RespR contractDownload(String customerRecId,HttpServletResponse response){
        CustomerRec customerRec = (CustomerRec) customerService.contractDownload(customerRecId).getData();
        String fileName = customerRec.getContractFileName();
        if(customerRec.getBase64Str()!=null){
            byte [] byteArray = Base64.getDecoder().decode(customerRec.getBase64Str());
            InputStream inputStream = new ByteArrayInputStream(byteArray);

            OutputStream outputStream = null;
            try {
                response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
                outputStream = response.getOutputStream();
                IOUtils.copy(inputStream, outputStream);
                response.flushBuffer();
                return new RespR(true);
            } catch (IOException e) {

            } finally {
                IOUtils.closeQuietly(inputStream);
                IOUtils.closeQuietly(outputStream);
            }
        }

        return new RespR(false);
    }
    @GetMapping("/generateWord")
    @ApiOperation(value="文档下载", notes="文档下载")
    public RespR generateWord(String customerRecId,HttpServletResponse response){
        CustomerRec customerRec = (CustomerRec) customerService.contractDownload(customerRecId).getData();
        String fileName = "合作说明.doc";
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("a", customerRec.getCustomerName());
        dataMap.put("b", customerRec.getCompanyName());
        dataMap.put("c", customerRec.getCompanyReferencenum());
        dataMap.put("d", customerRec.getCompanyAdress());
        dataMap.put("e", customerRec.getCompanyPhone());
        dataMap.put("f", customerRec.getCompanyOpenbank());
        dataMap.put("g", customerRec.getCompanyOpenbankAcc());
        dataMap.put("j", customerRec.getServiceStartTime().substring(0,10));
        dataMap.put("k", customerRec.getServiceEndTime().substring(0,10));
        Calendar now = Calendar.getInstance();
        dataMap.put("l",now.get(Calendar.YEAR)+"");
        dataMap.put("h",(now.get(Calendar.MONTH) + 1) + "");
        dataMap.put("i", now.get(Calendar.DAY_OF_MONTH)+"");
        OutputStream outputStream =null;
        try{
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            WordUtil.ExportSimpleWord(dataMap,"/static/templates/excel/",outputStream);
            response.flushBuffer();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(outputStream);
        }
        return new RespR(false);
    }




    /**
     * 分页查询客户备案预警信息
     *
     * @param page    参数集
     * @return 用户集合
     */
    @PostMapping("/findCustomerRecTimeList")
    @ApiOperation(value="客户备案预警查询", notes="客户备案预警查询")
    @LoginRequired
    public RespR findCustomerRecTimeList(Page page, CustomerRec customerRec) {

        Param param = paramService.getParamsByParamName("CUST_EARLY_WARNING");
        IPage ipage = customerRecService.findAllCustomerRec(page, customerRec);
        List<CustomerRec> lists = ipage.getRecords();
        if(lists.size()>0){
        //遍历删除
        Iterator<CustomerRec> iterator = lists.iterator();
        while (iterator.hasNext()) {
            CustomerRec customerRec1 = iterator.next();
            if (Integer.valueOf(param.getParamValue()) <= (DateUtil.daysBetween(customerRec1.getServiceEndTime(),new Date()))) {
                iterator.remove();//使用迭代器的删除方法删除
            }
          }
        }
        ipage.setTotal(lists.size());
        return new RespR(ipage);
    }





    /**
     * 分页查询余额告警用户
     *
     * @param page    参数集
     * @return 用户集合
     */
    @PostMapping("/findCustomerMoney")
    @ApiOperation(value="分页查询余额告警用户", notes="分页查询余额告警用户")
    @LoginRequired
    public RespR getCustomerMoneysByPage(Page page, Customer customer) {
        Param param = paramService.getParamsByParamName("CUST_MONEY_WARNING");
        IPage ipage = customerService.findAllCustomers(page, customer);
        List<Customer> lists = ipage.getRecords();
        if(lists.size()>0){
            //遍历删除
            Iterator<Customer> iterator = lists.iterator();
            while (iterator.hasNext()) {
                Customer customer1 = iterator.next();
                if (new BigDecimal(Double.valueOf(param.getParamValue())).compareTo(new BigDecimal(customer1.getAccountBalance())) < 0) {
                    iterator.remove();//使用迭代器的删除方法删除
                }
            }
        }
        ipage.setTotal(lists.size());
        return new RespR(ipage);
    }
}
