package com.boman.web.core.service.save;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.redis.service.RedisService;
import com.boman.domain.GenTableColumn;
import com.boman.domain.constant.FormDataConstant;
import com.boman.domain.constant.TableNameConst;
import com.boman.domain.dto.AjaxResult;
import com.boman.domain.dto.WxMsgDto;
import com.boman.system.api.RemoteUserService;
import com.boman.domain.dto.RowResult;
import com.boman.web.core.mapper.StandardMapper;
import com.boman.web.core.utils.ColumnUtils;
import com.boman.web.core.utils.IdUtils;
import com.boman.web.core.utils.SendSmsUtils;
import com.boman.wechat.api.RemoteWechatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;

import static com.boman.common.core.utils.obj.ObjectUtils.*;
import static com.boman.web.core.utils.ColumnUtils.*;

/**
 * @author shiqian
 * @description
 * @date 2021年03月22日 11:25
 **/
@Component
public class BaseSaveServiceImpl implements IBaseSaveService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseSaveServiceImpl.class);

    @Autowired
    private StandardMapper mapper;
    @Resource
    private RedisService redisService;
    @Resource
    private RemoteWechatService remoteWechatService;

    @Resource
    private RemoteUserService remoteUserService;

    /**
     * 功能描述: 保存一行
     *
     * @param tableName  tableName
     * @param commitData commitData
     * @return com.boman.system.common.RowResult
     */
    @Override
    public RowResult insertRow(String tableName, JSONObject commitData) {
        int ret = mapper.insert(tableName, commitData);
        if (ret > 0) {
            LOGGER.info("保存成功，保存的数据为：{}", commitData);
            commitData.put(FormDataConstant.SUCCESS_CNT, ret);
            return RowResult.ok("保存成功", commitData);
        }

        return RowResult.error("失败");
    }

    @Override
    public int insertRelList(String tableName, List<JSONObject> dataList) {
        requireNonNull(tableName, "insertRelList tableName is empty");
        requireNonNull(dataList, "insertRelList dataList is empty");

        String pkName = IdUtils.getPkName(tableName);

        for (JSONObject data : dataList) {
            Long maxId = IdUtils.getMaxId(tableName, pkName);
            data.put(TableNameConst.ID, maxId);
        }

        return mapper.insertList(tableName, dataList);
    }

    /**
     * 功能描述: 通用insertList
     *
     * @param tableName tableName
     * @param dataList  dataList
     * @return int
     */
    @Override
    public List<RowResult> insertList(String tableName, List<JSONObject> dataList) {
        requireNonNull(tableName, "insertList tableName is empty");
        requireNonNull(dataList, "insertList datList is empty");

        List<RowResult> rowResults = new ArrayList<>(dataList.size());
        List<GenTableColumn> columns = ColumnUtils.getColumnList(tableName);
        String pkName = IdUtils.getPkName(columns);
        List<Long> receiveUserIds = new ArrayList<>();
        Map<String, Object> messageInfo = new HashMap<>();
        for (JSONObject commitData : dataList) {
            Long maxId = IdUtils.getMaxId(tableName, pkName);
            packUpdateByAndTime(columns, commitData, new Timestamp(System.currentTimeMillis()), true);
            // 处理默认值
            handlerDefaultValue(commitData, columns);
            // 如果有单据、按照单据编号规则
            buildBillRule(tableName, commitData, columns);
            commitData.put(pkName, maxId);
            rowResults.add(insertRow(tableName, commitData));
            if ("urge_read_message".equals(tableName)) {
                receiveUserIds.add(commitData.getLong("receive_user_id"));
            }
        }
        messageInfo.put("thing1", dataList.get(0).getString("message_title"));
        messageInfo.put("thing2", dataList.get(0).getString("send_user_name"));
        messageInfo.put("thing4", dataList.get(0).getString("message_title"));
        messageInfo.put("thing5", dataList.get(0).getString("send_user_name"));
        // 获取发文相关信息
        if ("urge_read_message".equals(tableName)) {
            WxMsgDto wxMsgDto = new WxMsgDto();
            wxMsgDto.setIds(receiveUserIds);
            wxMsgDto.setParams(messageInfo);
            LOGGER.info("收文人id:{}, 发送数据： {}", receiveUserIds, messageInfo);
            remoteWechatService.pushMsg(wxMsgDto);

            List<Long> userIds = new ArrayList<>(new HashSet(receiveUserIds));
            AjaxResult userList = remoteUserService.selectUserByIds(userIds);
            List<Map<String, Object>> users = (List<Map<String, Object>>) userList.get("data");
            String accessKeyId = "LTAI5tNA2fcBJH6EWRH6Pxr6";
            String accessKeySecret = "5WdaPEOvC3u9LC7pwy2DQ9pgmJvgUr";
            String signName = "";
            String templateCode = "";
            //自定义的模板变量
            String templateParam = "";
            StringBuilder sb = new StringBuilder();
            if (users != null && users.size() > 0) {
                for (Map<String, Object> user : users) {
                    String phoneNumber = user.get("phonenumber").toString();
                    if (StringUtils.isNotBlank(phoneNumber)) {
                        sb.append(phoneNumber).append(",");
                    }
                }
            }
            if (StringUtils.isNotBlank(sb.toString())) {
                try {
                    String phoneNumbers = sb.toString().substring(0, sb.toString().length() - 1);
                    SendSmsUtils.sendSms(phoneNumbers, templateParam, accessKeyId, accessKeySecret, signName, templateCode);
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
        }
        return rowResults;
    }
}
