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

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.dao.CustomerDiningRecordDAO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.JwtUtil2;
import com.jpsoft.shinestar.modules.common.utils.WechatMessageUtil;
import com.jpsoft.shinestar.modules.workflow.entity.ProcinstActUser;
import com.jpsoft.shinestar.modules.workflow.entity.ProcinstActivity;
import com.jpsoft.shinestar.modules.workflow.service.ProcinstActUserService;
import com.jpsoft.shinestar.modules.workflow.service.ProcinstActivityService;
import com.jpsoft.shinestar.modules.workflow.service.ProcinstService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 墨鱼_mo
 * @date 2021-5-24 14:04
 */
@Transactional
@Component(value = "customerDiningRecordService")
@Slf4j
public class CustomerDiningRecordServiceImpl implements CustomerDiningRecordService {

    @Resource(name = "customerDiningRecordDAO")
    private CustomerDiningRecordDAO customerDiningRecordDAO;

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

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private ProcinstService procinstService;

    @Autowired
    private ProcinstActivityService procinstActivityService;

    @Autowired
    private ProcinstActUserService procinstActUserService;

    @Autowired
    private PersonInfoService personInfoService;


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

    @Override
    public int insert(CustomerDiningRecord model) {
        // TODO Auto-generated method stub
        //model.setId(UUID.randomUUID().toString());

        return customerDiningRecordDAO.insert(model);
    }

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

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

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

        return count > 0 ? true : false;
    }

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

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

        return page;
    }

    @Override
    public String customerDiningSubmit(PersonPopedom personPopedom, String customerCompany, String reason, Integer customerNum, Integer accompanyNum, String diningTime, String diningName, String diningFee, String formId,String ids,String draft) throws Exception {


        CustomerDiningRecord customerDiningRecord = new CustomerDiningRecord();
        if(StringUtils.isNotEmpty(ids)){
            customerDiningRecord=customerDiningRecordDAO.get(ids);

        }else{
            customerDiningRecord = new CustomerDiningRecord();
            customerDiningRecord.setId(UUID.randomUUID().toString());
        }

        customerDiningRecord.setPersonPopedomId(personPopedom.getId());
        customerDiningRecord.setCompanyId(personPopedom.getCompanyId());
        customerDiningRecord.setCustomerCompany(customerCompany);
        customerDiningRecord.setReason(reason);
        customerDiningRecord.setCustomerNum(customerNum);
        customerDiningRecord.setAccompanyNum(accompanyNum);
        customerDiningRecord.setDiningTime(DateUtil.parse(diningTime));
        customerDiningRecord.setDiningName(diningName);
        customerDiningRecord.setDiningFee(new BigDecimal(diningFee));
        customerDiningRecord.setStatus("-99");
        customerDiningRecord.setCreateTime(new Date());

        if(StringUtils.isNotEmpty(ids)){
            update(customerDiningRecord);
        }else {
            insert(customerDiningRecord);
        }

        if ("1".equals(draft)) {
            String procinstId = procinstService.addProcInst(customerDiningRecord.getId(), "接待进餐", formId, personPopedom, null,null,null);

            customerDiningRecord.setProcinstId(procinstId);
            customerDiningRecord.setStatus("0");
            update(customerDiningRecord);

            ProcinstActivity procinstActivity = procinstActivityService.findByActivityIndexAndProcinstId(1, procinstId);

            if (procinstActivity != null) {
                List<ProcinstActUser> procinstActUserList = procinstActUserService.findByProcinstActivityIdActionType(procinstActivity.getId(), "0", "1");
                if (procinstActUserList.size() > 0) {
                    for (ProcinstActUser procinstActUser : procinstActUserList) {

                        try {
                            PersonInfo personInfo = personInfoService.get(Long.parseLong(procinstActUser.getUserId()));

                            if (StringUtils.isNotBlank(personInfo.getOpenId())) {
                                //提交人
                                PersonInfo personInfo1 = personInfoService.get(personPopedom.getPersonId());
                                String accessToken = JwtUtil2.createToken(jwtSecret, personInfo.getId() + "", DateTime.now().plusHours(30 * 24).toDate());
                                CustomerDiningRecord finalCustomerDiningRecord = customerDiningRecord;
                                new Thread(() -> {
                                    WechatMessageUtil.sendEvenMessage(personInfo.getOpenId(), "有一条新的接待进餐信息待审核", personInfo1.getName(), com.jpsoft.shinestar.modules.common.utils.StringUtils.getApprovalNo(), "前往处理", wxConfig.getPortalUrl() + "xsy/approval/infosp?id=" + finalCustomerDiningRecord.getId() + "&procinstActUserId=" + procinstActUser.getId() + "&formId=" + formId + "&token=" + accessToken, wxConfig.getAppId(), wxConfig.getAppSecret());
                                }).start();
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                    }
                }
            }

        }


        return customerDiningRecord.getId();
    }
}
