package com.crm.manager.controller;

import com.alibaba.fastjson.JSON;
import com.crm.manager.service.FinanceRateService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.system.config.SendUpdateEmailCodeEntity;
import com.crm.rely.backend.model.dto.finance.rate.FinanceRateSearchDto;
import com.crm.rely.backend.model.entity.finance.rate.*;
import com.crm.rely.backend.model.entity.user.info.UserInfoEntity;
import com.crm.rely.backend.util.GetIpAndMac;
import com.crm.rely.backend.util.GoogleAuthenticatorUtil;
import com.crm.rely.backend.util.HttpUtil;
import org.jsoup.Connection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author houn
 */
@RestController
@RequestMapping("/finance/rate")
public class FinanceRateController {

    @Autowired
    private FinanceRateService financeRateService;

    /**
     * 添加汇率
     *
     * @param entity
     * @return
     */
    @PostMapping("/add")
    public BaseResultDto addRate(@RequestBody @Validated FinanceRateAddEntity entity, UserInfoEntity infoEntity) throws Exception {
//        entity.setEmail(infoEntity.getIbInfo().getEmail());
        /*if (!GoogleAuthenticatorUtil.verifyCode(infoEntity.getSecretKey(), entity.getGaCode())) {
            return BaseResultDto.error(Constants.GOOGLE_CAPTCHA_ERROR);
        }*/
        financeRateService.add(entity);
        return BaseResultDto.success();
    }

    /**
     * 修改汇率
     *
     * @param entity
     * @return
     */
    @PostMapping("/update")
    public BaseResultDto updateRate(@RequestBody @Validated FinanceRateUpdateEntity entity, UserInfoEntity infoEntity) throws Exception {
//        entity.setEmail(infoEntity.getIbInfo().getEmail());
       /* if (!GoogleAuthenticatorUtil.verifyCode(infoEntity.getSecretKey(), entity.getGaCode())) {
            return BaseResultDto.error(Constants.GOOGLE_CAPTCHA_ERROR);
        }*/
        financeRateService.update(entity);
        return BaseResultDto.success();
    }

    @PostMapping("/batch/update")
    public BaseResultDto updateBatchRate(@RequestBody @Validated FinanceRateBatchUpdateEntity entity, UserInfoEntity infoEntity) throws Exception {
        if (entity == null) {
            return BaseResultDto.error(Constants.SYSTEM_ERROR);
        }
        /*if (!GoogleAuthenticatorUtil.verifyCode(infoEntity.getSecretKey(), entity.getGaCode())) {
            return BaseResultDto.error(Constants.GOOGLE_CAPTCHA_ERROR);
        }*/
        List<FinanceRateUpdateEntity> entitys = null;
        if (entity.getData() != null) {
            entitys = new ArrayList<>(entity.getData().size());

            for (FinanceRateUpdatesEntity financeRateUpdatesEntity :
                    entity.getData()) {
                FinanceRateUpdateEntity financeRateUpdateEntity = new FinanceRateUpdateEntity();
                BeanUtils.copyProperties(financeRateUpdatesEntity, financeRateUpdateEntity);
                financeRateUpdateEntity.setType(entity.getType());
                entitys.add(financeRateUpdateEntity);
            }
        }
//        entity.setEmail(infoEntity.getIbInfo().getEmail());
        financeRateService.save(entity, entitys);
        return BaseResultDto.success();
    }

    /**
     * 删除汇率
     *
     * @param entity
     * @return
     */
    @PostMapping("/delete")
    public BaseResultDto deleteRate(@RequestBody @Validated FinanceRateDeleteEntity entity, UserInfoEntity infoEntity) throws Exception {
//        entity.setEmail(infoEntity.getIbInfo().getEmail());
        /*if (!GoogleAuthenticatorUtil.verifyCode(infoEntity.getSecretKey(), entity.getGaCode())) {
            return BaseResultDto.error(Constants.GOOGLE_CAPTCHA_ERROR);
        }*/
        financeRateService.delete(entity);
        return BaseResultDto.success();
    }

    /**
     * 查询汇率
     *
     * @param entity
     * @return
     */
    @PostMapping("/searcher/list")
    public BaseResultDto searcherListRate(@RequestBody @Validated FinanceRateSearchListEntity entity) throws Exception {
        BaseResultDto resultDto = financeRateService.searchList(entity);
        return resultDto;
    }

    /**
     * 单个查看汇率
     *
     * @param entity
     * @return
     */
    @PostMapping("/searcher/single")
    public BaseResultDto searcherSingleRate(@RequestBody @Validated SingleLongEntity entity) throws Exception {
        FinanceRateSearchDto financeRateSearchDto = financeRateService.searchSingle(entity.getId());
        return BaseResultDto.success(financeRateSearchDto);
    }

    @PostMapping("/add/send/code")
    public BaseResultDto addChannelSendEmailCode(UserInfoEntity infoEntity) throws Exception {

        return sendEmailCode(infoEntity);
    }

    @PostMapping("/update/send/code")
    public BaseResultDto updateUpdateSendEmailCode(UserInfoEntity infoEntity) throws Exception {

        return sendEmailCode(infoEntity);
    }
    @PostMapping("/batch/update/send/code")
    public BaseResultDto updateBatchUpdateSendEmailCode(UserInfoEntity infoEntity) throws Exception {

        return sendEmailCode(infoEntity);
    }

    @PostMapping("/delete/send/code")
    public BaseResultDto deleteChannelSendEmailCode(UserInfoEntity infoEntity) throws Exception {

        return sendEmailCode(infoEntity);
    }


    @RequestMapping("/convert")
    public BaseResultDto convert(@RequestBody @Validated FinanceRateEntity entity) throws Exception {

        String host = "https://tysjhlcx.market.alicloudapi.com";
        String path = "/exchange_rate/convert";
        String appcode = "e2e11e758e2c4a239456dead26feb847";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("fromCode", entity.getTransformCurrency());
        querys.put("toCode", entity.getCurrency());
        querys.put("money", "1");


        try {

            Connection.Response response = HttpUtil.get(host + path, headers, querys);
            return BaseResultDto.success(JSON.parseObject(response.body()).get("data"));
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResultDto.error();
        }
    }


    public BaseResultDto sendEmailCode(UserInfoEntity infoEntity) throws Exception {
        if (infoEntity == null) {
            return BaseResultDto.error(Constants.SYSTEM_ERROR);
        }
        SendUpdateEmailCodeEntity emailCodeEntity = new SendUpdateEmailCodeEntity();

        emailCodeEntity.setEmail(infoEntity.getEmail());
        emailCodeEntity.setTime(new Date());
        emailCodeEntity.setUser(infoEntity.getId());
        emailCodeEntity.setIp(GetIpAndMac.getIp());

        financeRateService.sendEmailCode(emailCodeEntity);
        return BaseResultDto.success(Constants.SEND_SUCCESS);
    }

}
