package com.huimv.env.admin.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.env.admin.common.token.TokenSign;
import com.huimv.env.admin.common.utils.Result;
import com.huimv.env.admin.common.utils.ResultCode;
import com.huimv.env.admin.common.utils.UploadImage;
import com.huimv.env.admin.entity.AccountGroup;
import com.huimv.env.admin.entity.BaseFarm;
import com.huimv.env.admin.entity.Farm;
import com.huimv.env.admin.entity.SysAccountMultilevel;
import com.huimv.env.admin.mapper.SysAccountMultilevelMapper;
import com.huimv.env.admin.service.IAccountGroupService;
import com.huimv.env.admin.service.IBaseFarmService;
import com.huimv.env.admin.service.ISysAccountGroupService;
import com.huimv.env.admin.service.ISysAccountMultilevelService;
import com.huimv.env.admin.session.AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-05-06
 */
@RestController
@RequestMapping("/admin/accountMultilevel")
@CrossOrigin
public class SysAccountMultilevelController {
    @Autowired
    private ISysAccountMultilevelService accountMultilevelService;
    @Autowired
    private IBaseFarmService farmService;
    @Autowired
    private SysAccountMultilevelMapper sysAccountMultilevelMapper;

    @Autowired
    private IAccountGroupService accountGroupService;
    @Autowired
    private UploadImage uploadImage;


    @PostMapping("/list")
    public Result list(@RequestBody Map map , HttpServletRequest request){
        Integer userId = TokenSign.getMemberIdByJwtToken(request);
        int pageNum = (Integer)map.get("pageNum");
        int pageSize = (Integer)map.get("pageSize");
        String searchStr = (String)map.get("searchStr");

        return accountMultilevelService.findUserAccount(searchStr,pageNum,pageSize,userId);

    }

    @PostMapping("/listSubordinate")
    public Result listSubordinate(@RequestBody Map map , HttpServletRequest request){
        Integer userId = TokenSign.getMemberIdByJwtToken(request);
        int pageNum = (Integer)map.get("pageNum");
        int pageSize = (Integer)map.get("pageSize");
        String searchStr = (String)map.get("searchStr");
        return accountMultilevelService.listSubordinate(searchStr,pageNum,pageSize,userId);
    }

    @PostMapping("/listSubordinateByFarm")
    public Result listSubordinateByFarm(@RequestBody Map map , HttpServletRequest request){
        Integer userId = TokenSign.getMemberIdByJwtToken(request);
        String farmId = (String)map.get("farmId");
        return accountMultilevelService.listSubordinateByFarm(farmId,userId);
    }

    @PostMapping("/add")
    public Result add(@RequestBody SysAccountMultilevel sysAccountMultilevel , HttpServletRequest request){

        Integer userId = TokenSign.getMemberIdByJwtToken(request);
        return accountMultilevelService.add(sysAccountMultilevel,userId);

    }

    @PostMapping("/update")
    public Result update(HttpServletRequest req,@RequestBody SysAccountMultilevel sysAccountMultilevel){
        accountMultilevelService.updateById(sysAccountMultilevel);
        String remoteHost = req.getRemoteHost();
        AccessToken accessToken = new AccessToken();
        accessToken.setCreated(new Date());
        accessToken.setAccountName(sysAccountMultilevel.getAccount());
        accessToken.setFarmId(sysAccountMultilevel.getFarmIds());
        Integer lastFarmId = sysAccountMultilevel.getLastFarmId();
        if (ObjectUtil.isEmpty(lastFarmId)) {
            lastFarmId = Integer.parseInt(sysAccountMultilevel.getFarmIds().split(",")[0]);
        }
        accessToken.setLastFarmId(lastFarmId);
        BaseFarm farm = farmService.getById(lastFarmId);
        String token = TokenSign.sign(sysAccountMultilevel.getAccount(), sysAccountMultilevel.getId(), sysAccountMultilevel.getFarmIds(), null, null,farm.getLng(),farm.getLat());
        accessToken.setToken(token);
        accessToken.setNickName(sysAccountMultilevel.getNickName());
        accessToken.setAvatarUrl(sysAccountMultilevel.getAvatarUrl());
        accessToken.setId(sysAccountMultilevel.getId());
        accessToken.setLoginIp(remoteHost);
        accessToken.setType(sysAccountMultilevel.getType());
        accessToken.setLat(farm.getLat());
        accessToken.setLng(farm.getLng());
        accessToken.setWechatId(sysAccountMultilevel.getWechatId());
        accessToken.setUserName(sysAccountMultilevel.getUserName());
        return new Result(ResultCode.SUCCESS,accessToken);

    }

    @GetMapping("/remove")
    public Result remove(@RequestParam(name ="userIds") List<Integer> userIds){

        accountGroupService.remove(new QueryWrapper<AccountGroup>().in("account_id",userIds));
        accountMultilevelService.removeByIds(userIds);

        return new Result(10000,"删除成功",true);

    }

    @GetMapping("/setAccountStatus")
    public Result setAccountStatus(@RequestParam(name = "ids") List<Integer> ids, @RequestParam(name = "status") Integer status){
        /* 设置账号状态 */
        return accountMultilevelService.setAccountStatus(ids,status);
    }

    @GetMapping("/findOne")
    public Result findOne(Integer id){
        return new Result(ResultCode.SUCCESS, accountMultilevelService.getById(id));
    }


    @GetMapping("/getLastFarmId")
    public Result getLastFarmId(HttpServletRequest request){
        Integer userId = TokenSign.getMemberIdByJwtToken(request);
        return  accountMultilevelService.getLastFarmId(userId);
    }

    @PostMapping("/editImg")
    @Transactional(rollbackFor = Exception.class)
    public Result editImg(HttpServletRequest httpServletRequest, @RequestParam("img") MultipartFile img) throws IOException {
        SysAccountMultilevel sysAccountMultilevel = accountMultilevelService.getById(TokenSign.getMemberIdByJwtToken(httpServletRequest));
        if (uploadImage.getImageCom(img).equals("上传失败")) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result(10001,"图片上传失败",false);
        }
        sysAccountMultilevel.setImgUrl(uploadImage.getImageCom(img));
        accountMultilevelService.updateById(sysAccountMultilevel);
        return Result.SUCCESS();
    }

    @PostMapping("/updateUserName")
    public Result updateUserName(HttpServletRequest httpServletRequest, @RequestBody Map<String, String> paramsMap){
        SysAccountMultilevel sysAccountMultilevel = accountMultilevelService.getById(TokenSign.getMemberIdByJwtToken(httpServletRequest));
        sysAccountMultilevel.setUserName(paramsMap.get("userName"));
        accountMultilevelService.updateById(sysAccountMultilevel);
        return Result.SUCCESS();
    }

    @PostMapping("/updatePaper")
    public Result updatePaper(HttpServletRequest httpServletRequest,@RequestBody Map<String, String> paramsMap){
        SysAccountMultilevel sysAccountMultilevel = accountMultilevelService.getById(TokenSign.getMemberIdByJwtToken(httpServletRequest));
        sysAccountMultilevel.setPapersType(paramsMap.get("papersType"));
        sysAccountMultilevel.setPapersCode(paramsMap.get("papersCode"));
        accountMultilevelService.updateById(sysAccountMultilevel);
        return Result.SUCCESS();
    }

    @PostMapping("/updateUser")
    public Result updateUser(HttpServletRequest httpServletRequest,
                             @RequestParam(value = "img", required = false) MultipartFile img,
                             @RequestParam(value = "userName", required = false) String userName,
                             @RequestParam(value = "phone", required = false) String phone,
                             @RequestParam(value = "workPost", required = false) Integer workPost,
                             @RequestParam(value = "workLocation", required = false) String workLocation,
                             @RequestParam(value = "workLocationId", required = false) String workLocationId,
                             @RequestParam(value = "workName", required = false) String workName,
                             @RequestParam(value = "papersType", required = false) String papersType,
                             @RequestParam(value = "papersCode", required = false) String papersCode) throws IOException {
        return accountMultilevelService.updateUser(httpServletRequest,img,userName,phone,workPost,workLocation,workLocationId,workName,papersType,papersCode);
    }

    @PostMapping("/getDetail")
    public Result getDetail(HttpServletRequest httpServletRequest){
        return new Result(ResultCode.SUCCESS,accountMultilevelService.getById(TokenSign.getMemberIdByJwtToken(httpServletRequest)));
    }

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/wechatLogin")
    public String wechatLogin(@RequestParam(name = "js_code")String js_code){
        String URL  = "https://api.weixin.qq.com/sns/jscode2session";
        String appid  = "wx7982c391ad9c00b3";
        String secret  = "87f5a2f00478fbe39ec1e6c832f11068";
        String grant_type  = "authorization_code";

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(URL)
                .queryParam("appid", appid)
                .queryParam("secret", secret)
                .queryParam("grant_type", grant_type)
                .queryParam("js_code", js_code);

        String urlWithParams = builder.toUriString();

        try {
            String forObject = restTemplate.getForObject(urlWithParams, String.class);
            System.out.println(forObject);
            return forObject;
        } catch (Exception e) {
            // 处理异常，例如记录日志、返回错误信息等
            e.printStackTrace();
            // 根据需要返回错误信息或处理逻辑
            System.out.println(e.getMessage());
            return "Error occurred: " + e.getMessage();
        }
    }

    @GetMapping("/wechatLogin2")
    public String wechatLogin2(@RequestParam(name = "js_code")String js_code){
        String URL  = "https://api.weixin.qq.com/sns/jscode2session";
        String appid  = "wx135afbc98e976019";
        String secret  = "d22f323303373cbc0677634fbc2abbbf";
        String grant_type  = "authorization_code";

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(URL)
                .queryParam("appid", appid)
                .queryParam("secret", secret)
                .queryParam("grant_type", grant_type)
                .queryParam("js_code", js_code);

        String urlWithParams = builder.toUriString();

        try {
            String forObject = restTemplate.getForObject(urlWithParams, String.class);
            System.out.println(forObject);
            return forObject;
        } catch (Exception e) {
            // 处理异常，例如记录日志、返回错误信息等
            e.printStackTrace();
            // 根据需要返回错误信息或处理逻辑
            System.out.println(e.getMessage());
            return "Error occurred: " + e.getMessage();
        }
    }

    @PostMapping("/saveWechat")
    public Result saveWechat(HttpServletRequest request,@RequestBody Map<String,String> map){
        String wechatId = map.get("wechatId");
        String avatarUrl = map.get("avatarUrl");
        String nickName = map.get("nickName");
        String farmId = map.get("farmId");
        String remoteHost = request.getRemoteHost();

        BaseFarm farm = farmService.getById(farmId);

        Integer userId = TokenSign.getMemberIdByJwtToken(request);
        SysAccountMultilevel sysAccountMultilevel = sysAccountMultilevelMapper.selectById(userId);
        sysAccountMultilevel.setWechatId(wechatId);
        sysAccountMultilevel.setAvatarUrl(avatarUrl);
        sysAccountMultilevel.setNickName(nickName);
        sysAccountMultilevel.setSubscribe(0);
        sysAccountMultilevelMapper.updateById(sysAccountMultilevel);

        AccessToken accessToken = new AccessToken();
        accessToken.setCreated(new Date());
        accessToken.setAccountName(sysAccountMultilevel.getAccount());
        accessToken.setFarmId(sysAccountMultilevel.getFarmIds());
        accessToken.setLastFarmId(sysAccountMultilevel.getLastFarmId());
        String token = TokenSign.sign(sysAccountMultilevel.getUserName(), userId, sysAccountMultilevel.getFarmIds(), null, null,farm.getLng(),farm.getLat());
        accessToken.setToken(token);
        accessToken.setNickName(sysAccountMultilevel.getNickName());
        accessToken.setAvatarUrl(sysAccountMultilevel.getAvatarUrl());
        accessToken.setId(sysAccountMultilevel.getId());
        accessToken.setLoginIp(remoteHost);
        accessToken.setType(sysAccountMultilevel.getType());
        accessToken.setLat(farm.getLat());
        accessToken.setLng(farm.getLng());
        accessToken.setWechatId(wechatId);
        accessToken.setUserName(sysAccountMultilevel.getUserName());
        return new Result(ResultCode.SUCCESS,accessToken);
    }

    @PostMapping("/getSubscribe")
    public Result getSubscribe(HttpServletRequest request){
        Integer memberIdByJwtToken = TokenSign.getMemberIdByJwtToken(request);
        SysAccountMultilevel sysAccountMultilevel = sysAccountMultilevelMapper.selectById(memberIdByJwtToken);
        if (ObjectUtil.isNull(sysAccountMultilevel.getSubscribe())){
            sysAccountMultilevel.setSubscribe(0);
        }
        sysAccountMultilevelMapper.updateById(sysAccountMultilevel);
        return new Result(ResultCode.SUCCESS,sysAccountMultilevel.getSubscribe());
    }
    @PostMapping("/subscribe")
    public Result subscribe(HttpServletRequest request){
        Integer memberIdByJwtToken = TokenSign.getMemberIdByJwtToken(request);
        SysAccountMultilevel sysAccountMultilevel = sysAccountMultilevelMapper.selectById(memberIdByJwtToken);
        sysAccountMultilevel.setSubscribe(1);
        sysAccountMultilevelMapper.updateById(sysAccountMultilevel);
        return Result.SUCCESS();
    }
}
