package com.sqx.modules.app.controller.app;

import com.alibaba.fastjson.JSON;
import com.aliyun.dyplsapi20170525.models.BindAxnResponse;
import com.aliyun.dyplsapi20170525.models.BindAxnResponseBody;
import com.aliyun.dyplsapi20170525.models.UpdateSubscriptionResponse;
import com.aliyun.dyplsapi20170525.models.UpdateSubscriptionResponseBody;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyun.tea.TeaException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.annotation.LoginUser;
import com.sqx.modules.app.dao.UserCertificationDao;
import com.sqx.modules.app.entity.UserCertification;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.service.AppService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.artificer.entity.Artificer;
import com.sqx.modules.artificer.service.ArtificerService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.coupon.entity.CouponUser;
import com.sqx.modules.coupon.service.CouponUserService;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app/user")
@Api(value = "APP管理", tags = {"APP管理"})
@Slf4j
public class AppController {

    @Autowired
    private UserService userService;
    @Autowired
    private AppService appService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    private ArtificerService artificerService;

    @Login
    @ApiOperation("生成虚拟号码")
    @GetMapping("/insertVirtualPhone")
    public Result insertVirtualPhone(String phoneA, String phoneB) {
        MessageInfo messageInfo1 = messageInfoDao.selectOne(new QueryWrapper<MessageInfo>().eq("user_name", phoneA).eq("by_user_name", phoneB));
        if (messageInfo1 == null) {
            messageInfo1 = messageInfoDao.selectOne(new QueryWrapper<MessageInfo>().eq("user_name", phoneB).eq("by_user_name", phoneA));
        }
        String accessKeyId = commonInfoService.findOne(386).getValue();
        String accessKeySecret = commonInfoService.findOne(387).getValue();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dyplsapi.aliyuncs.com";
        try {
            String poolKey = commonInfoService.findOne(382).getValue();
            com.aliyun.dyplsapi20170525.Client client = new com.aliyun.dyplsapi20170525.Client(config);
            if (messageInfo1 != null) {
                com.aliyun.dyplsapi20170525.models.UpdateSubscriptionRequest updateSubscriptionRequest = new com.aliyun.dyplsapi20170525.models.UpdateSubscriptionRequest();
                com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
                updateSubscriptionRequest.setPoolKey(poolKey);
                updateSubscriptionRequest.setSubsId(messageInfo1.getTitle());
                updateSubscriptionRequest.setPhoneNoX(messageInfo1.getContent());
                String value = commonInfoService.findOne(418).getValue();
                if("是".equals(value)){
                    updateSubscriptionRequest.setIsRecordingEnabled(true);
                }
                Calendar calendar=Calendar.getInstance();
                calendar.add(Calendar.HOUR,1);
                updateSubscriptionRequest.setExpiration(DateUtils.format(calendar.getTime()));
                updateSubscriptionRequest.setOperateType("updateExpire");
                UpdateSubscriptionResponse updateSubscriptionResponse = client.updateSubscriptionWithOptions(updateSubscriptionRequest, runtime);
                UpdateSubscriptionResponseBody body = updateSubscriptionResponse.getBody();
                String code = body.getCode();
                if("OK".equals(code)){
                    return Result.success().put("data", messageInfo1.getContent());
                }
                messageInfoDao.deleteById(messageInfo1.getId());
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState("18");
            messageInfo.setUserName(phoneA);
            messageInfo.setByUserName(phoneB);
            com.aliyun.dyplsapi20170525.models.BindAxnRequest bindAxnRequest = new com.aliyun.dyplsapi20170525.models.BindAxnRequest();
            bindAxnRequest.setPoolKey(poolKey);
            bindAxnRequest.setPhoneNoA(phoneA);
            bindAxnRequest.setPhoneNoB(phoneB);
            String value = commonInfoService.findOne(418).getValue();
            if("是".equals(value)){
                bindAxnRequest.setIsRecordingEnabled(true);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR, 1);
            bindAxnRequest.setExpiration(DateUtils.format(calendar.getTime()));
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            BindAxnResponse bindAxnResponse = client.bindAxnWithOptions(bindAxnRequest, runtime);
            BindAxnResponseBody body = bindAxnResponse.getBody();
            String code = body.code;
            if (!"OK".equals(code)) {
                return Result.error("获取号码失败！" + body.getMessage());
            }
            BindAxnResponseBody.BindAxnResponseBodySecretBindDTO secretBindDTO = body.getSecretBindDTO();
            messageInfo.setContent(secretBindDTO.getSecretNo());
            messageInfo.setTitle(secretBindDTO.getSubsId());
            messageInfo.setCreateAt(DateUtils.format(new Date()));
            messageInfoDao.insert(messageInfo);
            return Result.success().put("data", secretBindDTO.getSecretNo());
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return Result.error("获取号码失败！");
    }



    @Login
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("用户端修改密码")
    public Result updatePwd(@LoginUser UserEntity user, String pwd, String oldPwd) {
        if (!user.getPassword().equals(DigestUtils.sha256Hex(oldPwd))) {
            return Result.error("原始密码不正确！");
        }
        if (pwd.equals(oldPwd)) {
            return Result.error("新密码不能与旧密码相同！");
        }
        user.setPassword(DigestUtils.sha256Hex(pwd));
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updatePhone", method = RequestMethod.POST)
    @ApiOperation("用户端换绑手机号")
    @ResponseBody
    public Result updatePhone(@RequestAttribute("userId") Long userId, @RequestParam String phone, @RequestParam String msg) {
        return userService.updatePhone(phone, msg, userId);
    }

    @Login
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ApiOperation("用户修改个人信息")
    @ResponseBody
    public Result updateUser(@RequestBody UserEntity userEntity,@RequestAttribute("userId") Long userId) {
        userEntity.setUserId(userId);
        userService.updateById(userEntity);
        //更新artificer 技师主表
        UpdateWrapper<Artificer> uw = new UpdateWrapper<>();
        uw.set("artificer_img",userEntity.getAvatar());
        uw.eq("user_id",userId);
        artificerService.update(uw);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updateUserImageUrl", method = RequestMethod.POST)
    @ApiOperation("用户修改头像")
    @ResponseBody
    public Result updateUserImageUrl(@LoginUser UserEntity user, String avatar) {
        user.setAvatar(avatar);
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updateUserName", method = RequestMethod.POST)
    @ApiOperation("用户修改昵称")
    @ResponseBody
    public Result updateUserName(@LoginUser UserEntity user, String userName) {
        user.setUserName(userName);
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/selectUserById", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserById(@LoginUser UserEntity user) {
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(user.getUserId());
        user.setMoney(userMoney.getMoney());

        CouponUser couponUser = couponUserService.selectCountByUserId(user.getUserId());
        user.setMember(couponUser.getNum());

        //获取地址及更新时间
        Artificer artificer = artificerService.selectArtificerByUserId(user.getUserId());
        if(artificer != null){
            user.setLoglattime(artificer.getUpdateTime());
            user.setLoglataddress(artificer.getAddress());
        }


        return Result.success().put("data", user);
    }

    @RequestMapping(value = "/selectUserInfo", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserInfo(Long userId) {
        UserEntity userEntity = userService.getById(userId);
        return Result.success().put("data", userEntity);
    }


    @RequestMapping(value = "/selectNewApp", method = RequestMethod.GET)
    @ApiOperation("升级检测")
    @ResponseBody
    public Result selectNewApp(Integer classify) {
        return Result.success().put("data", appService.selectNewApp(classify));
    }

    @RequestMapping(value = "/updateClientId", method = RequestMethod.POST)
    @ApiOperation("绑定ClientId")
    @ResponseBody
    public Result updateClientId(String clientId,Long userId,Integer sysPhone ) {
        userService.updateUserClientIdIsNull(clientId);
        UserEntity userEntity=new UserEntity();
        userEntity.setSysPhone(sysPhone);
        userEntity.setUserId(userId);
        userEntity.setClientid(clientId);
        userService.updateById(userEntity);
        return Result.success();
    }



}
