package com.uas.platform.b2b.erp.service.impl;

import com.uas.platform.b2b.core.util.ThreadUtils;
import com.uas.platform.b2b.dao.EnterpriseDao;
import com.uas.platform.b2b.dao.ProductDao;
import com.uas.platform.b2b.dao.PurchaseOrderAllDao;
import com.uas.platform.b2b.erp.dao.AutOrderDao;
import com.uas.platform.b2b.erp.dao.AutOrderDetailDao;
import com.uas.platform.b2b.erp.dao.KeywordAliasDao;
import com.uas.platform.b2b.erp.model.AutOrder;
import com.uas.platform.b2b.erp.model.AutOrderDetail;
import com.uas.platform.b2b.erp.model.KeywordAlias;
import com.uas.platform.b2b.erp.service.AutOrderService;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.Product;
import com.uas.platform.b2b.model.PurchaseOrderAll;
import com.uas.platform.b2b.model.PurchaseOrderAllItem;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.Status;
import org.apache.axis.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自动生成订单
 *
 * Created by hejq on 2018-05-04.
 */
@Service
public class AutOrderServiceImpl implements AutOrderService {

    @Autowired
    private AutOrderDao autOrderDao;

    @Autowired
    private AutOrderDetailDao detailDao;

    @Autowired
    private KeywordAliasDao keywordAliasDao;

    @Autowired
    private EnterpriseDao enterpriseDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private PurchaseOrderAllDao orderAllDao;

    /**
     * 企业类型
     */
    private final String ENTERPRISE_TYPE = "enterprise";

    /**
     * 币别类型
     */
    private final String CURRENCY_TYPE = "currency";

    /**
     * 数字正则
     */
    private final String NUMBER_REG = "[^0-9]";

    /**
     * 用户类型
     */
    private final String USER_TYPE = "user";

    /**
     * 中文年
     */
    private final String YEAR_CH_CHARACTER = "年";

    /**
     * 中文月
     */
    private final String MONTH_CH_CHARACTER = "月";

    /**
     * 中文日
     */
    private final String DAY_CH_CHARACTER = "日";


    /**
     * 保存订单信息
     *
     * @param orderList 订单信息
     */
    @Override
    public void saveOrder(List<AutOrder> orderList) {
        if (!CollectionUtils.isEmpty(orderList)) {
            for (AutOrder order : orderList) {
                order.setStatus(Status.TOBE_HANDLE.value());
                order.setDate(new Date(System.currentTimeMillis()));
                order =  autOrderDao.save(order);
                if (!CollectionUtils.isEmpty(order.getDetails())) {
                    for (AutOrderDetail detail : order.getDetails()) {
                        detail.setPuId(order.getId());
                        detail.setDate(new Date(System.currentTimeMillis()));
                    }
                    detailDao.save(order.getDetails());
                    // 转成平台的单据
                    covertToSaleOrders(order);
                }
            }
        }
    }

    /**
     * 生成平台的单据
     *
     * @param autOrder 订单主表
     */
    private void covertToSaleOrders(final AutOrder autOrder) {
        ThreadUtils.task(new Runnable() {
            @Override
            public void run() {
                try {
                    PurchaseOrderAll order = coverToPurchase(autOrder);
                    orderAllDao.save(order);
                    AutOrder order1 = autOrderDao.findOne(order.getAuId());
                    order1.setToDate(new Date(System.currentTimeMillis()));
                    autOrderDao.save(order1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }).run();
    }

    /**
     * 解析的订单数据转换成平台的订单数据
     *
     * @param autOrder 解析的订单数据
     * @return
     */
    private PurchaseOrderAll coverToPurchase(AutOrder autOrder) throws ParseException {
        PurchaseOrderAll order = new PurchaseOrderAll();
        order.setCode(autOrder.getPu_code());
        order.setDate(new Date(System.currentTimeMillis()));
        order.setSendStatus((short) Status.NOT_UPLOAD.value());
        order.setStatus((short) Status.NOT_REPLY.value());
        order.setShipAddress(autOrder.getPu_shipaddresscode());
        order.setEnd(Constant.NO);
        order.setDisplay(Constant.NO);
        order.setPrint(Constant.NO);
        order.setCustPrint(Constant.NO);
        order.setReply(Constant.NO);
        order.setFilepath(autOrder.getPu_filepath());
        order.setAuId(autOrder.getId());
        KeywordAlias en_alias = keywordAliasDao.findByTypeAndAlias(ENTERPRISE_TYPE, autOrder.getEn_name());
        if (null != en_alias) {
            order.setEnUU(Long.valueOf(en_alias.getValue()));
            order.setCop(en_alias.getName());
            Enterprise enterprise = enterpriseDao.findOne(Long.valueOf(en_alias.getValue()));
            order.setUserUU(enterprise.getEnAdminuu());
        }
        KeywordAlias cu_alias = keywordAliasDao.findByTypeAndAlias(CURRENCY_TYPE, autOrder.getPu_currency());
        if (null != cu_alias) {
            order.setCurrency(cu_alias.getValue());
        }
        KeywordAlias ve_alias = keywordAliasDao.findByTypeAndAlias(ENTERPRISE_TYPE, autOrder.getVe_name());
        if (null != ve_alias) {
            order.setVendUU(Long.valueOf(ve_alias.getValue()));
            order.setReceiveName(ve_alias.getName());
        }
        Pattern p = Pattern.compile(NUMBER_REG);
        Matcher m = p.matcher(autOrder.getPu_date());
        String rate = m.replaceAll("").trim();
        order.setRate(StringUtils.isEmpty(rate) ? null : Float.valueOf(rate));
        KeywordAlias u_alias = keywordAliasDao.findByTypeAndAlias(USER_TYPE, autOrder.getEm_name());
        if (null != u_alias) {
            order.setUserUU(Long.valueOf(u_alias.getValue()));
        }
        Set<PurchaseOrderAllItem> items = new HashSet<>();
        if (!CollectionUtils.isEmpty(autOrder.getDetails())) {
            int i = 1;
            for (AutOrderDetail detail : autOrder.getDetails()) {
                items.add(coverToItem(detail, i, order.getEnUU()));
                i++;
            }
        }
        order.setOrderItems(items);
        return order;
    }

    /**
     * 将解析订单明细转成平台采购订单明细
     *
     * @param detail 解析出来的采购订单明细
     * @param i 序号
     * @param enUU 企业UU
     * @return
     */
    private PurchaseOrderAllItem coverToItem(AutOrderDetail detail, int i, Long enUU) throws ParseException {
        PurchaseOrderAllItem item = new PurchaseOrderAllItem();
        item.setStatus((short) Status.NOT_REPLY.value());
        item.setErpDate(new Date(System.currentTimeMillis()));
        item.setAudId(detail.getId());
        Pattern p = Pattern.compile(NUMBER_REG);
        Matcher m = p.matcher(detail.getPd_qty());
        String qty = m.replaceAll("").trim();
        item.setQty(StringUtils.isEmpty(qty) ? 0 : Double.valueOf(qty));
        item.setNumber(StringUtils.isEmpty(detail.getPd_detno()) ? (short) i : Short.valueOf(detail.getPd_detno()));
        Matcher ma = p.matcher(detail.getPd_rate());
        String taxtRate = ma.replaceAll("").trim();
        item.setTaxrate(StringUtils.isEmpty(taxtRate) ? null : Float.valueOf(taxtRate));
        List<Product> productList = productDao.findByEnUUAndCode(enUU, detail.getPd_prodcode());
        if (!CollectionUtils.isEmpty(productList)) {
            item.setProductId(productList.get(0).getId());
        }
        Matcher pr = p.matcher(detail.getPd_price());
        String price = pr.replaceAll("").trim();
        item.setPrice(StringUtils.isEmpty(price) ? null : Double.valueOf(price));
        item.setDelivery(matchTime(detail.getPd_delivery()));
        return item;
    }

    /**
     * 处理时间格式
     *
     * @param delivery 解析订单中的明细交期
     * @return
     */
    private Date matchTime(String delivery) throws ParseException {
        if (!StringUtils.isEmpty(delivery)) {
            delivery = delivery.trim();
            String TIME_PATTERN_1 = "\\d{4}-\\d{2}-\\d{2}";
            String TIME_PATTERN_2 = "\\d{4}\\d{2}\\d{2}";
            String TIME_PATTERN_3 = "\\d{4}/\\d{2}/\\d{2}";
            if (delivery.matches(TIME_PATTERN_1)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                return sdf.parse(delivery);
            } else if (delivery.matches(TIME_PATTERN_2)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");
                return sdf.parse(delivery);
            } else if (delivery.contains(YEAR_CH_CHARACTER) || delivery.contains(MONTH_CH_CHARACTER) || delivery.contains(DAY_CH_CHARACTER)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年mm月dd");
                return sdf.parse(delivery);
            } else if (delivery.matches(TIME_PATTERN_3)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/mm/dd");
                return sdf.parse(delivery);
            }

        }
        return null;
    }
}
