/*
 *  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.quartz.task;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.config.RsaProperties;
import me.zhengjie.modules.dm.card.domain.DmCard;
import me.zhengjie.modules.dm.card.service.DmCardService;
import me.zhengjie.modules.dm.card.service.dto.DmCardDto;
import me.zhengjie.modules.dm.plateNumber.domain.DmPlateNumber;
import me.zhengjie.modules.dm.plateNumber.repository.DmPlateNumberRepository;
import me.zhengjie.modules.dm.roomDevice.domain.DmRoomDevice;
import me.zhengjie.modules.dm.roomDevice.repository.DmRoomDeviceRepository;
import me.zhengjie.modules.dm.user.domain.DmUser;
import me.zhengjie.modules.dm.user.service.DmUserService;
import me.zhengjie.modules.dm.user.service.dto.DmUserDto;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.system.service.mapstruct.RoleMapper;
import me.zhengjie.utils.RsaUtils;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * ERP 数据同步
 * @author Sky
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class ZkDataSyncTask {

    private final String erpApiUrl = "https://portal.caih.com";
    private final String sign = "e34b2f59-0e9d-45ed-a32a-f4abd4381000";
    private final String header_key = "X_AUTO_USER_INFO_HEAD";
    private final String header_value = "{\"id\":\"anonymous\",\"tenantId\":\"caih\"}";
    private final String key = "DMERPYT!@#$QWER2021+{:>";

    private final DeptService deptService;
    private final UserService userService;
    private final DmUserService dmUserService;
    private final PasswordEncoder passwordEncoder;
    private final DmPlateNumberRepository dmPlateNumberRepository;
    private final DmRoomDeviceRepository dmRoomDeviceRepository;
    private final DmCardService dmCardService;

    private final RoleMapper roleMapper;

    public void run() throws Exception {
        log.info("deptSync 执行开始");
        deptSync();
        log.info("deptSync 执行结束");

        log.info("userSync 执行开始");
        userSync();
        log.info("userSync 执行结束");

        log.info("plateNumberSync 执行开始");
        plateNumberSync();
        log.info("plateNumberSync 执行结束");
    }

    private JSONObject getDatas(String api, int pagenum, int pagesize) {
        String res = HttpRequest.get(erpApiUrl + api)
                .header(header_key, header_value)
                .body("{\n" +
                        "    \"formData\":{\n" +
                        "        \"pageNum\":" + pagenum + ",\n" +
                        "        \"pageSize\":" + pagesize + "\n" +
                        "    },\n" +
                        "    \"product\":\"17\",\n" +
                        "    \"sign\":\"" + sign + "\"\n" +
                        "}").execute().body();
        JSONObject json = JSONObject.parseObject(res);
        return json;
    }

    private int gettotal(String api) {
        JSONObject json = getDatas(api, 0, 100);
        return json.getJSONObject("page").getInteger("totalCount");
    }

    /**
     * 部门数据同步
     */
    private void deptSync() {
        String api = "/api-third-party/busi/comm/usky/queryGroup";

        //计算总页数
        int total = gettotal(api);
        int pagesize = 100;
        int pagetotal = (total / pagesize);
        if (total % pagesize != 0) {
            pagetotal++;
        }

        log.info("pagetotal:"+pagetotal);
        //按页获取
        for (int k = 1; k <= pagetotal; k++) {
            JSONObject json = getDatas(api, k, pagesize);
            JSONArray datas = json.getJSONArray("data");
            JSONObject item;
            Dept dept;
            for (int i = 0; i < datas.size(); i++) {
                item = datas.getJSONObject(i);
                dept = new Dept();

                if (StringUtils.isBlank(item.getString("groupId"))) {
                    dept.setId(UUID.randomUUID().toString());
                } else {
                    dept.setId(item.getString("groupId"));
                }
                dept.setName(item.getString("groupName"));

                if (item.getString("parentId").equals("~")) {
                    dept.setPid(null);
                } else {
                    dept.setPid(item.getString("parentId"));
                }
                dept.setDeptSort(item.getInteger("sort"));
                dept.setEnabled(item.getBoolean("groupStatus"));
                dept.setTreeNames(item.getString("groupNamePath"));
                dept.setTreeIds(item.getString("groupIdPath"));
                dept.setDeptType(item.getInteger("groupType"));
                dept.setDescription(item.getString("groupName"));

                try {
                    DeptDto deptDto = deptService.findById(item.getString("groupId"));
                    if (deptDto != null) {
                        deptService.update(dept);
                    } else {
                        deptService.syncCreate(dept);
                    }
                } catch (Exception ex) {
                    System.out.println(JSONObject.toJSON(dept));
                }
            }
        }
    }

    /**
     * 人员数据同步
     */
    private void userSync() {

        String api = "/api-third-party/busi/comm/usky/queryUser";

        //计算总页数
        int total = gettotal(api);
        int pagesize = 100;
        int pagetotal = (total / pagesize);
        if (total % pagesize != 0) {
            pagetotal++;
        }

        log.info("pagetotal:"+pagetotal);
        //按页获取
        for (int k = 1; k <= pagetotal; k++) {
            JSONObject json = getDatas(api, k, pagesize);
            JSONArray datas = json.getJSONArray("data");
            JSONObject item;
            User user;
            UserDto userDto;
            Dept dept;
            DmUser dmUser;
            DmUserDto dmUserDto;
            for (int i = 0; i < datas.size(); i++) {
                item = datas.getJSONObject(i);
                user = new User();
                user.setId(item.getString("userId"));
                user.setUserCode(item.getString("userCode"));
                user.setNickName(item.getString("userName"));
                user.setUsername(item.getString("userAccount"));

                if(StringUtils.isBlank(item.getString("sex"))){
                    user.setGender("");
                }else{
                    user.setGender(item.getString("sex").equals("m") ? "男" : "女");
                }

                user.setEmail(item.getString("email"));
                user.setPhone(item.getString("mobile"));
                user.setEnabled(item.getInteger("userStatus") == 1);
                user.setIsAdmin(false);
                user.setOrgPassword("12345678");
                user.setUserRootGroupId(item.getString("userRootGroupId"));
                user.setUserRootGroupName(item.getString("userRootGroupName"));
                dept = new Dept();
                dept.setId(item.getString("userGroupId"));
                if (StringUtils.isBlank(dept.getId())) {
                    dept.setId("0001T110000000000UKL");
                }
                user.setDept(dept);

                Set<Job> jobs = new HashSet<Job>();
                Job job = new Job();
                job.setId(Long.valueOf(10));
                jobs.add(job);
                user.setJobs(jobs);

                dmUser = new DmUser();
                dmUser.setDept(dept);
                dmUser.setId(user.getId());
                dmUser.setEmail(user.getEmail());
                dmUser.setContacts(user.getPhone());
                dmUser.setName(user.getNickName());
                dmUser.setUsername(user.getUsername());
                dmUser.setSex(user.getGender());
                dmUser.setUserNumber(user.getUserCode());
                dmUser.setStatus(user.getEnabled());
                dmUser.setType("00");
                dmUser.setUserCode(user.getUserCode());
                dmUser.setUserRootGroupId(user.getUserRootGroupId());
                dmUser.setUserRootGroupName(user.getUserRootGroupName());
                dmUser.setJobs(jobs);

                try {
                    //1、入用户库
                    dmUserDto = dmUserService.findById(dmUser.getId());

                    if (dmUserDto != null) {
                        dmUserService.update(dmUser);
                    } else {
                        Set<Role> roles = new HashSet<Role>();
                        Role role = new Role();
                        role.setId(Long.valueOf(2));//普通用户
                        roles.add(role);
                        dmUser.setRoles(roles);
                        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
                        DmCardDto dmCardDto = dmCardService.create(new DmCard());
                        dmUser.setCardid(String.valueOf(dmCardDto.getId()));
                        dmUserService.create(dmUser);
                    }
                    user.setDmUser(dmUser);

                    //2、入账户库并与用户库关联
                    log.info("userCode:"+user.getUserCode());
                    userDto = userService.findById(user.getId());
                    if (userDto != null) {
                        //user.setPassword(passwordEncoder.encode("12345678"));
                        //user.setOssPassword(RsaUtils.encryptByPublicKey(RsaProperties.publicKey, "12345678"));
                        Set<Role> roles = new HashSet<Role>();
                        Role role = new Role();
                        for(RoleSmallDto roleSmallDto : userDto.getRoles()) {
                            role.setId(roleSmallDto.getId());//普通用户
                            roles.add(role);
                        }
                        user.setRoles(roles);
                        userService.updateSync(user);
                        dmUser.setOssPassword(userDto.getOssPassword());
                        dmUserService.update(dmUser);
                    } else {
                        Set<Role> roles = new HashSet<Role>();
                        Role role = new Role();
                        role.setId(Long.valueOf(2));//普通用户
                        roles.add(role);
                        user.setRoles(roles);
                        user.setPassword(passwordEncoder.encode("12345678"));
                        String ossPassword = RsaUtils.encryptByPublicKey(RsaProperties.publicKey, "12345678");
                        user.setOssPassword(ossPassword);
                        userService.createSync(user);
                        dmUser.setOssPassword(ossPassword);
                        dmUserService.update(dmUser);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //车牌及门禁设备数据同步
    private void plateNumberSync(){
        String url = "http://192.168.1.19:8000/api/thirdparty/v1/openInterface/getPlateNumber";
        //根据key拿到token
        Map<String,Object> newToken = SecurityUtils.getToken(key);
        //组装请求参数
        JSONObject param = new JSONObject();
        param.put("timestamp",newToken.get("timestamp"));
        param.put("nonce",newToken.get("nonce"));
        //请求车牌接口
        String res = HttpRequest.get(url)
                .header("XYTACCESSTOKEN",newToken.get("token").toString() )
                .body(param.toJSONString()).execute().body();
        if(StringUtils.isNotEmpty(res)) {
            log.info("res:"+res);
            JSONObject dataJSON = JSONObject.parseObject(res);
            String plateRumberArray = dataJSON.getString("data");
            if(!ObjectUtils.isEmpty(plateRumberArray)){
                //新增之前清空表数据
                dmPlateNumberRepository.deleteAll();
                dmRoomDeviceRepository.deleteAll();
                //进行新增
                JSONArray dataJSONArray = JSONArray.parseArray(plateRumberArray);
                for(int i = 0;i<dataJSONArray.size();i++){
                    String plateNumberJSON = dataJSONArray.getString(i);
                    DmPlateNumber plateNumber = JSONObject.parseObject(plateNumberJSON,DmPlateNumber.class);
                    Set<DmRoomDevice> dmRoomDevices = plateNumber.getDmRoomDevices();
                    dmRoomDeviceRepository.saveAll(dmRoomDevices);
                    dmPlateNumberRepository.save(plateNumber);
                }
//                List<DmPlateNumber> dmPlateNumberList = JSONArray.parseArray(plateRumberArray, DmPlateNumber.class);
//                dmPlateNumberRepository.saveAll(dmPlateNumberList);
            } else {
                log.info("plateRumberArray is null.");
            }
        } else {
            log.info("res is null.");
        }

    }
}