/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.dm.dmCard.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.dm.dmCard.domain.DmCard;
import me.zhengjie.modules.dm.dmCard.repository.DmCardRepository;
import me.zhengjie.modules.dm.dmCard.service.DmCardService;
import me.zhengjie.modules.dm.dmCard.service.dto.DmCardDto;
import me.zhengjie.modules.dm.dmCard.service.dto.DmCardQueryCriteria;
import me.zhengjie.modules.dm.dmCard.service.mapstruct.DmCardMapper;
import me.zhengjie.modules.dmuser.domain.DmUser;
import me.zhengjie.modules.dmuser.service.DmUserService;
import me.zhengjie.modules.dmuser.service.dto.DmUserDto;
import me.zhengjie.modules.dmuser.service.mapstruct.DmUserMapper;
import me.zhengjie.utils.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zhirong
* @date 2021-11-10
**/
@Service
@RequiredArgsConstructor
public class DmCardServiceImpl implements DmCardService {
    @Value("${zkUpdateUrl}")
    private String zkUpdateUrl;
    @Value("${personOperate}")
    private String personOperate;
    private final DmCardRepository dmCardRepository;
    private final DmCardMapper dmCardMapper;
    private final DmUserService dmUserService;
    private final DmUserMapper dmUserMapper;
    @Value("${key}")
    private String key;// = "DMERPYT!@#$QWER2021+{:>"

    @Override
    public Map<String,Object> queryAll(DmCardQueryCriteria criteria, Pageable pageable){
        Page<DmCard> page = dmCardRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(dmCardMapper::toDto));
    }

    @Override
    public List<DmCardDto> queryAll(DmCardQueryCriteria criteria){
        return dmCardMapper.toDto(dmCardRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public List<Map<String,Object>> getAllByCardNumber() {
        return dmCardRepository.getAllByCardNumber();
    }

    @Override
    @Transactional
    public DmCardDto findById(Long cardId) {
        DmCard dmCard = dmCardRepository.findById(cardId).orElseGet(DmCard::new);
        ValidationUtil.isNull(dmCard.getId(),"DmCard","id",cardId);
        return dmCardMapper.toDto(dmCard);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmCardDto create(DmCard resources) throws Exception {
//        resources.setCardId(IdUtil.simpleUUID());
        //设置用户信息
        resources = setDmUserInfoToSysUser(resources);
        if (dmCardRepository.findByCardNumber(resources.getCardNumber()) != null) {
            throw new EntityExistException(DmCard.class, "卡号", resources.getCardNumber());
        }
        DmCardDto dmCard = dmCardMapper.toDto(dmCardRepository.save(resources));

//        String url = "https://smartpark.caih.com/zkxt/api/thirdparty/v1/user/updateZkUsers";
        Map<String,Object> newToken = SecurityUtils.getToken(key);
        JSONObject param = new JSONObject();
        param.put("timestamp",newToken.get("timestamp"));
        param.put("nonce",newToken.get("nonce"));
        JSONObject data = new JSONObject();
        data.put("cardid",dmCard.getCardNumber());
        data.put("id",dmCard.getDmUser().getId());
        param.put("query",data);
        HttpRequest.get(zkUpdateUrl)
                .header("XYTACCESSTOKEN",newToken.get("token").toString() )
                .body(param.toJSONString()).execute().body();

        DmUserDto dmUserDto = dmUserService.findById(dmCard.getDmUser().getId());
//        String api = "http://10.208.128.14:8069/openapi/personOperate";
        JSONObject person = new JSONObject();
        person.put("userId",dmUserDto.getUserNumber());
        person.put("userName",dmUserDto.getName());
        person.put("deptId",dmUserDto.getDept().getId());
        person.put("cardId",dmCard.getCardNumber());
        person.put("operateType",2);
        String res = HttpRequest.post(personOperate)
                .form("person",person.toJSONString()).execute().body();
        System.out.println("res:"+res);

        dmUserDto.setCardId(dmCard.getCardNumber());
        dmUserService.update(dmUserMapper.toEntity(dmUserDto));

        return null;
    }

    /**
     * 将绑定的DM用户信息跟账号进行关联
     * @param resources
     */
    public DmCard setDmUserInfoToSysUser(DmCard resources){
        //判断关联的DM用户是否已关联别的账号
        if(resources != null && resources.getDmUser() != null && resources.getDmUser().getId() != null){
            List<DmCard> list = findByDmUserId(resources.getDmUser().getUserNumber(),resources.getId());
            if(list != null && list.size() > 0){
                throw new BadRequestException("该用户已绑定卡号,请重新选择绑定用户");
            }
        }
        if(resources.getDmUser() != null && resources.getDmUser().getId() != null){
            //查询关联的DM用户信息
            DmUserDto dmUserDto = dmUserService.findById(resources.getDmUser().getId());
            if(dmUserDto != null){
                List<DmUserDto> temp = new ArrayList<>();
                temp.add(dmUserDto);
                DmUser dmUser = dmUserMapper.toEntity(temp).get(0);
                //设置对应的信息
//                resources.setDmUser(dmUser);
                resources.setUserName(dmUser.getName());//昵称/用户名
                resources.setUserType(dmUser.getUsertype());//类型
                resources.setDept(dmUser.getDept());//部门
            }
        }
        return resources;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DmCard resources) throws Exception {
        resources = setDmUserInfoToSysUser(resources);
        if(resources.getDept() != null && resources.getDept().getId() == null){
            resources.setDept(null);
        }
        if(resources.getDmUser() != null && resources.getDmUser().getUserNumber() == null){
            resources.setDmUser(null);
        }
        if (dmCardRepository.findByCardNumber(resources.getCardNumber()) != null) {
            throw new EntityExistException(DmCard.class, "卡号", resources.getCardNumber());
        }
        DmCard dmCard = dmCardRepository.findById(resources.getId()).orElseGet(DmCard::new);
        ValidationUtil.isNull( resources.getId(),"DmCard","id",resources.getId());
        dmCard.copy(resources);

        if (resources.getCardNumber() != null){
//            String url = "http://192.168.1.4:6112/api/thirdparty/v1/user/updateZkUsers";
            Map<String,Object> newToken = SecurityUtils.getToken(key);
            JSONObject param = new JSONObject();
            param.put("timestamp",newToken.get("timestamp"));
            param.put("nonce",newToken.get("nonce"));
            JSONObject data = new JSONObject();
            data.put("cardid",resources.getCardNumber());
            data.put("id",resources.getDmUser().getId());
            param.put("query",data);
            HttpRequest.get(zkUpdateUrl)
                    .header("XYTACCESSTOKEN",newToken.get("token").toString() )
                    .body(param.toJSONString()).execute().body();

            DmUserDto dmUserDto = dmUserService.findById(resources.getDmUser().getId());
//            String api = "http://10.208.128.14:8069/openapi/personOperate";
            JSONObject person = new JSONObject();
            person.put("userId",dmUserDto.getUserNumber());
            person.put("userName",dmUserDto.getName());
            person.put("deptId",dmUserDto.getDept().getId());
            person.put("cardId",resources.getCardNumber());
            person.put("operateType",2);
            String res = HttpRequest.post(personOperate)
                    .form("person",person.toJSONString()).execute().body();
            System.out.println("res:"+res);

            dmUserDto.setCardId(resources.getCardNumber());
            dmUserService.update(dmUserMapper.toEntity(dmUserDto));
        }

        dmCardRepository.save(dmCard);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long userName : ids) {
            dmCardRepository.deleteById(userName);
        }
    }

    @Override
    public void download(List<DmCardDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmCardDto dmCard : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" id",  dmCard.getId());
            map.put("卡号", dmCard.getCardNumber());
            map.put("用户工号", dmCard.getDmUser().getUserNumber());
            map.put("用户种类", dmCard.getUserType());
            map.put("用户部门", dmCard.getDept().getId());
            map.put("开卡状态", dmCard.getStatus());
            map.put("余额", dmCard.getBalance());
//            map.put("创建者", dmCard.getCreateBy());
//            map.put("更新者", dmCard.getUpdateBy());
            map.put("创建时间", dmCard.getCreateTime());
//            map.put("更新时间", dmCard.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<DmCard> findByDmUserId(String userNumber, Long cardId) {
        return dmCardRepository.findByDmUserId(userNumber,cardId);
    }

    @Override
    public DmCard findByCardNumber(String cardNumber) {
        return dmCardRepository.findByCardNumber(cardNumber);
    }

    @Override
    public DmCard findByUserNumber(String userNumber) {
        return dmCardRepository.findByUserNumber(userNumber);
    }
}