package com.iamberry.wechat.handles.admin;

import com.iamberry.wechat.core.entity.*;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.drp.PlaceWithDrawalsLogs;
import com.iamberry.wechat.core.entity.machineNumber.MachineNumber;
import com.iamberry.wechat.core.entity.machineNumber.MachineNumberLogs;
import com.iamberry.wechat.core.entity.machineNumber.WarrantyCard;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.machineNumber.MachineNumberService;
import com.iamberry.wechat.tools.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by Administrator on 2017/7/19.
 */
@Controller
@RequestMapping("/admin/qrCode")
public class QrCodeHandler {
    @Autowired
    private MachineNumberService machineNumberService;
    @Autowired
    private SystemService systemService;

    @ResponseBody
    @RequestMapping("/_addQrCode")
    public ModelAndView _addQrCode(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/admin/qrCode/addQrCode");
        return mv;
    }
    /**
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/addQrCode")
    public ResultMsg addQrCode(HttpServletRequest request,
                                             @RequestParam("btchNo") String btchNo,
                                             @RequestParam("describe") String describe,
                                             @RequestParam("number") Integer number) throws Exception {
        ResultMsg remsg = new ResultMsg();
        remsg.setStatus(true);
        remsg.setResultCode("200");
        remsg.setMessage("添加成功！");
        if(StringUtils.isEmpty(btchNo)){
            remsg.setStatus(false);
            remsg.setResultCode("4000");
            remsg.setMessage("批次号不能为空!");
            return remsg;
        }
        if(StringUtils.isEmpty(describe)){
            remsg.setStatus(false);
            remsg.setResultCode("4000");
            remsg.setMessage("描述不能为空!");
            return remsg;
        }
        if(number == null || number == 0){
            remsg.setStatus(false);
            remsg.setResultCode("4000");
            remsg.setMessage("数量不能为空!");
            return remsg;
        }
        /*if(machineNumberService.selectQrcodeLogsByBatch(btchNo) == 1){
            remsg.setStatus(false);
            remsg.setResultCode("4000");
            remsg.setMessage("该批次已存在!");
            return remsg;
        }*/
        MachineNumberLogs machineNumberLogs = new MachineNumberLogs();
        machineNumberLogs.setLogsBatch(btchNo);
        machineNumberLogs.setLogsRemark(describe);
        machineNumberLogs.setLogsNumber(number);
        Integer msg = 0;
        try{
            msg =  machineNumberService.addNumberLogs(machineNumberLogs);
        }catch(Exception ex){ //捕获异常，也可以是具体异常，如NullPointException
            remsg.setStatus(false);
            remsg.setResultCode("4000");
            remsg.setMessage("添加失败!");
            return remsg;
        }
        if(msg == 1){
            QrCode gc = new QrCode(machineNumberService);
            gc.add(machineNumberLogs);
            //启动线程获取二维码
            /*Thread thread1 = new Thread(gc);
            thread1.start();*/
            new Thread(gc).start();
            //gc.run();
        }else{
            remsg.setStatus(false);
            remsg.setResultCode("4000");
            remsg.setMessage("添加失败!");
            return remsg;
        }
        return remsg;
    }


    /**
     * 查询生产二维码日志列表
     * @param request
     * @param pageNO
     * @param pageSize
     * @param logsBatch
     * @param beginDate
     * @param endDate
     * @return
     */
    @RequestMapping("/listQrCodeLogs")
    public ModelAndView listQrCodeLogs(HttpServletRequest request,
                                       @RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
                                       @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                       @RequestParam(value = "logsBatch",  required = false) String logsBatch,
                                       @RequestParam(value = "beginDate",  required = false) String beginDate,
                                       @RequestParam(value = "endDate",  required = false) String endDate){
        ModelAndView mv = new ModelAndView("/admin/qrCode/listQrCode");
        Page page = new Page();
        Map params=new HashMap<String, Object>();
        if(logsBatch != null && !logsBatch.equals("")){
            params.put("logsBatch",logsBatch);
            mv.addObject("logsBatch", logsBatch);
        }
        if(beginDate != null && !beginDate.equals("")){
            params.put("beginDate",beginDate);
            mv.addObject("beginDate", beginDate);
        }
        if(endDate != null && !endDate.equals("")){
            params.put("endDate",endDate);
            mv.addObject("endDate", endDate);
        }
        page.setParams(params);
        page.setPageNo((pageNO - 1) * pageSize);
        page.setPageSize(pageSize);
        // JSP 数据
        mv.addObject("list", machineNumberService.listNumberLogs(page));
        // 分页数据
        mv.addObject("pageSize", PaperBean.justPaperCount(machineNumberService.listNumberLogsCount(page), pageSize));
        mv.addObject("pageNO", pageNO);
        mv.addObject("url","/admin/qrCode/listQrCodeLogs?pageSize=" + pageSize + "&pageNO=");
        return mv;
    }


    /**
     * 查询生产批次二维码
     * @param request
     * @param pageNO
     * @param pageSize
     * @return
     */
    @RequestMapping("/listQrCodeNumber")
    public ModelAndView listQrCodeNumber(HttpServletRequest request,
                                   @RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
                                   @RequestParam(value = "pageSize", defaultValue = "20", required = false) int pageSize,
                                   @RequestParam(value = "logsBatch",  required = false) String logsBatch){
        ModelAndView mv = new ModelAndView("/admin/qrCode/listQrCodeNumber");
        Page page = new Page();
        Map params=new HashMap<String, Object>();
        if(logsBatch != null && !logsBatch.equals("")){
            params.put("logsBatch",logsBatch);
        }
        page.setParams(params);
        page.setPageNo((pageNO - 1) * pageSize);
        page.setPageSize(pageSize);
        // JSP 数据
        mv.addObject("list", machineNumberService.listNumberQrCode(page));
        // 分页数据
        mv.addObject("pageSize", PaperBean.justPaperCount(machineNumberService.listNumberQrCodeCount(page), pageSize));
        mv.addObject("pageNO", pageNO);
       /* mv.addObject("barCodePrefix", ResultInfo.barCodePrefix);//条形码前缀*/
        mv.addObject("url","/admin/qrCode/listQrCodeNumber?pageSize=" + pageSize + "&logsBatch="+logsBatch+"&pageNO=");
        return mv;
    }

    /**
     * 修改状态为已打印
     * @param request
     * @param numberId
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateIsprInt")
    public ResultMsg updateIsprInt(HttpServletRequest request,@RequestParam(value = "numberId",  required = false) String numberId){
        ResultMsg resultMsg = new ResultMsg();
        if(numberId == null){
            resultMsg.setStatus(false);
            resultMsg.setResultCode("400");
            return resultMsg;
        }
        Integer msg = machineNumberService.updateIsprInt(numberId);
        if(msg == 1){
            resultMsg.setStatus(true);
            resultMsg.setResultCode("200");
        }
        return resultMsg;
    }


    @RequestMapping("/downLoadBarcode")
    public ModelAndView downLoadWithdraw(HttpServletRequest request, MachineNumber machineNumber) {
        // 准备model
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("fileName", "条形码记录"); // 下载文件名称

        // 标题
        List<String> titles = new ArrayList<String>();
        titles.add("条形码");
        titles.add("批次");
        model.put("titles", titles);

        Page page = new Page();
        Map params=new HashMap<String, Object>();
        if(machineNumber.getNumberBatch() != null && !machineNumber.getNumberBatch().equals("")) {
            params.put("logsBatch", machineNumber.getNumberBatch());
        }
        page.setPageNo(0);
        page.setParams(params);
        List<MachineNumber> listMachineNumber = machineNumberService.listNumberQrCode(page);
        // 封装导出内容
        List<List<Object>> countexts = new ArrayList<List<Object>>();
        if (listMachineNumber != null && listMachineNumber.size() > 0) {
            for (MachineNumber MachineNumber : listMachineNumber) {
                List<Object> row = new ArrayList<Object>();
                row.add(MachineNumber.getNumberBarcode());
                row.add(MachineNumber.getNumberBatch());
                countexts.add(row);
            }
        }
        model.put("varList", countexts);
        ObjectExcelView erv = new ObjectExcelView();
        ModelAndView mv = new ModelAndView(erv, model);
        return mv;
    }

    @ResponseBody
    @RequestMapping("/qrcodProgressUpdate")
    public ResponseJson qrcodProgressUpdate(HttpServletRequest request,
                                    @RequestParam(value = "logsBatchs",  required = false) String[] logsBatchs){
        ResponseJson responseJson = new ResponseJson();
        if(logsBatchs == null){
            return responseJson;
        }
        // JSP 数据
        responseJson.addResponseKeyValue("list", machineNumberService.qrcodProgressUpdate(logsBatchs));
        return responseJson;
    }


    /**
     * 查询质保卡信息
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/select_card_list")
    public ModelAndView selectWarrantyCardList(HttpServletRequest request,
                                               @RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
                                               @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize) throws Exception {
        ModelAndView mv = new ModelAndView("admin/qrCode/warrantyCardList");
        StringBuilder url = new StringBuilder("/admin/qrCode/select_card_list?pageSize=");
        url.append(pageSize);
        WarrantyCard card = new WarrantyCard();

        String userName = request.getParameter("userName");
        String userEmail = request.getParameter("userEmail");
        String cardBarcode = request.getParameter("cardBarcode");
        if (StringUtils.isNotEmpty(userName)) {
            mv.addObject("userName",userName);
            url.append("&userName=");
            url.append(userName);
            card.setUserName(userName);
        }
        if (StringUtils.isNotEmpty(userEmail)) {
            mv.addObject("userEmail",userEmail);
            url.append("&userEmail=");
            url.append(userEmail);
            card.setUserEmail(userEmail);
        }
        if (StringUtils.isNotEmpty(cardBarcode)) {
            mv.addObject("cardBarcode",cardBarcode);
            url.append("&cardBarcode=");
            url.append(cardBarcode);
            card.setCardBarcode(cardBarcode);
        }

        //获取换新时间期限
        ShopSystemRule renewRule =  systemService.selectOneShopRuleById(242);
        //获取质保时间期限
        ShopSystemRule endRule =  systemService.selectOneShopRuleById(243);

        PageBean page = new PageBean();
        page.setPageNumber(pageNO);
        page.setPageSize(pageSize);
        page.initRecordBegin();
        card.setPage(page);

        //分页查询质保卡集合
        List<WarrantyCard> cardList = machineNumberService.listWarrantyCard(card);

        //添加质保结束时间和包换时间
        if (cardList != null && cardList.size() > 0) {
            for (WarrantyCard warrantyCard : cardList) {
                StringBuilder location = new StringBuilder(warrantyCard.getCardProvince());
                if (StringUtils.isNotEmpty(warrantyCard.getCardCity())) {
                    location.append("-");
                    location.append(warrantyCard.getCardCity());
                }
                if (StringUtils.isNotEmpty(warrantyCard.getCardDistrict())) {
                    location.append("-");
                    location.append(warrantyCard.getCardDistrict());
                }
                warrantyCard.setCardLocation(location.toString());
                if (warrantyCard.getCardSaleTime() != null) {
                    warrantyCard.setCardEndTime(updateDate(warrantyCard.getCardSaleTime(),endRule.getRuleNum().intValue()));
                    warrantyCard.setCardRenewTime(updateDate(warrantyCard.getCardSaleTime(),renewRule.getRuleNum().intValue()));
                }
            }
        }

        url.append("&pageNO=");
        mv.addObject("cardList",cardList);
        mv.addObject("pageSize",machineNumberService.WarrantyCardCount(card));
        mv.addObject("pageNO",pageNO);
        mv.addObject("url",url.toString());
        return mv;
    }

    /**
     * 修改日期 增加月
     * @param date
     * @param month
     * @return
     * @throws Exception
     */
    public Date updateDate(Date date,int month) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, month);
        return calendar.getTime();
    }
}

