package cn.com.countrygarden.bi.main.controller.resident;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.resident.ResidentContract;
import cn.com.countrygarden.bi.main.model.resident.ResidentContractParty;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.resident.ResidentContractService;
import cn.com.countrygarden.bi.main.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;

/**
 * Created by chenweijiang on 2017/11/13.
 */
@RestController("ResidentContractController")
@RequestMapping("/api/resident/contract")
public class ContractController {

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ResidentContractService contractService;

    @RequestMapping(value = "", method = {RequestMethod.GET}, produces = {"application/json;charset=utf-8"})
    public Object search(@RequestParam(name = "organId", required = false) String organId,
                         @RequestParam(name = "commId", required = false) String commId,
                         @RequestParam(name = "startTime", required = false) String startTime,
                         @RequestParam(name = "endTime", required = false) String endTime,
                         @RequestParam(name = "contractCode", required = false) String contractCode,
                         @RequestParam(name = "contractStatus", required = false) String contractStatus,
                         @RequestParam(name = "page", required = false, defaultValue = "1") int page,
                         @RequestParam(name = "size", required = false, defaultValue = "10") int size,
                         HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        ResidentContract query = new ResidentContract();
        query.setOrganId(organId);
        query.setCommId(commId);
        query.setContractCode(contractCode);
        query.setStatus(contractStatus);
        if (!StringUtils.isEmpty(startTime)) {
            query.setStartDate(DateUtil.parseDate(startTime));
        }
        if (!StringUtils.isEmpty(endTime)) {
            query.setEndDate(DateUtil.parseDate(endTime));
        }
        PageData result = contractService.listContract(token.getUserCode(), query, page, size);
        return Response.response(result);
    }


    @RequestMapping(value = "", method = {RequestMethod.PUT}, produces = {"application/json;charset=utf-8"})
    public Object create(@RequestParam(name = "organCode") String organId,
                         @RequestParam(name = "commId") String commId,
                         @RequestParam(name = "organName") String organName,
                         @RequestParam(name = "commName") String commName,
                         @RequestParam(name = "ncSystemNumber") String ncSystemNumber,
                         @RequestParam(name = "contractCode") String contractCode,
                         @RequestParam(name = "signTime") String signTime,
                         @RequestParam(name = "contractType") String contractType,
                         @RequestParam(name = "partyB") String partyB,
                         @RequestParam(name = "taxpayerNumber") String taxpayerNumber,
                         @RequestParam(name = "address") String address,
                         @RequestParam(name = "phone") String phone,
                         @RequestParam(name = "bank") String bank,
                         @RequestParam(name = "account") String account,
                         @RequestParam(name = "startDate") String startDate,
                         @RequestParam(name = "endDate") String endDate,
                         @RequestParam(name = "fixedAmount") String fixedAmount,
                         @RequestParam(name = "floatAmount", required = false) String floatAmount,
                         @RequestParam(name = "paymentMethod") String paymentMethod,
                         @RequestParam(name = "remark", required = false) String remark,
                         @RequestParam(name = "bipApprovalNumber") String bipApprovalNumber,
                         @RequestParam(name = "isFinalSigned") boolean isFinalSigned,
                         HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        ResidentContract entity = new ResidentContract();
        entity.setOrganId(organId);
        entity.setCommId(commId);
        entity.setOrganName(organName);
        entity.setCommName(commName);
        entity.setNcSystemNumber(ncSystemNumber);
        entity.setContractCode(contractCode);
        entity.setSignTime(DateUtil.parseDate(signTime));
        entity.setContractType(contractType);
        entity.setPartyB(partyB);
        entity.setTaxpayerNumber(taxpayerNumber);
        entity.setAddress(address);
        entity.setPhone(phone);
        entity.setBank(bank);
        entity.setAccount(account);
        entity.setStartDate(DateUtil.parseDate(startDate));
        entity.setEndDate(DateUtil.parseDate(endDate));
        entity.setFixedAmount(new BigDecimal(fixedAmount));
        entity.setFloatAmount(floatAmount);
        entity.setPaymentMethod(paymentMethod);
        entity.setRemark(remark);
        entity.setBipApprovalNumber(bipApprovalNumber);
        entity.setFinalSigned(isFinalSigned);
        contractService.createContract(entity, token.getUserCode());
        return Response.response("");
    }

    @RequestMapping(value = "", method = {RequestMethod.POST}, produces = {"application/json;charset=utf-8"})
    public Object update(@RequestParam(name = "id") Integer id,
                         @RequestParam(name = "organCode") String organId,
                         @RequestParam(name = "commId") String commId,
                         @RequestParam(name = "organName") String organName,
                         @RequestParam(name = "commName") String commName,
                         @RequestParam(name = "ncSystemNumber") String ncSystemNumber,
                         @RequestParam(name = "contractCode") String contractCode,
                         @RequestParam(name = "signTime") String signTime,
                         @RequestParam(name = "contractType") String contractType,
                         @RequestParam(name = "partyB") String partyB,
                         @RequestParam(name = "taxpayerNumber") String taxpayerNumber,
                         @RequestParam(name = "address") String address,
                         @RequestParam(name = "phone") String phone,
                         @RequestParam(name = "bank") String bank,
                         @RequestParam(name = "account") String account,
                         @RequestParam(name = "startDate") String startDate,
                         @RequestParam(name = "endDate") String endDate,
                         @RequestParam(name = "fixedAmount") String fixedAmount,
                         @RequestParam(name = "floatAmount", required = false) String floatAmount,
                         @RequestParam(name = "paymentMethod") String paymentMethod,
                         @RequestParam(name = "remark", required = false) String remark,
                         @RequestParam(name = "bipApprovalNumber") String bipApprovalNumber,
                         @RequestParam(name = "isFinalSigned") boolean isFinalSigned,
                         HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        ResidentContract entity = new ResidentContract();
        entity.setId(id);
        entity.setOrganId(organId);
        entity.setCommId(commId);
        entity.setOrganName(organName);
        entity.setCommName(commName);
        entity.setNcSystemNumber(ncSystemNumber);
        entity.setContractCode(contractCode);
        entity.setSignTime(DateUtil.parseDate(signTime));
        entity.setContractType(contractType);
        entity.setPartyB(partyB);
        entity.setTaxpayerNumber(taxpayerNumber);
        entity.setAddress(address);
        entity.setPhone(phone);
        entity.setBank(bank);
        entity.setAccount(account);
        entity.setStartDate(DateUtil.parseDate(startDate));
        entity.setEndDate(DateUtil.parseDate(endDate));
        entity.setFixedAmount(new BigDecimal(fixedAmount));
        entity.setFloatAmount(floatAmount);
        entity.setPaymentMethod(paymentMethod);
        entity.setRemark(remark);
        entity.setBipApprovalNumber(bipApprovalNumber);
        entity.setFinalSigned(isFinalSigned);
        contractService.updateContract(entity, token.getUserCode());
        return Response.response("");
    }

    @RequestMapping(value = "/{contractId}", method = {RequestMethod.DELETE}, produces = {"application/json;charset=utf-8"})
    public Object expired(@PathVariable(value = "contractId", required = true) Integer contractId,
                          HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        contractService.expired(contractId, token.getUserCode());
        return Response.response("");
    }

    @RequestMapping(value = "/status", method = {RequestMethod.PUT}, produces = {"application/json;charset=utf-8"})
    public Object updateStatus(@RequestParam(name = "contractId", required = true) Integer contractId,
                               @RequestParam(name = "status", defaultValue = "", required = true) String status,
                               HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        contractService.updateStatus(contractId, token.getUserCode(), status);
        return Response.response("");
    }

    @RequestMapping(value = "/party/export", method = {RequestMethod.GET}, produces = {"application/json;charset=utf-8"})
    public Object export(HttpServletRequest request, HttpServletResponse response) {
        List<ResidentContractParty> parties = contractService.exportPartyB();

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        workbook.setSheetName(0, "供应商列表");
        PartyBExporter exporter = new PartyBExporter();
        exporter.createHeader(workbook, sheet);
        exporter.createBody(parties, workbook, sheet);

        response.setContentType("multipart/form-data");
        String fileName = "export.xlsx";
        try {
            fileName = URLEncoder.encode("供应商列表.xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception ex) {

        } finally {
            try {
                workbook.close();
            } catch (Exception ex) {

            }
        }

        return Response.response();
    }
}
