package com.dxhy.core.controller.mailGather;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.util.UUIDUtils;
import com.dxhy.common.utils.Base64Encoding;
import com.dxhy.common.utils.R;
import com.dxhy.common.vo.UserInfo;
import com.dxhy.core.model.mailGather.EmailMaintainExcel;
import com.dxhy.core.model.mailGather.EmailMaintainVo;
import com.dxhy.core.service.mailGather.EmailMaintainService;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * (EmailMaintain)表控制层
 *
 * @author makejava
 * @since 2023-03-23 08:39:46
 */
@Slf4j
@RestController
@RequestMapping("/emailMaintain")
public class EmailMaintainController extends AbstractController  {
    /**
     * 服务对象
     */
    @Resource
    private EmailMaintainService emailMaintainService;

    /**
     * 分页查询
     *
     * @param pramsMap 筛选条件
     * @return 查询结果
     */
    @PostMapping("/queryByPage")
    public ResponseEntity<R> queryByPage(@RequestBody Map<String, Object> pramsMap) {
        // 入参统一在入口处理
//        pramsMap.put("dbName", getUserInfo().getDbName());
//        List<String> gfshList = new ArrayList<>();
//        if (!"99".equals(pramsMap.get("gfsh")) && pramsMap.get("gfsh") != null && !"".equals(pramsMap.get("gfsh"))) {
//            gfshList.add(pramsMap.get("gfsh").toString());
//        } else {
//            gfshList = UserInfoUtil.getGfshAll(getUserInfo().getOrg());
//            if (gfshList.size() == 0) {
//                return ResponseEntity.ok(R.ok().put("data", ""));
//            }
//        }
        Object deptId = pramsMap.get("deptId");
        if(deptId == null || "".equals(String.valueOf(deptId))){
            return ResponseEntity.ok(R.error("查询参数有误！"));
        }
        if("99".equals(String.valueOf(deptId))){
            pramsMap.put("deptId","");
        }
        UserInfo userInfo = getUserInfo();
        log.debug("用户信息：{}", JSONObject.toJSONString(userInfo));
        String loginname = getUserInfo().getLoginname();
        pramsMap.put("createUser",loginname);
        return ResponseEntity.ok(R.ok().put("data",this.emailMaintainService.queryByPage(pramsMap)));
    }

    /**
     * 新增数据
     *
     * @param emailMaintain 实体
     * @return 新增结果
     */
    @PostMapping("/add")
    public ResponseEntity<R> add(@RequestBody EmailMaintainVo emailMaintain) {
        if(StringUtils.isBlank(emailMaintain.getEmailPassword()) || StringUtils.isBlank(emailMaintain.getEmailAddress()) ){
            return ResponseEntity.ok(R.error("邮箱地址/密码不能为空！"));
        }else {
            String encode = Base64Encoding.encode(emailMaintain.getEmailPassword());
            emailMaintain.setEmailPassword(encode);
        }
        String loginname = getUserInfo().getLoginname();
        emailMaintain.setCreateUser(loginname);

        DynamicContextHolder.push(DbConstant.BASICS_READ);
        EmailMaintainVo vo = new EmailMaintainVo();
        vo.setEmailAddress(emailMaintain.getEmailAddress());
        EmailMaintainVo maintainVo = emailMaintainService.getEmailMaintainVo(vo);
        if(maintainVo != null){
            return ResponseEntity.ok(R.error("邮箱地址已存在！"));
        }
        boolean insert = this.emailMaintainService.insert(emailMaintain);
        if(insert){
            return ResponseEntity.ok(R.ok());
        }
        return ResponseEntity.ok(R.error());
    }

    /**
     * 编辑数据
     *
     * @param emailMaintain 实体
     * @return 编辑结果
     */
    @PostMapping("/edit")
    public ResponseEntity<R> edit(@RequestBody  EmailMaintainVo emailMaintain) {
        if(StringUtils.isBlank(emailMaintain.getEmailPassword()) || StringUtils.isBlank(emailMaintain.getEmailAddress()) ){
            return ResponseEntity.ok(R.error("邮箱地址/密码不能为空！"));
        }else {
            String encode = Base64Encoding.encode(emailMaintain.getEmailPassword());
            emailMaintain.setEmailPassword(encode);
        }
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        EmailMaintainVo vo = new EmailMaintainVo();
        vo.setEmailAddress(emailMaintain.getEmailAddress());
        EmailMaintainVo maintainVo = emailMaintainService.getEmailMaintainVo(vo);
        if(maintainVo != null && maintainVo.getId().equals(emailMaintain.getId())){
            return ResponseEntity.ok(R.error("邮箱地址已存在！"));
        }

        String userId = emailMaintain.getUserId();

        String userName = emailMaintainService.getUserName(userId);
        if(StringUtils.isBlank(userName)){
            R data = new R(101, "用户编码在系统中查询不到，请核实！");
            data.put("data", "");
            return ResponseEntity.ok(data);
        }

        boolean b = emailMaintainService.update(emailMaintain);
        if(b){
            return ResponseEntity.ok(R.ok());
        }
        return ResponseEntity.ok(R.error());
    }

    /**
     * 编辑数据
     *
     * @param pramsMap
     * @return 删除结果
     */
    @PostMapping("/delete")
    public ResponseEntity<R> delete(@RequestBody Map<String, Object> pramsMap) {

        String id = pramsMap.get("id").toString();

        log.info("传入的删除参数id={}",id);

        DynamicContextHolder.push(DbConstant.BASICS_READ);
        boolean b = emailMaintainService.deleteById(id);
        if(b){
            return ResponseEntity.ok(R.ok());
        }
        return ResponseEntity.ok(R.error());
    }


    /**
     * 编辑数据
     *
     * @param file 实体
     * @return 编辑结果
     */
    @RequestMapping("/emailUpload")
    public ResponseEntity<R> emailUpload(@RequestParam(value = "file") MultipartFile file,
                                         @RequestParam(value = "deptId") String deptId,
                                         @RequestParam(value = "deptName") String deptName) {

        try {
            List<EmailMaintainExcel> emailMaintainExcels =
                    EasyExcel.read(file.getInputStream()).sheet().head(EmailMaintainExcel.class).headRowNumber(1).doReadSync();
            log.info("解析的数据：{}",JSONObject.toJSONString(emailMaintainExcels));
            if (emailMaintainExcels == null || emailMaintainExcels.isEmpty()) {
                return ResponseEntity.ok(R.error("数据解析失败"));
            }
            List<String> errorMsgList = Lists.newArrayList();
            List<EmailMaintainVo>  mailList = Lists.newArrayList();
            List<String> mailTitleList = new ArrayList<>();
            int resultIndex = 1;
            for (EmailMaintainExcel maintainExcel : emailMaintainExcels) {

                resultIndex++;
                String userId = maintainExcel.getUserId();
                if (StringUtils.isBlank(userId)) {
                    errorMsgList.add("第" + resultIndex + "行，用户编码不能为空");
                    continue;
                }
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                String userName = emailMaintainService.getUserName(userId);
                if(StringUtils.isBlank(userName)){
                    errorMsgList.add("第" + resultIndex + "行，用户编码在系统中查询不到，请核实！");
                    continue;
                }
                String address = maintainExcel.getEmailAddress();
                if (StringUtils.isBlank(address)) {
                    errorMsgList.add("第" + resultIndex + "行，邮箱地址不能为空");
                    continue;
                }
                if(!address.contains("@qq.com") && !address.contains("@163.com")){
                    errorMsgList.add("第" + resultIndex + "行，不支持该邮箱类型");
                    continue;
                }
                String password = maintainExcel.getEmailPassword();
                if (StringUtils.isBlank(password)) {
                    errorMsgList.add("第" + resultIndex + "行，授权码不能为空");
                    continue;
                }

                if(mailTitleList.contains(maintainExcel.getEmailAddress())){
                    errorMsgList.add("第" + resultIndex + "行，用户邮箱地址重复，请核实！");
                    continue;
                }

                int i = emailMaintainService.selectByEmail(maintainExcel.getEmailAddress());
                if(i>0){
                    errorMsgList.add("第" + resultIndex + "行，邮箱数据已存在，请核实！");
                    continue;
                }

                mailTitleList.add(maintainExcel.getEmailAddress());

                EmailMaintainVo maintainVo = new EmailMaintainVo();
                maintainVo.setId(UUIDUtils.generateShortUuid());
                maintainVo.setCompanyCode(deptId);
                maintainVo.setDeptId(deptId);
                maintainVo.setDeptName(deptName);
                maintainVo.setUsername(userName);
                maintainVo.setUserId(userId);
                maintainVo.setEmailAddress(address);
                String encode = Base64Encoding.encode(password);
                maintainVo.setEmailPassword(encode);
                maintainVo.setDelStatus("0");
                maintainVo.setCreateUser(getUserInfo().getLoginname());
                maintainVo.setCreateTime(new Date());
                maintainVo.setModifyTime(new Date());
                mailList.add(maintainVo);
            }
            if (ObjectUtil.isNotEmpty(errorMsgList)) {
                JSONObject json = new JSONObject();
                json.put("datalist", errorMsgList);

                R data = new R(101, "校验信息有误");
                data.put("data", json);
                return ResponseEntity.ok(data);

            }
            int i = emailMaintainService.insertBatch(mailList);
            if(i > 0){
                return ResponseEntity.ok(R.ok());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.ok(R.error("数据解析失败"));
    }



    /**
     * 编辑数据
     *
     * @param paramsMap 实体
     * @return 编辑结果
     */
    @PostMapping("/getUserName")
    public ResponseEntity<R> getUserName(@RequestBody  Map<String,String> paramsMap) {
        String userCode = paramsMap.get("userCode");
        if(StringUtils.isEmpty(userCode)){
            return ResponseEntity.ok(R.error("数据不能为空！"));
        }
        String userName = emailMaintainService.getUserName(userCode);
        JSONObject json = new JSONObject();
        if(StringUtils.isNotEmpty(userName)){
            json.put("datalist", userName);
            log.debug("返回结果：{}", json.toJSONString());
            String jsonString = Base64.encode(json.toJSONString());
            return ResponseEntity.ok(R.ok().put("data",jsonString));
        }else{
            R result = new R(500,"未查询到该用户");
//            return ResponseEntity.ok(R.error().put("data","未查询到用户名为"+userName+"数据"));
            return ResponseEntity.ok(result);
        }
    }

}

