package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.annotation.AutoLog;
import cn.com.ctop.common.module.entity.BindAccountLogin;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
import cn.com.ctop.common.module.service.IBindAccountLoginService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.common.module.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.ctop.service.ICreateInternalService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 账号绑定-登陆
 * @Author: jeecg-boot
 * @Date: 2019-07-31
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "账号绑定-登陆")
@RestController
@RequestMapping("/ctop/bindAccountLogin")
public class BindAccountLoginController {
    @Autowired
    private IBindAccountLoginService bindAccountLoginService;
    @Autowired
    private UserAllocationMapper userAllocationMapper;
    @Autowired
    private ICreateInternalService createInternalService;
    @Autowired
    private ISysRoleService sysRoleService;
    /**
     * @param json
     * @return
     */
    @PostMapping(value = "/login")
    public Result<IPage<BindAccountLogin>> login(@RequestBody JSONObject json) {
        log.info("登录入参:{}", json);
        Result<IPage<BindAccountLogin>> result = new Result<>();
        String advertiserId = json.getString("advertiserId");
        if (Check.isNull(advertiserId)) {
            result.setSuccess(false);
            result.setMessage("广告主id为空");
            return result;
        }
        //创建人
        String userId = json.getString("userId");
        String loginType = json.getString("loginType");
        // 广告主名称
        String advertiserName = json.getString("advertiser_name");
        //项目id
        Long projectId = json.getLong("projectId");
        //账号
        String accountName = json.getString("accountName");
        String password = json.getString("password");
        Map<String, Object> stringObjectMap = createInternalService.bindLogin(projectId,advertiserId, accountName, password, loginType, userId, advertiserName);
        Boolean trueOrFalse = (Boolean) stringObjectMap.get("success");
        if (Boolean.TRUE.equals(trueOrFalse)&&!loginType.equals(CtopAdConstant.PLATFORM_TYPE_PANGOLIN_PY)) {
            Map<String, Object> deleteMap = new HashMap<>();
            deleteMap.put("account_name", accountName);
            deleteMap.put("user_id", userId);
            deleteMap.put("advertiser_id", advertiserId);
            userAllocationMapper.deleteByMap(deleteMap);
            Long accountId = (Long) stringObjectMap.get("accountId");
            String mediaId = json.getString("mediaId");
            String userName = json.getString("userName");
            // 媒体类型： 1 头条 2 快手
            String projectName = json.getString("projectName");
            String systemType = json.getString("systemType");
            UserAllocation userAllocation = new UserAllocation();
            userAllocation.setUserName(userName);
            userAllocation.setUserId(userId);
            userAllocation.setAdvertiserId(advertiserId);
            userAllocation.setAccountId(accountId);
          //  userAllocation.setAdvertiserName(advertiserName);
            userAllocation.setAccountName(accountName);
            userAllocation.setProjectId(projectId);
            // userAllocation.setProjectName(projectName);
            userAllocation.setMediaId(mediaId);
            userAllocation.setSystemType(systemType);
            int i = userAllocationMapper.insert(userAllocation);
            if (i > 0) {
                log.info("用户分配入库完成,advertiserId:{}", advertiserId);
            }
        }
        result.setSuccess(trueOrFalse);
        result.setMessage((String) stringObjectMap.get("message"));
        return result;
    }


    /**
     * 分页列表查询
     *
     * @param bindAccountLogin
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "账号绑定-登陆-分页列表查询")
    @ApiOperation(value = "账号绑定-登陆-分页列表查询", notes = "账号绑定-登陆-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<BindAccountLogin>> queryPageList(BindAccountLogin bindAccountLogin,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        Result<IPage<BindAccountLogin>> result = new Result<>();
        String accountName = bindAccountLogin.getAccountName();
        String loginType = bindAccountLogin.getLoginType();
        bindAccountLogin.setAccountName(null);
        bindAccountLogin.setLoginType(null);
        QueryWrapper<BindAccountLogin> queryWrapper = QueryGenerator.initQueryWrapper(bindAccountLogin, req.getParameterMap());
        if(null!=accountName&&!"".equals(accountName.trim())){
            queryWrapper.like("account_name",accountName);
        }
        if(null != loginType&&!"".equals(loginType.trim())&&!"none".equals(loginType)){
            queryWrapper.eq("login_type",loginType);
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String roleCode = sysRoleService.getRoleCodeByUserId(user.getId());
        if(!"admin".equals(roleCode)){
            queryWrapper.eq("user_id", user.getId());
        }
        queryWrapper.orderByDesc("id");
        Page<BindAccountLogin> page = new Page<>(pageNo, pageSize);
        IPage<BindAccountLogin> pageList = bindAccountLoginService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param bindAccountLogin
     * @return
     */
    @AutoLog(value = "账号绑定-登陆-添加")
    @ApiOperation(value = "账号绑定-登陆-添加", notes = "账号绑定-登陆-添加")
    @PostMapping(value = "/add")
    public Result<BindAccountLogin> add(@RequestBody BindAccountLogin bindAccountLogin) {
        Result<BindAccountLogin> result = new Result<>();
        try {
            bindAccountLoginService.save(bindAccountLogin);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param bindAccountLogin
     * @return
     */
    @AutoLog(value = "账号绑定-登陆-编辑")
    @ApiOperation(value = "账号绑定-登陆-编辑", notes = "账号绑定-登陆-编辑")
    @PutMapping(value = "/edit")
    public Result<BindAccountLogin> edit(@RequestBody BindAccountLogin bindAccountLogin) {
        Result<BindAccountLogin> result = new Result<>();
        BindAccountLogin bindAccountLoginEntity = bindAccountLoginService.getById(bindAccountLogin.getId());
        if (bindAccountLoginEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = bindAccountLoginService.updateById(bindAccountLogin);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "账号绑定-登陆-通过id删除")
    @ApiOperation(value = "账号绑定-登陆-通过id删除", notes = "账号绑定-登陆-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<Object> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            bindAccountLoginService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "账号绑定-登陆-批量删除")
    @ApiOperation(value = "账号绑定-登陆-批量删除", notes = "账号绑定-登陆-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<BindAccountLogin> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<BindAccountLogin> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.bindAccountLoginService.removeByIds(Arrays.asList(ids.split(StringUtils.COMMA)));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "账号绑定-登陆-通过id查询")
    @ApiOperation(value = "账号绑定-登陆-通过id查询", notes = "账号绑定-登陆-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<BindAccountLogin> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<BindAccountLogin> result = new Result<>();
        BindAccountLogin bindAccountLogin = bindAccountLoginService.getById(id);
        if (bindAccountLogin == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(bindAccountLogin);
            result.setSuccess(true);
        }
        return result;
    }
}
