package co.dc.aptiv.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import co.dc.aptiv.AptivApp;
import co.dc.commons.utils.DateTimeUtil;
import co.dc.aptiv.pojo.BillPojo;
import org.apache.commons.dbutils.QueryRunner;
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 co.dc.commons.basedao.BaseDao;
import co.dc.commons.dto.RetStatus;
import co.dc.aptiv.ScanFrame;
import co.dc.aptiv.mina.TestMachineCollectorMina;
import co.dc.aptiv.pojo.BillDetailPojo;
import org.springframework.util.StringUtils;

/**
 * @describe: 单据
 * @author: liuxinglong
 * @version: 2018/4/17 15:21
 */
@Service("billService")
public class BillService extends BaseDao<BillPojo> {

    private static final Log log = LogFactory.getLog(BillService.class);

    @Resource
    private QueryRunner queryRunner;
    @Resource
    private BillDetailService billDetailService;
    @Resource
    private TestMachineCollectorMina sendCollectorMina;

    private ScanFrame scanFrame;

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

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

    /**
     * 根据参数获取捡配单数据
     *
     * @param starttime 开始时间
     * @param endtime   结束时间
     * @return
     */
    public List<BillPojo> listonlyPCbill(String starttime, String endtime) {
        log.info("根据参数获取捡配单数据-String starttime=" + starttime + ", String endtime=" + endtime);
        List<BillPojo> billPojos = new ArrayList<BillPojo>();
        StringBuffer sql = new StringBuffer();
        sql.append("select * from ").append(getTableName()).append(" ");
        sql.append("where 1=1 ");
        if (!starttime.equals("")) {
            sql.append("and createtime >= '").append(starttime).append(" 00:00:00' ");
        }
        if (!endtime.equals("")) {
            sql.append("and createtime <= '").append(endtime).append(" 23:59:59' ");
        }
        sql.append(" and delflag = 0 order by createtime desc");

        try {
            billPojos = queryRunner.query(sql.toString(), new BeanListHandler<BillPojo>(BillPojo.class));
        } catch (SQLException e) {
            log.error("根据参数获取捡配单数据-异常:", e);
        }
        return billPojos;
    }

    /**
     * 整单删除
     *
     * @param pcbillid 捡配单id
     * @return
     */
    public int delPCbill(long pcbillid) {
        log.info("整单删除-long pcbillid=" + pcbillid);
        int upint = 0;
        upint = del(pcbillid);
        //此处需要删除相关的详情表数据和物料表数据
        try {
            queryRunner.update("delete from dc_PCbillinfo where pcbillid=?", pcbillid);
        } catch (SQLException e) {
            log.error("整单删除-异常:", e);
        }
        return upint;
    }

    /**
     * 获取当前产品的所有数据
     *
     * @param pcbillid
     * @return
     */
    public RetStatus<BillPojo> checkPCbill(long pcbillid) {
        log.info("获取当前产品的所有数据-long pcbillid=" + pcbillid);
        RetStatus<BillPojo> ret = new RetStatus<BillPojo>(1, "");
        BillPojo billPojo;
        List<BillDetailPojo> goodinfos;
        try {
            billPojo = findById(pcbillid);
            goodinfos = AptivApp.billDetailService.getinfoGoods(pcbillid);
            update("countedBox", goodinfos != null ? goodinfos.size() : 0, "id", pcbillid);
            ret.set(0, "", billPojo);
        } catch (Exception e) {
            log.error("获取当前产品的所有数据-异常:", e);
        }
        return ret;

    }


    /**
     * 获取所有单据信息
     *
     * @return
     */
    public List<BillPojo> listAllBill() {
        String sql = "SELECT * FROM bill WHERE delFlag = 0";
        try {
            List<BillPojo> listBill = queryRunner.query(sql, new BeanListHandler<BillPojo>(BillPojo.class));
            return listBill;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据参数查找单据
     *
     * @param online     查找模式 true 联机模式，false 自动模式
     * @param materielId 物料id
     * @param beginDate  开始日期
     * @param endDate    结束日期
     * @return
     */
    public List<BillPojo> findByParam(boolean online, Long materielId, String beginDate, String endDate) {
        String sql = "SELECT * FROM bill WHERE delFlag = 0";
        if (online) {
            sql += " AND materielId = 0";
        } else {
            sql += " AND materielId != 0";
        }
        if (!online && materielId > 0) {
            sql += " AND materielId = " + materielId;
        }
        if (!StringUtils.isEmpty(beginDate) && !StringUtils.isEmpty(endDate)) {
            sql += " AND createTime BETWEEN '" + beginDate + " 00:00:00' AND '" + endDate + " 23:59:59'";
        }
        try {
            List<BillPojo> listBill = queryRunner.query(sql, new BeanListHandler<BillPojo>(BillPojo.class));
            return listBill;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 创建单据
     *
     * @param materielId 物料单据
     * @return
     */
    public BillPojo addBill(Long materielId) {
        String dateTime = DateTimeUtil.getDateTimeString();
        BillPojo billPojo = new BillPojo();
        billPojo.setBillCode(dateTime.replace(" ", "").replace("-", "").replace(":", ""));
        billPojo.setMaterielId(materielId);
        billPojo.setNumber(0);
        billPojo.setQualifiedNum(0);
        billPojo.setUnqualifiedNum(0);
        billPojo.setState(0);
        billPojo.setCreateTime(dateTime);
        billPojo.setModifyTime(dateTime);
        billPojo.setDelFlag(0);
        long billId = this.save(billPojo);
        billPojo.setId(billId);
        log.info("创建单据 单据Id=" + billId);
        return billPojo;
    }

    /**
     * 更新单据
     *
     * @param billPojo 单据
     * @return
     */
    public int updateBill(BillPojo billPojo) {
        log.info("更新单据 单据编号=" + billPojo.getBillCode());
        return this.update(billPojo);
    }

    /**
     * 更新单据统计数据
     *
     * @param id
     * @param bdp
     * @return
     */
    public int updateBillStatistics(long id, BillDetailPojo bdp) {
        log.info("更新单据 id=" + id);
        BillPojo billPojo = this.findById(id);
        billPojo.setNumber(billPojo.getNumber() + 1);
        billPojo.setQualifiedNum(billPojo.getQualifiedNum() + (bdp.getState() == 1 ? 1 : 0));
        billPojo.setUnqualifiedNum(billPojo.getUnqualifiedNum() + (bdp.getState() == 1 ? 0 : 1));
        billPojo.setModifyTime(DateTimeUtil.getDateTimeString());

        //调用显示当前任务统计
        getScanFrame().loadDate(billPojo.getNumber(), billPojo.getQualifiedNum(), billPojo.getUnqualifiedNum());
        return this.update(billPojo);
    }


    public ScanFrame getScanFrame() {
        return scanFrame;
    }
}
