package co.dc.aptiv.service;

import co.dc.aptiv.AptivApp;
import co.dc.aptiv.BillFrame;
import co.dc.aptiv.ScanFrame;
import co.dc.aptiv.common.XLSService;
import co.dc.aptiv.pojo.BillDetailPojo;
import co.dc.aptiv.pojo.BillPojo;
import co.dc.aptiv.pojo.MaterielPojo;
import co.dc.commons.basedao.BaseDao;
import co.dc.commons.utils.DateTimeUtil;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @describe: 单据详情
 * @author: liuxinglong
 * @version: 2018/4/17 15:21
 */
@Service("billDetailService")
public class BillDetailService extends BaseDao<BillDetailPojo> {

    private static final Log log = LogFactory.getLog(BillDetailService.class);
    @Resource
    private BillService billService;
    @Resource
    private PropertiesConfiguration configuration;

    private ScanFrame scanFrame;
    private BillFrame billFrame;

    public BillFrame getBillFrame() {
        return billFrame;
    }

    public void setBillFrame(BillFrame billFrame) {
        this.billFrame = billFrame;
    }

    public ScanFrame getScanFrame() {
        return scanFrame;
    }

    public void setScanFrame(ScanFrame scanFrame) {
        this.scanFrame = scanFrame;
    }

    @Override
    protected String getTableName() {
        return BillDetailPojo.tableName;
    }

    /**
     * 根据pcbillid查询产品列表
     *
     * @param pcbillid
     * @return
     */
    public List<BillDetailPojo> getinfoGoods(long pcbillid) {
        log.info("根据pcbillid查询产品列表-long pcbillid=" + pcbillid);
        List<BillDetailPojo> billDetailPojos = new ArrayList<BillDetailPojo>();
        try {
            billDetailPojos = queryRunner.query("select * from " + getTableName() + " where pcbillid = " + pcbillid + " and delflag = 0 order by modifyTime desc",
                    new BeanListHandler<BillDetailPojo>(BillDetailPojo.class));
        } catch (SQLException e) {
            log.error("根据pcbillid查询产品列表-异常:", e);
        }
        return billDetailPojos;
    }

    /**
     * 查询所有为上传的产品列表并且变更上传字段的值
     *
     * @return
     */
    public List<BillDetailPojo> getunupedGoods() {
        log.info("查询所有为上传的产品列表");
        List<BillDetailPojo> billDetailPojos = new ArrayList<BillDetailPojo>();
        Map<String, Object> where = new HashMap<String, Object>();
        where.put("updatedflag", 0);
        billDetailPojos = listByParam(where);
        if (billDetailPojos != null && billDetailPojos.size() > 0) {
            update("updatedflag", 1, "updatedflag", 0);
        }
        return billDetailPojos;
    }


    /**
     * 获取物料在详情表中最后一条记录的创建日期
     *
     * @param materielId 物料Id
     * @return
     */
    public String getLastDate(long materielId) {
        try {
            String sql = "SELECT * FROM bill_detail WHERE materielId = " + materielId + " ORDER BY createTime DESC LIMIT 1";
            BillDetailPojo billDetailPojo = queryRunner.query(sql, new BeanHandler<BillDetailPojo>(BillDetailPojo.class));
            if (billDetailPojo != null) {
                return billDetailPojo.getCreateTime().substring(0, 10);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存单据详情
     *
     * @param billId         单据Id
     * @param materielId     物料Id
     * @param qrCode         生成的二维码
     * @param colledtionCode 采集器返回信息
     * @return
     */
    public BillDetailPojo addBillDetail(Long billId, Long materielId, String qrCode, String colledtionCode) {
        log.info("保存码详情");
        BillDetailPojo billDetailPojo = new BillDetailPojo();
        try {
            billDetailPojo.setBillId(billId);
            billDetailPojo.setMaterielId(materielId);
            billDetailPojo.setQrCode(qrCode);
            billDetailPojo.setCollectionCode(colledtionCode);
            billDetailPojo.setState(qrCode.equals(colledtionCode) ? 1 : 0);
            billDetailPojo.setCreateTime(AptivApp.qrcodeService.createDateTime);
            billDetailPojo.setModifyTime(DateTimeUtil.getDateTimeString());
            billDetailPojo.setDelFlag(0);
            Long billDetailId = this.save(billDetailPojo);
            billDetailPojo.setId(billDetailId);
        } catch (Exception e) {
            log.error("生产模式：二维码唯一索引生效" + e);
            billDetailPojo.setId(-1);
            billDetailPojo.setQrCode("正常生产捕获重码，请停止打印并联系管理员！" + billDetailPojo.getQrCode());
            billDetailPojo.setState(0);
            AptivApp.qrcodeService.sendErrorCommand("生产模式：二维码唯一索引生效！");
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    getScanFrame().alertMsg(1, "正常生产捕获重码，请停止打印并联系管理员！");
                }
            });
        }
        return billDetailPojo;
    }

    /**
     * 导出详情
     *
     * @param billPojos
     */
    public void exportDetails(List<BillPojo> billPojos) {
        if (billPojos == null || billPojos.size() < 1) {
            getBillFrame().alertMsg(1, "当前查询结果为空，不能导出！");
            return;
        }
        List<MaterielPojo> materielPojos = AptivApp.materielService.listAll();
        Map<Long, MaterielPojo> materielMap = new HashMap<Long, MaterielPojo>(materielPojos.size());
        for (MaterielPojo pojo : materielPojos) {
            materielMap.put(pojo.getId(), pojo);
        }
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        Integer index = 1;
        for (BillPojo billPojo : billPojos) {
            List<BillDetailPojo> billDetailPojos = listByParam("billId", billPojo.getId() + "");
            //单据查详情
            for (int j = 0; j < billDetailPojos.size(); j++) {
                Map<String, Object> map = new HashMap<String, Object>(8);
                map.put("index", index);
                map.put("billCode", billPojo.getBillCode());
                MaterielPojo materielPojo = materielMap.get(billDetailPojos.get(j).getMaterielId());
                map.put("dpn", materielPojo != null ? materielPojo.getDpn() : "物料已删除");
                map.put("qrCode", billDetailPojos.get(j).getQrCode());
                map.put("collectionCode", billDetailPojos.get(j).getCollectionCode());
                map.put("state", billDetailPojos.get(j).getState() == 1 ? "合格" : "不合格");
                map.put("createTime", billDetailPojos.get(j).getCreateTime());
                map.put("modifyTime", billDetailPojos.get(j).getModifyTime());
                mapList.add(map);
                index++;
            }
        }
        //检查码是否超过行限制
        if (index > 65535) {
            getBillFrame().alertMsg(1, "导出的码数据不能超过65535行！");
            return;
        }
        //设置路径并导出excel
        String fileName = "C:\\Users\\" + System.getProperties().getProperty("user.name") + "\\Desktop\\" + "码详情" + DateTimeUtil.getDateTimeString().replace(":", "-") + ".xls";
        boolean bool = export(mapList, fileName);
        if (bool) {
            getBillFrame().alertMsg(0, "导出成功，路径为：" + fileName);
        } else {
            getBillFrame().alertMsg(1, "数据导出失败！");
        }
    }

    /**
     * 导出
     *
     * @param mapList  结果
     * @param fileName 文件名
     */
    public boolean export(List<Map<String, Object>> mapList, String fileName) {
        try {
            XLSService xlsService = new XLSService(fileName);
            //全部数据  设置第一行名称
            xlsService.createRow(1, 0);
            //顶级经销商可以导出所有的机构或门店
            xlsService.setStringCell(0, "序号");
            xlsService.setStringCell(1, "单据编号");
            xlsService.setStringCell(2, "DPN");
            xlsService.setStringCell(3, "生成码");
            xlsService.setStringCell(4, "采集码");
            xlsService.setStringCell(5, "是否合格");
            xlsService.setStringCell(6, "码生成时间");
            xlsService.setStringCell(7, "码采集时间");
            //单据查详情
            for (Map<String, Object> map : mapList) {
                xlsService.createRow(1, Integer.parseInt(map.get("index").toString()));
                xlsService.setIntCell(0, Integer.parseInt(map.get("index").toString()));
                xlsService.setStringCell(1, map.get("billCode").toString());
                xlsService.setStringCell(2, map.get("dpn").toString());
                xlsService.setStringCell(3, map.get("qrCode").toString());
                xlsService.setStringCell(4, map.get("collectionCode").toString());
                xlsService.setStringCell(5, map.get("state").toString());
                xlsService.setStringCell(6, map.get("createTime").toString());
                xlsService.setStringCell(7, map.get("modifyTime").toString());
            }
            xlsService.getWorkbook().removeSheetAt(0);
            xlsService.exportXLS();
            return true;
        } catch (Exception e) {
            log.error("导出机构异常" + e);
            return false;
        }
    }


}
