package com.jpsoft.shinestar.modules.business.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;

import cn.hutool.core.date.DateUtil;
import cn.hutool.db.sql.Order;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.dao.CompanyGoodInfoDAO;
import com.jpsoft.shinestar.modules.base.dao.GoodsInfoDAO;
import com.jpsoft.shinestar.modules.base.dao.OrderInfoDAO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.dao.BillPushGoodsDAO;
import com.jpsoft.shinestar.modules.business.dto.BillPushDetailDTO;
import com.jpsoft.shinestar.modules.business.dto.BillPushGoodsDTO;
import com.jpsoft.shinestar.modules.business.entity.BillPushGoods;
import com.jpsoft.shinestar.modules.common.utils.JwtUtil2;
import com.jpsoft.shinestar.modules.common.utils.StringUtils;
import com.jpsoft.shinestar.modules.common.utils.WechatMessageUtil;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.jpsoft.shinestar.modules.business.dao.BillPushDAO;
import com.jpsoft.shinestar.modules.business.entity.BillPush;
import com.jpsoft.shinestar.modules.business.service.BillPushService;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.github.pagehelper.PageHelper;

@Transactional
@Component(value="billPushService")
public class BillPushServiceImpl implements BillPushService {

    @Value("${jwt.secret}")
    private String jwtSecret;


    @Autowired
    private WxConfig wxConfig;

    @Resource(name = "billPushDAO")
    private BillPushDAO billPushDAO;

	@Resource(name="orderInfoDAO")
	private OrderInfoDAO orderInfoDAO;

	@Resource(name="billPushGoodsDAO")
	private BillPushGoodsDAO billPushGoodsDAO;

	@Resource(name="goodsInfoDAO")
	private GoodsInfoDAO goodsInfoDAO;

	@Resource(name="companyGoodInfoDAO")
	private CompanyGoodInfoDAO companyGoodInfoDAO;

    @Autowired
    private CompanyPaymentInfoService companyPaymentInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonRoleIconService personRoleIconService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private PersonPopedomIconService personPopedomIconService;

    @Autowired
    private IconInfoService iconInfoService;

    @Autowired
	private CompanyInfoService companyInfoService;

	@Autowired
	private CheckinInfoService checkinInfoService;


	@Override
	public BillPush get(String id) {
		// TODO Auto-generated method stub
		return billPushDAO.get(id);
	}

	@Override
	public int insert(BillPushDetailDTO dto,String subject) {
		// TODO Auto-generated method stub
		//model.setId(UUID.randomUUID().toString());

		int affectCount = 0;

		BillPush billPush = new BillPush();
		billPush.setId(UUID.randomUUID().toString());
		billPush.setName(dto.getName());
		billPush.setBak(dto.getBak());
		billPush.setInvoiceType(dto.getInvoiceType());
		billPush.setCollectionAccountId(dto.getCollectionAccountId().toString());

		String checkinInfoId = dto.getCheckinInfoId();
		CheckinInfo checkinInfo = checkinInfoService.get(checkinInfoId);

		if(checkinInfo!=null){
			billPush.setCompanyId(checkinInfo.getCompanyId());
		}

		billPush.setPayee(dto.getPayee());
		billPush.setCheckinInfoId(dto.getCheckinInfoId());

		billPush.setDelFlag(false);
		billPush.setCreateBy(subject);
		billPush.setCreateTime(new Date());
		billPush.setPersonId(dto.getPersonId());
		billPush.setStatus("0");
		billPush.setIsOpenWechat(dto.getIsOpenWechat());
		billPush.setIsOpenAlipay(dto.getIsOpenAlipay());
		billPush.setInvoiced(false);

		int count = billPushDAO.insert(billPush);

		int bodyNum = 0;

		if(count>0){
			String goodsId = "";
			String body = "";
			BigDecimal totalFee = BigDecimal.ZERO;

			List<BillPushGoodsDTO> billPushGoodsDTOList = dto.getBillPushGoodsList();

			for (BillPushGoodsDTO billPushGoodsDTO:billPushGoodsDTOList) {
				BillPushGoods billPushGoods = new BillPushGoods();
				billPushGoods.setSortNo(billPushGoodsDTO.getSortNo());
				billPushGoods.setId(UUID.randomUUID().toString());
				billPushGoods.setBillPushId(billPush.getId());
				billPushGoods.setBeginEndTime(billPushGoodsDTO.getBeginDate()+","+billPushGoodsDTO.getEndDate());

				//billPushGoodsDTO实体类的GoodsId为CompanyGoodInfo实体类的ID
				CompanyGoodInfo companyGoodInfo = companyGoodInfoDAO.get(billPushGoodsDTO.getGoodsId());

				//将本次收款单单价保存到租户对应收费项中
				companyGoodInfo.setUnitPrice(billPushGoodsDTO.getUnitPrice());
				companyGoodInfo.setUpdateTime(new Date());
				companyGoodInfo.setUpdateBy(subject);
				companyGoodInfoDAO.update(companyGoodInfo);

				GoodsInfo goodsInfo = goodsInfoDAO.get(companyGoodInfo.getGoodsId());

				if(goodsInfo!=null){
					billPushGoods.setGoodsId(goodsInfo.getId());
					body += goodsInfo.getName()+",";
					bodyNum++;

					JSONObject jsonObject = new JSONObject();

					String start = "";
					String end = "";
					String total = "";
					if(goodsInfo.getType().equals("7")){
						 start = billPushGoodsDTO.getNumStr();
						 end = billPushGoodsDTO.getNumStr2();
						 total = billPushGoodsDTO.getNumStr3();
					}
					else{
						total = billPushGoodsDTO.getNumStr3();
					}
					jsonObject.put("start",start);
					jsonObject.put("end",end);
					jsonObject.put("total",total);
					billPushGoods.setNumStr(jsonObject.toString());
				}

				BigDecimal feeDecimal = billPushGoodsDTO.getTotalFee();
				String standard = billPushGoodsDTO.getStandard();
				if(feeDecimal!=null) {
					totalFee = totalFee.add(feeDecimal);
				}

				JSONObject jsonObject = new JSONObject();
				jsonObject.put("standard",standard);
				jsonObject.put("unitPrice", billPushGoodsDTO.getUnitPrice());
				jsonObject.put("totalFee",feeDecimal);

				billPushGoods.setDetails(jsonObject.toString());

				billPushGoods.setDelFlag(false);
				billPushGoods.setCreateBy(subject);
				billPushGoods.setCreateTime(new Date());

				int billPushGoodsCount = billPushGoodsDAO.insert(billPushGoods);

				if(billPushGoodsCount>0){
					CompanyGoodInfo companyGoodInfo1 = companyGoodInfoDAO.get(billPushGoodsDTO.getGoodsId());

					GoodsInfo goodsInfo2 = goodsInfoDAO.get(companyGoodInfo1.getGoodsId());

					goodsId += goodsInfo2.getId()+",";
				}
			}

			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setId(UUID.randomUUID().toString());
			if(StringUtils.isNotEmpty(body)){
				body = body.substring(0,body.lastIndexOf(","));
				orderInfo.setBody(body);
			}

			if(StringUtils.isNotEmpty(goodsId)){
				goodsId = goodsId.substring(0,goodsId.lastIndexOf(","));
				orderInfo.setGoodsId(goodsId);
			}

			orderInfo.setTotalFee(totalFee);
			orderInfo.setPayStatus(10);
			orderInfo.setOutOrderNo(StringUtils.getOutTradeNo());
			orderInfo.setStatus("1");
			orderInfo.setDelFlag(false);
			orderInfo.setCreateBy(subject);
			orderInfo.setCreateTime(new Date());
			orderInfo.setCompanyId(dto.getCompanyId());

			if(bodyNum>1){
				//多于一个为综合
				orderInfo.setType("10");
			}
			else{
				GoodsInfo goodsInfo = goodsInfoDAO.get(goodsId);
				if(goodsInfo!=null){
					orderInfo.setType(goodsInfo.getType());
				}
			}

			int orderCount = orderInfoDAO.insert(orderInfo);

			if(orderCount>0){
				billPush.setOrderId(orderInfo.getId());
				affectCount = billPushDAO.update(billPush);
			}
		}

		return affectCount;
	}

	@Override
	public int update(BillPush model) {
		// TODO Auto-generated method stub
		return billPushDAO.update(model);
	}

	@Override
	public int delete(String id) {
		// TODO Auto-generated method stub
		return billPushDAO.delete(id);
	}

	@Override
	public boolean exist(String id) {
		// TODO Auto-generated method stub
		int count = billPushDAO.exist(id);

		return count > 0 ? true : false;
	}

	@Override
	public List<BillPush> list() {
		// TODO Auto-generated method stub
		return billPushDAO.list();
	}

	@Override
	public Page<BillPush> pageSearch(Map<String, Object> searchParams, int pageNumber, int pageSize,List<Sort> sortList) {
        Page<BillPush> page = PageHelper.startPage(pageNumber,pageSize).doSelectPage(()->{
            billPushDAO.search(searchParams,sortList);
        });

        return page;
	}

    @Override
    public BillPush findByOrderId(String orderId) {
        return billPushDAO.findByOrderId(orderId);
    }

    @Override
    public void sendAccountRemind(BillPush billPush) {
        if (billPush != null && org.apache.commons.lang3.StringUtils.isNotBlank(billPush.getCollectionAccountId())) {
            OrderInfo orderInfo = orderInfoDAO.get(billPush.getOrderId());
            CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.valueOf(billPush.getCollectionAccountId()));

            if (companyPaymentInfo.getFinancePersonId() != null) {


                //财务人员
                PersonInfo personInfo = personInfoService.get(companyPaymentInfo.getFinancePersonId());

                List<PersonRoleIcon> personRoleIconList = personRoleIconService.findByIconName("账单管理");

                String perosnToken = JwtUtil2.createToken(jwtSecret, personInfo.getId() + "", DateTime.now().plusHours(24 * 30).toDate());

                if (personRoleIconList.size() > 0) {


                    List<PersonPopedom> personPopedomList = personPopedomService.findByPersonIdAndRoleIdList(personInfo.getId(), personRoleIconList);

                    if (personPopedomList.size() > 0) {

                        //发送到账提醒模板消息
                        WechatMessageUtil.sendAccountRemind(personInfo.getOpenId(), "有一笔新的账单已到账", DateUtil.format(orderInfo.getPayTime(), "yyyy-MM-dd HH:mm"), orderInfo.getPayNameStr(), orderInfo.getTotalFee().toString(), orderInfo.getOutOrderNo(), "前往查看", wxConfig.getPortalUrl() + "master/mine/bill/pay?id=" + orderInfo.getId() + "&exchange=1&role_id=" + personPopedomList.get(0) + "&token=" + perosnToken, wxConfig.getAppId(), wxConfig.getAppSecret());
                    }

                } else {
                    PersonPopedomIcon personPopedomIcon = personPopedomIconService.findByPersonIdAndIconName(personInfo.getId(), "账单管理");
                    if (personPopedomIcon != null) {
                        //发送到账提醒模板消息
                        WechatMessageUtil.sendAccountRemind(personInfo.getOpenId(), "有一笔新的账单已到账", DateUtil.format(orderInfo.getPayTime(), "yyyy-MM-dd HH:mm"), orderInfo.getPayNameStr(), orderInfo.getTotalFee().toString(), orderInfo.getOutOrderNo(), "前往查看", wxConfig.getPortalUrl() + "master/mine/bill/pay?id=" + orderInfo.getId() + "&exchange=1&role_id=" + personPopedomIcon.getPersonPopedomId() + "&token=" + perosnToken, wxConfig.getAppId(), wxConfig.getAppSecret());
                    }
                }


            }

        }
    }

	@Override
	public void sendNotPayBillRemind(BillPush billPush) {
		if (billPush != null && org.apache.commons.lang3.StringUtils.isNotBlank(billPush.getCollectionAccountId())) {
			OrderInfo orderInfo = orderInfoDAO.get(billPush.getOrderId());
			CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.valueOf(billPush.getCollectionAccountId()));

			if (companyPaymentInfo.getFinancePersonId() != null) {


				//账单接受人
				PersonInfo person  = personInfoService.get(billPush.getPersonId());
				//账单接受公司
				CompanyInfo companyInfo1 = companyInfoService.get(billPush.getCompanyId());

				//财务人员
				PersonInfo personInfo = personInfoService.get(companyPaymentInfo.getFinancePersonId());

				List<PersonRoleIcon> personRoleIconList = personRoleIconService.findByIconName("账单管理");

				String perosnToken = JwtUtil2.createToken(jwtSecret, personInfo.getId() + "", DateTime.now().plusHours(24 * 30).toDate());


				if (personRoleIconList.size() > 0) {


					List<PersonPopedom> personPopedomList = personPopedomService.findByPersonIdAndRoleIdList(personInfo.getId(), personRoleIconList);

					if (personPopedomList.size() > 0) {

						//发送消息
						WechatMessageUtil.sendEvenMessage(personInfo.getOpenId(), "有一笔超过缴费周期的账单，请查看", companyInfo1.getName()+"-"+person.getName(), billPush.getId().substring(0,5),"前往查看", wxConfig.getPortalUrl() + "master/mine/bill/pay?id=" + orderInfo.getId() + "&exchange=1&role_id=" + personPopedomList.get(0) + "&token=" + perosnToken, wxConfig.getAppId(), wxConfig.getAppSecret());
					}

				} else {
					PersonPopedomIcon personPopedomIcon = personPopedomIconService.findByPersonIdAndIconName(personInfo.getId(), "账单管理");
					if (personPopedomIcon != null) {
						//发送到账提醒模板消息

						WechatMessageUtil.sendEvenMessage(personInfo.getOpenId(), "有一笔超过缴费周期的账单，请查看", companyInfo1.getName()+"-"+person.getName(), billPush.getId().substring(0,5),"前往查看", wxConfig.getPortalUrl() + "master/mine/bill/pay?id=" + orderInfo.getId() + "&exchange=1&role_id=" + personPopedomIcon.getPersonPopedomId() + "&token=" + perosnToken, wxConfig.getAppId(), wxConfig.getAppSecret());
					}
				}


            }

        }
    }
}