package com.xmomen.module.order.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xmomen.framework.mybatis.dao.MybatisDao;
import com.xmomen.framework.mybatis.page.Page;
import com.xmomen.framework.utils.DateUtils;
import com.xmomen.framework.utils.StringUtilsExt;
import com.xmomen.module.order.entity.TbOrder;
import com.xmomen.module.order.entity.TbOrderExample;
import com.xmomen.module.order.entity.TbOrderRelation;
import com.xmomen.module.order.entity.TbPurchase;
import com.xmomen.module.order.entity.TbPurchaseExample;
import com.xmomen.module.order.mapper.OrderMapper;
import com.xmomen.module.order.model.CreatePurchase;
import com.xmomen.module.order.model.OrderPurchaseModel;
import com.xmomen.module.order.model.PurchaseModel;

/**
 * Created by Jeng on 16/4/5.
 */
@Service
public class PurchaseService {

    @Autowired
    MybatisDao mybatisDao;

    /**
     * 查询采购单
     *
     * @param keyword
     * @param limit
     * @param offset
     * @return
     */
    public Page<PurchaseModel> getPurchaseList(Map param, Integer limit, Integer offset) {
        //调用mybatisDao的selectPage方法，传入OrderMapper.ORDER_MAPPER_NAMESPACE + "getPurchaseList"作为mapper的namespace，param作为参数，limit和offset作为分页参数
        return (Page<PurchaseModel>) mybatisDao.selectPage(OrderMapper.ORDER_MAPPER_NAMESPACE + "getPurchaseList", param, limit, offset);
    }

    /**
     * 查询采购单
     *
     * @param keyword
     * @param limit
     * @param offset
     * @return
     */
    public List<PurchaseModel> getPurchaseList(Map param) {
        //调用mybatisDao的getSqlSessionTemplate().selectList方法，传入OrderMapper.ORDER_MAPPER_NAMESPACE + "getPurchaseList"作为mapper的namespace，param作为参数
        return mybatisDao.getSqlSessionTemplate().selectList(OrderMapper.ORDER_MAPPER_NAMESPACE + "getPurchaseList", param);
    }

    /**
     * 创建采购单
     *
     * @param createPurchase
     * @return
     */
    @Transactional
    public synchronized void createPurchase(CreatePurchase createPurchase) {
        //创建一个Map对象，用于存放参数
        Map param = new HashMap();

        //创建一个SimpleDateFormat对象，用于格式化日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //如果createPurchase的appointmentTimeStart不为空，则将appointmentTimeStart和appointmentTimeEnd格式化为字符串，并存入param中
        if (createPurchase.getAppointmentTimeStart() != null) {
            param.put("startTime", format.format(createPurchase.getAppointmentTimeStart()));
            param.put("endTime", format.format(createPurchase.getAppointmentTimeEnd()));
        }
        //否则，将orderDate格式化为字符串，并存入param中
        else {
            param.put("startTime", format.format(createPurchase.getOrderDate()));
            param.put("endTime", format.format(new Date(createPurchase.getOrderDate().getTime() + 24 * 3600 * 1000)));
        }
        //调用mybatisDao的getSqlSessionTemplate().selectList方法，传入OrderMapper.ORDER_MAPPER_NAMESPACE + "getOrderPurchaseList"作为mapper的namespace，param作为参数，将结果存入purchaseModelList中
        List<OrderPurchaseModel> purchaseModelList = mybatisDao.getSqlSessionTemplate().selectList(OrderMapper.ORDER_MAPPER_NAMESPACE + "getOrderPurchaseList", param);
        //如果purchaseModelList为空，则抛出异常
        if (CollectionUtils.isEmpty(purchaseModelList)) {
            if (createPurchase.getAppointmentTimeStart() != null) {
                throw new IllegalArgumentException("选定的配送日期内没有需要生成采购计划的订单");
            }
            else {
                throw new IllegalArgumentException("今天没有需要生成采购计划的订单");
            }
        }
        //创建一个Map对象，用于存放TbPurchase对象
        Map<String, TbPurchase> tbPurchaseMap = new HashMap<String, TbPurchase>();
        //创建一个List对象，用于存放订单号
        List<String> orderNoList = new ArrayList<String>();
        //生成一个采购单号
        String purchaseCode = DateUtils.getDateTimeString();
        //遍历purchaseModelList
        for (OrderPurchaseModel purchaseModel : purchaseModelList) {
            //如果tbPurchaseMap中不存在purchaseModel的itemCode，则创建一个TbPurchase对象，并存入tbPurchaseMap中
            if (tbPurchaseMap.get(purchaseModel.getItemCode()) == null) {
                TbPurchase tbPurchase = new TbPurchase();
                tbPurchase.setPurchaseCode(purchaseCode);
                tbPurchase.setCreateDate(mybatisDao.getSysdate());
                tbPurchase.setPurchaseStatus(0);
                tbPurchase.setItemCode(purchaseModel.getItemCode());
                tbPurchase.setTotal(purchaseModel.getTotalItemQty());
                tbPurchase.setTotalWeight(purchaseModel.getTotalWeight());
                tbPurchaseMap.put(purchaseModel.getItemCode(), tbPurchase);
            }
            //否则，将purchaseModel的totalItemQty和totalWeight累加到tbPurchaseMap中对应的TbPurchase对象的total和totalWeight中
            else {
                BigDecimal total = tbPurchaseMap.get(purchaseModel.getItemCode()).getTotal().add(purchaseModel.getTotalItemQty());
                BigDecimal totalWeight = tbPurchaseMap.get(purchaseModel.getItemCode()).getTotalWeight().add(purchaseModel.getTotalWeight());
                tbPurchaseMap.get(purchaseModel.getItemCode()).setTotal(total);
                tbPurchaseMap.get(purchaseModel.getItemCode()).setTotalWeight(totalWeight);
            }
            //将purchaseModel的orderNo存入orderNoList中
            orderNoList.add(purchaseModel.getOrderNo());
        }
        //遍历tbPurchaseMap，将TbPurchase对象插入数据库
        for (TbPurchase tbPurchase : tbPurchaseMap.values()) {
            mybatisDao.insert(tbPurchase);
        }
        //去除重复的订单号
        HashSet h = new HashSet(orderNoList);
        orderNoList.clear();
        orderNoList.addAll(h);
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderStatus("2");//待采购
        TbOrderExample tbOrderExample = new TbOrderExample();
        tbOrderExample.createCriteria()
                .andOrderStatusEqualTo("1")
                .andOrderNoIn(orderNoList);
        mybatisDao.updateByExampleSelective(tbOrder, tbOrderExample);
        for (String orderNo : orderNoList) {
            TbOrderRelation tbOrderRelation = new TbOrderRelation();
            tbOrderRelation.setRefType("ORDER_PURCHASE_CODE");
            tbOrderRelation.setOrderNo(orderNo);
            tbOrderRelation.setRefValue(purchaseCode);
            mybatisDao.insert(tbOrderRelation);
        }
    }

    @Transactional
    public void updatePurchaseStatus(Integer id, Integer purchaseStatus) {
        TbPurchaseExample tbPurchaseExample = new TbPurchaseExample();
        tbPurchaseExample.createCriteria().andIdEqualTo(id);
        TbPurchase tbPurchase = new TbPurchase();
        tbPurchase.setPurchaseStatus(purchaseStatus);
        mybatisDao.updateOneByExampleSelective(tbPurchase, tbPurchaseExample);
    }

    /**
     * 删除采购单
     *
     * @param id
     */
    public void deletePurchase(Integer id) {
        mybatisDao.deleteByPrimaryKey(TbPurchase.class, id);
    }

}
