package common.controller;

import common.model.*;
import common.service.ContractService;
import dic.ContractStatusEnum;
import dic.OperateObjectTypeEnum;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import security.annotation.CurrentAccount;
import util.IPAddrUtil;
import util.NewUserLogThread;
import util.ResultModel;
import util.ValidateUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mxq on 17/12/21.
 * 优先测试账号查询
 */
@Controller
@RequestMapping("{platform}/contract")
public class ContractController {

    private static final Logger logger = LoggerFactory.getLogger(ContractController.class);

    private static final Map<String, String> CONTRACT_STATUS = new HashMap<String, String>() {{
//        put(ContractStatusEnum.WAIT.getKey(), ContractStatusEnum.WAIT.getValue());
//        put(ContractStatusEnum.EXECUTING.getKey(), ContractStatusEnum.EXECUTING.getValue());
//        put(ContractStatusEnum.END.getKey(), ContractStatusEnum.END.getValue());
//        put(ContractStatusEnum.CANCEL.getKey(), ContractStatusEnum.CANCEL.getValue());
//        put(ContractStatusEnum.MONEY_BACK_ALL.getKey(), ContractStatusEnum.MONEY_BACK_ALL.getValue());
//        put(ContractStatusEnum.MONEY_BACK_PART.getKey(), ContractStatusEnum.MONEY_BACK_PART.getValue());
//        put(ContractStatusEnum.MONEY_BACK_NONE.getKey(), ContractStatusEnum.MONEY_BACK_NONE.getValue());
//        put(ContractStatusEnum.DELETE.getKey(), ContractStatusEnum.DELETE.getValue());

        putdata(this,ContractStatusEnum.WAIT);
        putdata(this,ContractStatusEnum.EXECUTING);
        putdata(this,ContractStatusEnum.END);
        putdata(this,ContractStatusEnum.CANCEL);
        putdata(this,ContractStatusEnum.MONEY_BACK_ALL);
        putdata(this,ContractStatusEnum.MONEY_BACK_PART);
        putdata(this,ContractStatusEnum.MONEY_BACK_NONE);
        putdata(this,ContractStatusEnum.MONEY_BACK_FIRST);
        putdata(this,ContractStatusEnum.DELETE);

    }};


    private static  void putdata(Map map,ContractStatusEnum a){
        map.put(a.getKey(),a.getValue());
    }

    @Autowired
    private ContractService service;

    @RequestMapping(value = "find", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findAll(@CurrentAccount User loginAccount, @PathVariable String platform,
                               @RequestParam String startDate, @RequestParam String endDate,String contractId) {

        return ResultModel.OK(service.findAll(loginAccount,startDate, endDate, platform,contractId));
    }

    @RequestMapping(value = "contractid/find", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findOne(@CurrentAccount User loginAccount, @PathVariable String platform,
                             String startDate, String endDate,String contractId) {

        return ResultModel.OK(service.findOne(loginAccount,startDate, endDate, platform,contractId));
    }


    @RequestMapping(value = "export", method = RequestMethod.GET,produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @ResponseBody
    public ResponseEntity<byte[]> export(@CurrentAccount User loginAccount, @PathVariable String platform, @RequestParam String startDate
                                , @RequestParam String endDate, HttpServletRequest request, HttpServletResponse response) {
        List<Contract> contractList = service.findAll(loginAccount, startDate, endDate, platform,null);


        byte[] content = new byte[0];
        StringBuilder sb = new StringBuilder();
        sb.append("时间,合同编号,客户账号,签约方,销售,开始日期,结束日期,套餐类型,合同金额,收款金额,合同状态\r\n");
        if(ValidateUtil.isValid(contractList)){
            for (Contract c : contractList){
                sb.append(c.getDs()).append(",").append(c.getContractCode()).append(",").append(c.getEmail()).append(",").append(c.getCustomerBody()).append(",").append(c.getSaleName()).append(",")
                        .append(c.getStartDate()).append(",").append(c.getEndDate()).append(",").append(c.getPriceLevelName()).append(",").append(c.getMoney()).append(",").append(c.getPayMoney()).append(",")
                        .append(CONTRACT_STATUS.get(c.getStatus())).append("\r\n");
            }
        }
        InputStream in =  new  ByteArrayInputStream(sb.toString().getBytes());
        try {
            content  = IOUtils.toByteArray(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        response.setHeader("filename", "contract.csv");
        response.setHeader("content-disposition", "attachment; filename=contract.csv");
        response.setHeader("Content-Type","text/csv");
        response.setContentType("APPLICATION/OCTET-STREAM");

        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), platform, "导出合同", startDate, endDate, request,platform);
        userlog.start();
        //返回文件字符串
        return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "pay/export", method = RequestMethod.GET,produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @ResponseBody
    public ResponseEntity<byte[]> exportPay(@CurrentAccount User loginAccount, @RequestParam String startDate, @RequestParam String endDate,
                                             HttpServletRequest request, HttpServletResponse response, @PathVariable String platform ,
                                            String moneyType,String packageTypeSearch,String money_ids) {
        List<ContractMoney> moneyList = service.findPayAll(loginAccount,startDate, endDate, platform, moneyType, packageTypeSearch,money_ids);
        Map<String, String> map = new HashMap<>();
        map.put("pay", "收款");
        map.put("invoice", "开票");

        byte[] content = new byte[0];
        StringBuilder sb = new StringBuilder();

        Long parseSum = 0L;
        if(ValidateUtil.isValid(moneyList)){
            for (ContractMoney c : moneyList){
                sb.append(c.getDs()).append(",")
                .append(c.getContractCode()==null?"":c.getContractCode()).append(",")
                .append(c.getEmail()==null?"":c.getEmail()).append(",")
                .append(c.getCompany()==null?"":c.getCompany()).append(",")
                .append(c.getPackageName()==null?"":c.getPackageName()).append(",")
                .append(c.getSalseName()==null?"":c.getSalseName()).append(",")
                .append(map.get(c.getType()==null?"":c.getType())).append(",")
                .append(c.getMoney()==null?"":c.getMoney()).append(",")
                .append(c.getCreateName()==null?"":c.getCreateName()).append("\r\n");

                if("pay".equals(c.getType())){
                    // 付款
                    parseSum +=  c.getMoney();

                }else{
                    parseSum -= c.getMoney();
                }
            }

        }

        StringBuffer titlebuffer = new StringBuffer();
        titlebuffer.append("日期, 合同编号 ,客户账号 ,签约方名称 ,套餐类型, 销售, 事项 ,金额 ,操作人 \r\n");
        titlebuffer.append("汇总,  - , -  ,  - ,  - ,  - ,  -  ,").append(parseSum).append(" , - \r\n");
        titlebuffer.append(sb);

        InputStream in =  new  ByteArrayInputStream(titlebuffer.toString().getBytes());
        try {
            content  = IOUtils.toByteArray(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        response.setHeader("filename", "contract_pay.csv");
        response.setHeader("content-disposition", "attachment; filename=contract_pay.csv");
       // response.setHeader("Content-Type", "application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Type","text/csv");
        response.setContentType("APPLICATION/OCTET-STREAM");

        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), platform, "导出收款开票", startDate, endDate, request, platform);
        userlog.start();
        //返回文件字符串
        return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "findone", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findOne(@CurrentAccount User loginAccount, @RequestParam String code) {
        return ResultModel.OK(service.findOne(code));
    }

    @RequestMapping(value = "checkAccount", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel checkAccount(@CurrentAccount User loginAccount, @RequestParam String email, @PathVariable String platform) {
        return ResultModel.OK(service.checkAccount(email, platform));
    }

    @RequestMapping(value = "checkTime", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel checkTime(@RequestParam String type, @RequestParam String email,
                                 @RequestParam String platform, @RequestParam(required = false) String product) {
        return ResultModel.OK(service.checkTime(email, platform,type,product));
    }

    @RequestMapping(value = "find/body", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findBody(@CurrentAccount User loginAccount,@PathVariable String platform,String dropall) {

        if("all".equals(dropall)){
            platform = dropall;
        }

        return ResultModel.OK(service.findBody(platform));
    }

    @RequestMapping(value = "find/code", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findCode(@CurrentAccount User loginAccount, @RequestParam String code,@PathVariable String platform,String company) {

        return ResultModel.OK(service.getContractCode(code,platform,company));
    }

    @RequestMapping(value = "find/pricelevel", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findPricelevel(@CurrentAccount User loginAccount, @PathVariable String platform) {
        return ResultModel.OK(service.findSetmeal(platform));
    }

    @RequestMapping(value = "find/increment", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findIncrement(@CurrentAccount User loginAccount) {
        return ResultModel.OK(service.findIncrement());
    }

    @RequestMapping(value = "find/rebat", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel rebat(@CurrentAccount User loginAccount, @RequestParam String product,
                             @RequestParam Integer level, @RequestParam Long money) {
        return ResultModel.OK(service.getRebat(product, level, money));
    }

    @RequestMapping(value = "find/sale", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel rebat(@CurrentAccount User loginAccount) {
        return ResultModel.OK(service.getSales());
    }


    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel create(@CurrentAccount User loginAccount, @RequestBody Contract contract, HttpServletRequest request, @PathVariable String platform) {

        Contract contract1 = service.create(loginAccount, contract);
        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), contract1.getContractCode(), "新建合同","",contract1.toString(), request, platform);
        userlog.start();
//        ContractSendEmailThread email = new ContractSendEmailThread(contract);
//        email.start();
        return ResultModel.OK(contract1);
    }

    @RequestMapping(value = "update", method = RequestMethod.PUT)
    @ResponseBody
    public ResultModel update(@CurrentAccount User loginAccount, @RequestBody Contract contract, HttpServletRequest request, @PathVariable String platform) {

        String ip = IPAddrUtil.getIpAddrNew(request);
        Contract contract1 = service.update(loginAccount, contract,ip);
        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), contract1.getContractCode(), "修改合同","",contract1.toString(), request, platform);
        userlog.start();

        return ResultModel.OK(contract1);
    }

    @RequestMapping(value = "pay", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel pay(@CurrentAccount User loginAccount, @RequestBody ContractMoney contract, HttpServletRequest request, @PathVariable String platform) {
        ContractMoney contract1 = service.pay(loginAccount, contract);
        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), contract1.getContractCode(), "收款开票","",contract1.toString(), request, platform);
        userlog.start();
        return ResultModel.OK(contract1);
    }

    @RequestMapping(value = "change", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel change(@CurrentAccount User loginAccount,
                              @RequestBody ContractChange contract, HttpServletRequest request, @PathVariable String platform) {
        Contract contract1 = service.change(loginAccount, contract,null);
        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), contract1.getContractCode(), "修改套餐","",contract1.toString(), request, platform);
        userlog.start();
        return ResultModel.OK(contract1);
    }

    /**
     *
     * @param loginAccount
     * @param startDate
     * @param endDate
     * @param code
     * @return
     */
    @RequestMapping(value = "find/pay", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findPay(@CurrentAccount User loginAccount, @RequestParam String startDate,
                               @RequestParam String endDate, @RequestParam String code) {
        return ResultModel.OK(service.findPay(startDate, endDate, code));
    }

    @RequestMapping(value = "find/change", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findChange(@CurrentAccount User loginAccount, @RequestParam String startDate,
                                  @RequestParam String endDate, @RequestParam String code) {
        return ResultModel.OK(service.findChange(startDate, endDate, code));
    }

    @RequestMapping(value = "find/flowchange", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel flowchange(@CurrentAccount User loginAccount, @RequestParam String startDate,
                                  @RequestParam String endDate, @RequestParam String code) {
        return ResultModel.OK(service.findflowChange(startDate, endDate, code));
    }


    @RequestMapping(value = "update/pay", method = RequestMethod.PUT)
    @ResponseBody
    public ResultModel updatePay(@CurrentAccount User loginAccount, @RequestBody ContractMoney contract, HttpServletRequest request,
                                 @PathVariable String platform) {

        String ip = IPAddrUtil.getIpAddrNew(request);
        Contract contract1 = service.updatePay(loginAccount, contract,ip);
        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), contract1.getContractCode(), "修改收款开票","", contract1.toString(), request, platform);
        userlog.start();
        return ResultModel.OK(contract1);
    }

    @RequestMapping(value = "find/payall", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findPayAll(@CurrentAccount User loginAccount, @RequestParam String startDate,
                               @RequestParam String endDate, @PathVariable String platform,
                                  String moneyType,String packageTypeSearch,String money_ids) {
        return ResultModel.OK(service.findPayAll(loginAccount,startDate, endDate, platform,moneyType,packageTypeSearch, money_ids));

    }

    @RequestMapping(value = "build", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel build(@RequestBody Contract contract, HttpServletRequest request) {

        logger.error("tkiio---------------" + contract);
        return ResultModel.OK(service.build(contract));
    }

    @RequestMapping(value = "trade", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel baseCreate( @PathVariable String platform) {
        return ResultModel.OK(service.getTradeData(platform));
    }


    @RequestMapping(value = "code/all", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel contractCodeAll( @PathVariable String platform,String contractId) {

        return ResultModel.OK(service.contractCodeAll(platform,contractId));
    }


    @RequestMapping(value = "setstaus", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel contractStatusUpdate( @PathVariable String platform,@CurrentAccount User loginUser,
                                             String contractId,String status,HttpServletRequest request) {

        String ip = IPAddrUtil.getIpAddrNew(request);
        return ResultModel.OK(service.contractStatusUpdate(platform,contractId,status,ip,loginUser));
    }


    @RequestMapping(value = "codecheck", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel codeCheck( @PathVariable String platform,String contractCode) {

        return ResultModel.OK(service.contractCodeCheck(platform,contractCode));
    }


    /**
     * 删除记录
     * @param platform
     * @param
     * @return
     */
    @RequestMapping(value = "change/del", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel changesDel( @PathVariable String platform,@CurrentAccount User loginAccount,
                                   String id,String type,HttpServletRequest request) {

        return ResultModel.OK(service.changesDel(platform,id,type, IPAddrUtil.getIpAddrNew(request),loginAccount));

    }









}
