package com.iformall.controller;

import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.PushLimit;
import com.iformall.domain.po.WxCUserBasicInfo;
import com.iformall.domain.po.WxMsg;
import com.iformall.domain.po.WxMsgConfig;
import com.iformall.enums.EnumMsgSend;
import com.iformall.enums.EnumMsgStatus;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxMsgConfigMapper;
import com.iformall.service.PushLimitService;
import com.iformall.service.WxCUserTagsService;
import com.iformall.service.WxMsgService;
import com.iformall.utils.Constant;
import com.iformall.utils.DateUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

/**
 * @author gongbiao
 */
@RestController
@RequestMapping("wxMsg")
public class WxMsgController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMsgService wxMsgService;

    @Autowired
    WxMsgConfigMapper wxMsgConfigMapper;

    @Autowired
    WxCUserTagsService wxCUserTagsService;

    @Autowired
    PushLimitService pushLimitService;

    @ApiOperation("分页列表接口")
    @GetMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    public ResultData list(@ModelAttribute WxMsg wxMsg, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxMsgController::list");
        if (null == wxMsg) wxMsg = new WxMsg();
        wxMsg.setTenantId(getTenantId());
        //wxMsg.setWay(EnumSendWay.TAG.getCode());
        wxMsg.setSortColumns(WxMsg.Field.Createtime_DESC);
        final PageInfo<WxMsg> page = wxMsgService.listAsPage(wxMsg, pageNum, pageSize);
        return new ResultData(page);
    }

    @ApiOperation("新增接口")
    @PostMapping("add")
    public ResultData add(@RequestBody WxMsg wxMsg) {
        logger.debug("[" + getIpAddr() + "] WxMsgController::add");
        //不是草稿检验疲劳度
        if (!wxMsg.getStatus().equals(EnumMsgStatus.MSG_STATUS_DRAFT.getCode())) {
            if (wxMsg.getIsright().equals(EnumMsgSend.MSG_SEND_IMMEDIATELY.getCode())) {
                try {
                    pushLimitService.checkSendTime(getTenantId());
                } catch (MallinkException e) {
                    logger.error(e.getMessage());
                    return new ResultData(e.getErrorCode(), e.getMessage());
                }
            } else {
                PushLimit pushLimit = pushLimitService.getPushLimit(getTenantId());
                String sendtime = wxMsg.getSendtime();
                Date date = DateUtils.stringToDate(sendtime, "yyyy-MM-dd HH:mm:ss");
                boolean isInDate = DateUtils.isInDate(date, pushLimit.getTimeStart(), pushLimit.getTimeEnd());
                if (!isInDate) {
                    return new ResultData(ErrorCode.PUSH_LIMIT_NOT_INRANG);
                }
            }

            if(wxMsg.getId()!=null){
                //如果不是草稿必然之前状态是草稿，删除
                wxMsgService.deleteById(wxMsg.getId());
            }

        }
        wxMsg.setTenantId(getTenantId());
        //1、手机多条以逗号分隔，直接通过实体得到wxmsg.getphones
        //2、通过标签
        String phones = wxMsg.getPhones();
        String label = wxMsg.getLabel();
        if (!phones.equals("") && !label.equals("")) {//两种方式只能选其一
            return new ResultData(ErrorCode.MSG_SEND_WAY_CHOOSE_ERROR);
        }

        if (phones.equals("")) {//没有手工输入手机号时解析标签,有，继续流转
            phones = parselabel(wxMsg.getTenantId(), wxMsg);
            if (phones.equals("")) {//解析之后手机号依然不存在时返回
                return new ResultData(ErrorCode.MSG_NO_VALID_PHONE);
            }
        }

        //保证手机号惟一
        String[] phoneSplit = phones.split(",");
        Set<String> phoneSet = new HashSet<>();
        for (String phone : phoneSplit) {
            phoneSet.add(phone);
        }
        wxMsg.setExpectSendNumber(phoneSet.size());//预计发送数量
        StringBuffer sb = new StringBuffer();
        for (String phone : phoneSet) {
            sb.append(phone).append(",");
        }
        wxMsg.setPhones(sb.deleteCharAt(sb.length() - 1).toString());

        //从短信配置中查询密钥 bid 等信息
        WxMsgConfig wxMsgConfig = new WxMsgConfig();
        wxMsgConfig.setTenantId(wxMsg.getTenantId());
        List<WxMsgConfig> wxMsgConfigs = wxMsgConfigMapper.findList(wxMsgConfig);
        if (wxMsgConfigs.size() == 0) return new ResultData(ErrorCode.MSG_SERVER_NOT_FIND, "您还未接入短信运营商，请联系平台管理员");
        wxMsgConfig = wxMsgConfigs.get(0);

        if (wxMsgConfig.getRemains() == 0) {
            logger.info("短信数量为0");
            return new ResultData(ErrorCode.MSG_SUM_ZERO);
        }

        if (wxMsgConfig.getRemains() < wxMsg.getExpectSendNumber()) {
            logger.info("短信数量不足");
            return new ResultData(ErrorCode.MSG_SUM_INSUFFICENT);
        }
        wxMsgService.saveOrUpdate(wxMsg, wxMsgConfig);
        return new ResultData();
    }

    private String parselabel(String tenantId, WxMsg wxmsg) {
        String label = wxmsg.getLabel();
        String[] arys = label.split(",");
        List<Long> tagids = new ArrayList<>();
        for (int i = 0; i < arys.length; i++) {
            tagids.add(Long.parseLong(arys[i]));
        }
        List<WxCUserBasicInfo> list = wxCUserTagsService.findByTag(tenantId, tagids);

        StringBuilder sb = new StringBuilder();
        if (list.size() > 0) {
            for (WxCUserBasicInfo cUserInfo : list) {
                sb.append(cUserInfo.getPhone()).append(",");
            }
            return sb.toString();
        }
        return "";
    }

    @ApiOperation("根据id删除接口")
    @GetMapping("/del")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    public ResultData delete(Long id) {
        logger.debug("[" + getIpAddr() + "] WxMsgController::delete");
        wxMsgService.deleteById(id);
        return new ResultData(Result.SUCCESS, "删除成功", null);
    }

    @ApiOperation("根据id查询接口")
    @GetMapping("/findById")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    public ResultData findById(Long id) {
        logger.debug("[" + getIpAddr() + "] WxMsgController::findById");
        WxMsg wxMsg = wxMsgService.getById(id);
        String label = wxMsg.getLabel();
        if (label != null && !label.isEmpty()) {
            String[] arys = label.split(",");
            List<Long> tagids = new ArrayList<>();
            for (int i = 0; i < arys.length; i++) {
                tagids.add(Long.parseLong(arys[i]));
            }
            wxMsg.setTagsList(wxCUserTagsService.findTagList(getTenantId(), tagids));
        }
        return new ResultData(wxMsg);
    }


    @RequestMapping("/excleupload")
    public ResultData excleupload(@RequestParam("file") MultipartFile file) {
        logger.debug("[" + getIpAddr() + "] WxMsgController::excleupload");
        if (file.isEmpty()) {
            return new ResultData(Result.SUCCESS, "上传文件不能为空");
        }

        String filename = UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        File path = new File(Constant.fileDirectory);
        if (!path.exists()) {
            path.mkdirs();
        }
        String filepath = Constant.fileDirectory + File.separator + filename;
        try {
            FileOutputStream out = new FileOutputStream(new File(filepath));
            IOUtils.write(file.getBytes(), out);
            IOUtils.closeQuietly(out);
        } catch (Exception e) {
            return new ResultData(Result.ERROR, "上传失败");
        }

        return new ResultData(Result.SUCCESS, "上传成功", filepath);
    }

}
