package com.mortals.xhx.module.attendance.web;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.ThreadPool;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.AppealResultEnum;
import com.mortals.xhx.common.code.ProcessStatusEnum;
import com.mortals.xhx.common.pdu.user.UserPdu;
import com.mortals.xhx.feign.user.IUserFeign;
import com.mortals.xhx.module.attendance.model.AttendanceLeaveRecordEntity;
import com.mortals.xhx.module.attendance.model.AttendanceLeaveRecordQuery;
import com.mortals.xhx.module.attendance.service.AttendanceLeaveRecordService;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.workman.model.WorkmanQuery;
import com.mortals.xhx.module.workman.service.WorkmanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toMap;

/**
 * 请假记录信息
 *
 * @author zxfei
 * @date 2023-04-07
 */
@RestController
@RequestMapping("attendance/leave/record")
public class AttendanceLeaveRecordController extends BaseCRUDJsonBodyMappingController<AttendanceLeaveRecordService, AttendanceLeaveRecordEntity, Long> {

    @Autowired
    private ParamService paramService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private WorkmanService workmanService;
    @Autowired
    private UserService userService;
//    @Autowired
//    private IUserFeign iUserFeign;

    public AttendanceLeaveRecordController() {
        super.setModuleDesc("请假记录信息");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "deptId", deptService.find(new DeptQuery()).stream().collect(toMap(x -> x.getId().toString(), y -> y.getDeptName(), (o, n) -> n)));
        this.addDict(model, "approverId", workmanService.find(new WorkmanQuery()).stream().collect(toMap(x -> x.getId().toString(), y -> y.getName(), (o, n) -> n)));
        this.addDict(model, "leaveType", paramService.getParamBySecondOrganize("AttendanceLeaveRecord", "leaveType"));
        this.addDict(model, "auditResult", AppealResultEnum.getEnumMap());
        this.addDict(model, "processStatus", ProcessStatusEnum.getEnumMap());
        this.addDict(model, "createUserId", userService.find(new UserQuery()).stream().collect(toMap(x -> x.getId().toString(), y -> y.getRealName(), (o, n) -> n)));

//        //从门户获取登录用户信息
//        UserPdu userPdu = new UserPdu();
//        userPdu.setSize(-1);
//        List <UserPdu> userPduList = iUserFeign.list(userPdu).getData().getData();
//        Map<String, String> ans = new HashMap<>();
//        for(UserPdu str: userPduList) {
//            if(str != null) {  //增加非空判断
//                ans.put(str.getId().toString(), str.getRealName());
//            }
//        }
//
//        this.addDict(model, "createUserId", ans);


        super.init(model, context);
    }


    /**
     * 主动同步拉取请假考勤记录
     */
    @PostMapping(value = "syncLeaveRecord")
    public String syncLeaveRecord(@RequestBody AttendanceLeaveRecordQuery query) {
        JSONObject jsonObject = new JSONObject();
        String busiDesc = this.getModuleDesc() + "主动同步拉取请假考勤记录";
        try {
            if (ObjectUtils.isEmpty(query.getStartTimeStart())) throw new AppException("开始时间不能为空");
            if (ObjectUtils.isEmpty(query.getEndTimeEnd())) {
                query.setEndTimeStart(DateUtil.today());
            }
            long between = DateUtil.between(DateUtil.parseDate(query.getStartTimeStart()), DateUtil.parseDate(query.getEndTimeEnd()), DateUnit.DAY, true);
            if (between > 120) throw new AppException("时间范围不能超过120天");
            Context context = this.getContext();
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    service.syncLeaveRecord(query, context);
                }
            });
            ThreadPool.getInstance().execute(thread);

            recordSysLog(request, busiDesc + " 【成功】");
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            jsonObject.put(KEY_RESULT_MSG, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error("主动同步拉取请假考勤记录", e);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            jsonObject.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return jsonObject.toJSONString();
    }


}