package com.willalp.salary.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.StringUtils;
import com.willalp.common.utils.poi.ExcelUtil;
import com.willalp.msg.domain.HsAppUserMsg;
import com.willalp.msg.service.IHsAppUserMsgService;
import com.willalp.push.domain.HsAppPush;
import com.willalp.push.service.IHsAppPushService;
import com.willalp.salary.domain.HsSalarySlip;
import com.willalp.salary.mapper.HsSalarySlipMapper;
import com.willalp.salary.service.IHsSalarySlipService;
import com.willalp.wx.domain.WxMsgTemplateSalarySheet;
import com.willalp.wx.enums.WxTemplateKeyEnum;
import com.willalp.wx.service.WxMsgService;
import com.willalp.wx.utils.WxUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工资条基础Service业务层处理
 *
 * @author willalp
 * @date 2022-07-26
 */
@Service
public class HsSalarySlipServiceImpl extends ServiceImpl<HsSalarySlipMapper, HsSalarySlip> implements IHsSalarySlipService {
    @Resource
    private HsSalarySlipMapper hsSalarySlipMapper;

    @Resource
    private IHsAppPushService pushService;

    @Resource
    private WxMsgService wxMsgService;

    @Resource
    private WxUtils wxUtils;

    @Resource
    private IHsAppUserMsgService userMsgService;

    /**
     * 查询工资条基础列表
     *
     * @param hsSalarySlip 工资条基础
     * @return 工资条基础
     */
    @Override
    public List<HsSalarySlip> selectHsSalarySlipList(HsSalarySlip hsSalarySlip) {
        return hsSalarySlipMapper.selectHsSalarySlipList(hsSalarySlip);
    }

    @Override
    public List<HsSalarySlip> excelList(HsSalarySlip hsSalarySlip) {
        return hsSalarySlipMapper.excelList(hsSalarySlip);
    }

    @Override
    public String importData(List<HsSalarySlip> list, ExcelUtil<HsSalarySlip> util, InputStream is, String fileName) {
        try {
            JSONArray jsonArray = new JSONArray();
            List<HsSalarySlip> dbList = this.selectHsSalarySlipList(null);
            List<HsSalarySlip> saveList = new ArrayList<>();
            List<HsSalarySlip> updateList = new ArrayList<>();
            try {
                //所有数据转换成完整JSON
                jsonArray = util.importExcelToJson(StringUtils.EMPTY, is, 0, 0, 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (0 == list.size()) {
                return "0条有效数据请检查Excel";
            }
            String fileNameStr = fileName.substring(0, fileName.indexOf("."));
            if (jsonArray.size() == list.size()) {
                for (int i = 0; i < list.size(); i++) {
                    List<Object> list1 = Collections.singletonList(jsonArray.get(i));
                    JSONArray jsonArray1 = new JSONArray(list1);
                    list.get(i).setZend(jsonArray1);
                    list.get(i).setPaySlipStatus(String.valueOf(1));
                    list.get(i).setSource(fileNameStr);
                    int isUpdate = 0;
                    for (HsSalarySlip item : dbList) {
                        if (ObjectUtil.isNotEmpty(item) &&
                                ObjectUtil.isNotEmpty(list.get(i))) {
                            //名字
                            if (StringUtils.isNotBlank(item.getUserName()) &&
                                    StringUtils.equals(item.getUserName(), list.get(i).getUserName())) {
                                //日期
                                if (StringUtils.isNotBlank(item.getPayDate()) &&
                                        StringUtils.equals(item.getPayDate(), list.get(i).getPayDate())) {
                                    //文件名
                                    if (StringUtils.isNotBlank(item.getSource()) &&
                                            StringUtils.equals(item.getSource(), list.get(i).getSource())) {
                                        list.get(i).setId(item.getId());
                                        list.get(i).setUpdateTime(new Date());
                                        updateList.add(list.get(i));
                                        isUpdate++;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (isUpdate == 0) {
                        saveList.add(list.get(i));
                    }
                }
            }
            if (0 != saveList.size()) {
                saveOrUpdateBatch(saveList);
            }
            if (0 != updateList.size()) {
                saveOrUpdateBatch(updateList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "工资数据导入失败";
        }
        return "工资数据导入成功";

    }

    @Override
    public void updatePushStatus(String[] ids) {
        List<HsAppPush> pushs = pushService.getOpenIds();
        List<HsSalarySlip> list;
        if (0 != ids.length) {
            list = hsSalarySlipMapper.selectList(new QueryWrapper<HsSalarySlip>()
                    .in("id", ids));
        } else {
            list = hsSalarySlipMapper.selectList(new QueryWrapper<HsSalarySlip>()
                    .eq("pay_slip_status", "1"));
//            hsSalarySlipMapper.updateAllPushStatus();
        }
        if (0 != list.size()) {
            List<HsAppUserMsg> ums = new ArrayList<>();
            list.forEach(iSp -> {
                iSp.setPaySlipStatus("2");
                String userCode = iSp.getUserCode();
                if (StringUtils.isNotBlank(userCode)) {
                    //获取OpenId并推送
                    List<HsAppPush> collect = pushs.stream().filter(p -> StringUtils.isNotBlank(p.getUserNo()) && p.getUserNo().equals(userCode)).collect(Collectors.toList());
                    if (0 != collect.size()) {
                        String pushId = collect.get(0).getPushCid();
                        WxMsgTemplateSalarySheet wxMsgTemplateSalarySheet = new WxMsgTemplateSalarySheet();
                        wxMsgTemplateSalarySheet.setThing2(wxUtils.getFormat(iSp.getUserName()));
                        wxMsgTemplateSalarySheet.setAmount3(wxUtils.getFormat(String.valueOf(iSp.getSalary())));
                        wxMsgTemplateSalarySheet.setTime4(wxUtils.getFormat(iSp.getPayDate()));
                        wxMsgTemplateSalarySheet.setThing5(wxUtils.getFormat("请仔细核对您的工资，如有疑问请联系人事部门"));
                        wxMsgService.sendQRCodeMsg(pushId, wxMsgTemplateSalarySheet, WxTemplateKeyEnum.SALARY_SHEET, false);
                    }
                    //生成消息
                    HsAppUserMsg aum = new HsAppUserMsg();
                    aum.setUserCode(userCode);
                    aum.setMsgType("3");
                    aum.setMsgContent("您的" + iSp.getPayDate() + "工资条已发送，请查看核对");
                    aum.setMsgIsRead("0");
                    aum.setCreateTime(new Date());
                    ums.add(aum);
                }
            });
            if (0 != ums.size()) {
                userMsgService.saveBatch(ums);
            }
            if (0 != list.size()) {
                this.updateBatchById(list);
            }
        }
    }

    @Override
    public boolean updateSalaryJsonData(HsSalarySlip hsSalarySlip) {

        return false;
    }

    @Override
    public JSONArray appGetSalarySlipToUser(String un, String oc) {
        if (StringUtils.isBlank(oc)) {
            throw new BaseException("请验证机构编码");
        } else {
            if ("G00000003".equals(oc)) {
                throw new BaseException("当前为游客模式请切换或绑定机构");
            }
        }
        if (StringUtils.isBlank(un)) {
            throw new BaseException("用户编码不能为空");
        }
        List<HsSalarySlip> list = hsSalarySlipMapper.selectList(new QueryWrapper<HsSalarySlip>()
                .eq("pay_slip_status", "2")
                .eq("user_code", un)
                .last("order by pay_date desc"));
        JSONArray jsonArray = new JSONArray();
        list.forEach(i -> {
            Map<String, Object> map = new HashMap<>();
            map.put("date", i.getSource());
            map.put("data", i.getZend().get(0));
            map.put("fsalary", i.getFsalary());
            jsonArray.add(map);
        });
        return jsonArray;
    }
}
