package com.ecep.contract.cloud.u8;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.SpringApp;
import com.ecep.contract.ds.other.service.DepartmentService;
import com.ecep.contract.model.Department;
import com.ecep.contract.model.Employee;
import com.ecep.contract.ui.Tasker;

/**
 * 用友U8系统-同步员工信息
 */
public class EmployeesSyncTask extends Tasker<Object> {
    private static final Logger logger = LoggerFactory.getLogger(EmployeesSyncTask.class);
    private final AtomicInteger counter = new AtomicInteger(0);

    DepartmentService departmentService;

    public EmployeesSyncTask() {
        updateTitle("用友U8系统-同步员工信息");
    }

    DepartmentService getDepartmentService() {
        if (departmentService == null) {
            departmentService = SpringApp.getBean(DepartmentService.class);
        }
        return departmentService;
    }

    @Override
    protected Object execute(MessageHolder holder) throws Exception {
        YongYouU8Service service = SpringApp.getBean(YongYouU8Service.class);

        holder.debug("读取 U8 系统 Person 数据表...");
        List<Map<String, Object>> list = service.queryAllPerson();
        int size = list.size();
        holder.debug("总共读取 Person 数据 " + size + " 条");

        for (Map<String, Object> rs : list) {
            if (isCancelled()) {
                holder.debug("Cancelled");
                return null;
            }

            MessageHolder sub = holder.sub(counter.get() + "/" + size + ">");
            sync(rs, sub);

            // 更新进度
            updateProgress(counter.incrementAndGet(), size);
        }
        return null;
    }

    private void sync(Map<String, Object> rs, MessageHolder holder) {
        String personCode = (String) rs.get("cPersonCode");
        String personName = (String) rs.get("cPersonName");
        String departmentCode = (String) rs.get("cDepCode");
        String personEmail = (String) rs.get("cPersonEmail");
        String personPhone = (String) rs.get("cPersonPhone");
        java.sql.Timestamp personValidDate = (java.sql.Timestamp) rs.get("dPValidDate");
        java.sql.Timestamp personInValidDate = (java.sql.Timestamp) rs.get("dPInValidDate");
        boolean modified = false;

        Employee employee = getEmployeeService().findByCode(personCode);
        // 按员工代码未匹配时，尝试使用名字去匹配
        if (employee == null) {
            employee = getEmployeeService().findByName(personName);
            if (employee == null) {
                employee = new Employee();
                employee.setCode(personCode);
                employee.setName(personName);
                employee.setActive(false);
                employee.setCreated(LocalDate.now());
                holder.info("创建员工：" + personCode + ", 姓名：" + personName + ".");

                // consumer.accept("员工编号：" + personCode + ", 姓名：" + personName + ", 本地未创建");
                // return;
            }
            employee.setCode(personCode);
            modified = true;
        }

        MessageHolder subHolder = holder.sub(personName + ": ");

        if (!StringUtils.hasText(employee.getName())) {
            employee.setName(personName);
            modified = true;
        }

        if (StringUtils.hasText(departmentCode)) {
            Department departmentByCode = getDepartmentService().findByCode(departmentCode);
            if (departmentByCode == null) {
                subHolder.warn("部门代码：" + departmentCode + "未匹配到部门");
            } else {
                if (!Objects.equals(employee.getDepartment(), departmentByCode)) {
                    employee.setDepartment(departmentByCode);
                    subHolder.info("更新部门：" + departmentByCode.getName());
                    modified = true;
                }
            }
        }

        if (StringUtils.hasText(personPhone)) {
            if (!Objects.equals(personPhone, employee.getPhone())) {
                employee.setPhone(personPhone);
                subHolder.info("更新电话：" + personPhone);
                modified = true;
            }
        }

        if (StringUtils.hasText(personEmail)) {
            if (!Objects.equals(personEmail, employee.getEmail())) {
                employee.setEmail(personEmail);
                subHolder.info("更新Email：" + personEmail);
                modified = true;
            }
        }

        if (personValidDate != null) {
            LocalDate localDate = personValidDate.toLocalDateTime().toLocalDate();
            if (!Objects.equals(localDate, employee.getEntryDate())) {
                employee.setEntryDate(localDate);
                subHolder.info("更新入职日期：" + localDate);
                modified = true;
            }
        }

        if (personInValidDate != null) {
            LocalDate localDate = personInValidDate.toLocalDateTime().toLocalDate();
            if (!Objects.equals(localDate, employee.getLeaveDate())) {
                employee.setLeaveDate(localDate);
                subHolder.info("更新离职日期：" + localDate);
                modified = true;
            }
        }

        if (modified) {
            getEmployeeService().save(employee);
            subHolder.info("更新保存");
        } else {
            subHolder.debug("无更新");
        }
    }
}
