/*
 *  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.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.dm.company.domain.DmCompany;
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.JobService;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.utils.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

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

    private final String erpApiUrl = "http://121.31.41.88:29312";
    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 DeptService deptService;
    private final UserService userService;
    private final DmUserService dmUserService;
    private final PasswordEncoder passwordEncoder;

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

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

    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++;
        }

        //按页获取
        for (int k = 0; 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.create(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++;
        }

        //按页获取
        for (int k = 0; 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.setPassword(passwordEncoder.encode("12345678"));
                user.setEnabled(item.getInteger("userStatus") == 1);
                user.setIsAdmin(false);
                user.setOrgPassword("12345678");
                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("10");
                jobs.add(job);
                user.setJobs(jobs);

                Set<Role> roles = new HashSet<Role>();

                Role role = new Role();
                role.setId("2");//普通用户
                roles.add(role);
                user.setRoles(roles);
                dmUser = new DmUser();
                dmUser.setDept(dept);
                dmUser.setId(user.getId());
                dmUser.setEmail(user.getEmail());
                dmUser.setContacts(user.getPhone());
                dmUser.setName(user.getNickName());
                dmUser.setSex(user.getGender());
                dmUser.setUsercode(user.getUsercode());
                dmUser.setJobs(jobs);
                dmUser.setRoles(roles);

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

                    if (dmUserDto != null) {
                        dmUserService.update(dmUser);
                    } else {
                        dmUserService.create(dmUser);
                    }
                    user.setDmUser(dmUser);

                    //2、入账户库并与用户库关联
                    userDto = userService.findById(user.getId());
                    if (userDto != null) {
                        userService.update(user);
                    } else {
                        userService.create(user);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}