package com.infoepoch.pms.dispatchassistant.controller.oa;

import com.infoepoch.pms.dispatchassistant.common.component.Result;
import com.infoepoch.pms.dispatchassistant.common.constant.StoreKeys;
import com.infoepoch.pms.dispatchassistant.common.utils.JsonUtils;
import com.infoepoch.pms.dispatchassistant.common.utils.StringUtils;
import com.infoepoch.pms.dispatchassistant.domain.basic.store.KeyValueStore;
import com.infoepoch.pms.dispatchassistant.domain.basic.store.KeyValueStoreService;
import com.infoepoch.pms.dispatchassistant.domain.oa.OaCriteria;
import com.infoepoch.pms.dispatchassistant.domain.oa.OaOrganizationService;
import com.infoepoch.pms.dispatchassistant.domain.oa.OaService;
import com.infoepoch.pms.dispatchassistant.domain.oa.OaUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/oa")
public class OaController {

    private final static Logger logger = LoggerFactory.getLogger(OaController.class);

    @Autowired
    private OaService oaService;
    @Autowired
    private OaUserService oaUserService;
    @Autowired
    private OaOrganizationService oaOrganizationService;

    @Autowired
    private KeyValueStoreService keyValueStoreService;

    /**
     * @param messageId 待办ID
     * @param moaFlag   moa标识
     * @param backUrl   返回地址
     * @param request
     * @param response
     */
    @RequestMapping("/todo-redirect")
    public void todoRedirect(@RequestParam(required = false) String messageId, @RequestParam(required = false) String moaFlag,
                             @RequestParam(required = false) String backUrl,
                             HttpServletRequest request, HttpServletResponse response) {
        try {
            oaService.oaTodoRedirect(messageId, moaFlag, backUrl, request, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param criteria
     * @return
     */
    @PostMapping("/account/sync-oa-employee-manual")
    public Result syncOAUserMaintainManual(@RequestBody OaCriteria criteria) {
        if (StringUtils.isNotBlank(criteria.getEmployeeNumber())) {
            oaUserService.syncOaEmployee(null, null, criteria.getEmployeeNumber());
            return Result.successData("同步成功");
        } else {
            oaUserService.syncOaEmployee(criteria.getStartLastUpdateDate(), criteria.getEndLastUpdateDate(), null);
            return Result.successData("同步成功");
        }
    }

    /**
     * 同步用户信息
     *
     * @param runtimeTaskId
     */
    @GetMapping("/account/sync-oa-employee")
    public void syncOAUserMaintain(String runtimeTaskId) {
        OaCriteria criteria;
        String criteriaStr = keyValueStoreService.queryValueByKey(StoreKeys.OA_EMPLOYEE_SYNC_CRITERIA);
        if (StringUtils.isBlank(criteriaStr)) {
            criteria = new OaCriteria();
            criteria.setStartLastUpdateDate(new Date());
            criteria.setEndLastUpdateDate(new Date());
            keyValueStoreService.addKeyValue(new KeyValueStore(
                    StoreKeys.OA_EMPLOYEE_SYNC_CRITERIA,
                    JsonUtils.objectToJson(criteria)
            ));
        } else {
            try {
                criteria = JsonUtils.jsonToObject(criteriaStr, OaCriteria.class);
                if (criteria.getStartLastUpdateDate() == null) {
                    criteria.setStartLastUpdateDate(new Date());
                }
                if (criteria.getEndLastUpdateDate() == null) {
                    criteria.setEndLastUpdateDate(new Date());
                }
                criteria.setEmployeeNumber(null);
            } catch (Exception e) {
                criteria = new OaCriteria();
                criteria.setStartLastUpdateDate(new Date());
                criteria.setEndLastUpdateDate(new Date());
                keyValueStoreService.addKeyValue(new KeyValueStore(
                        StoreKeys.OA_EMPLOYEE_SYNC_CRITERIA,
                        JsonUtils.objectToJson(criteria)
                ));
            }
        }
        oaUserService.scheduleSyncOaEmployee(criteria.getStartLastUpdateDate(), criteria.getEndLastUpdateDate());
        criteria.setStartLastUpdateDate(criteria.getEndLastUpdateDate());
        criteria.setEndLastUpdateDate(null);
        keyValueStoreService.modifyKeyValue(new KeyValueStore(
                StoreKeys.OA_EMPLOYEE_SYNC_CRITERIA,
                JsonUtils.objectToJson(criteria)
        ));
    }

    /**
     * @param criteria
     * @return
     */
    @PostMapping("/sync-organization-manual")
    public Result syncOrganizationManual(@RequestBody OaCriteria criteria) {
        try {
            oaOrganizationService.syncOaOrganization(criteria.getStartLastUpdateDate(), criteria.getEndLastUpdateDate(), criteria.getOrgCode());
        } catch (Exception e) {
            logger.info(e.getMessage());
            return Result.successData("同步失败");
        }
        return Result.successData("同步成功");
    }

    /**
     * 同步组织信息
     *
     * @param runtimeTaskId
     */
    @GetMapping("/sync-organization")
    public void syncOrganization(String runtimeTaskId) {
        OaCriteria criteria;
        String criteriaStr = keyValueStoreService.queryValueByKey(StoreKeys.OA_ORGANIZATION_SYNC_CRITERIA);
        if (StringUtils.isBlank(criteriaStr)) {
            criteria = new OaCriteria();
            criteria.setStartLastUpdateDate(new Date());
            criteria.setEndLastUpdateDate(new Date());
            keyValueStoreService.addKeyValue(new KeyValueStore(
                    StoreKeys.OA_ORGANIZATION_SYNC_CRITERIA,
                    JsonUtils.objectToJson(criteria)
            ));
        } else {
            try {
                criteria = JsonUtils.jsonToObject(criteriaStr, OaCriteria.class);
                if (criteria.getStartLastUpdateDate() == null) {
                    criteria.setStartLastUpdateDate(new Date());
                }
                if (criteria.getEndLastUpdateDate() == null) {
                    criteria.setEndLastUpdateDate(new Date());
                }
                criteria.setOrgCode(null);
            } catch (Exception e) {
                criteria = new OaCriteria();
                criteria.setStartLastUpdateDate(new Date());
                criteria.setEndLastUpdateDate(new Date());
                keyValueStoreService.addKeyValue(new KeyValueStore(
                        StoreKeys.OA_ORGANIZATION_SYNC_CRITERIA,
                        JsonUtils.objectToJson(criteria)
                ));
            }
        }
        oaOrganizationService.scheduleSyncOaOrganization(criteria.getStartLastUpdateDate(), criteria.getEndLastUpdateDate());
        criteria.setStartLastUpdateDate(criteria.getEndLastUpdateDate());
        criteria.setEndLastUpdateDate(null);
        keyValueStoreService.modifyKeyValue(new KeyValueStore(
                StoreKeys.OA_ORGANIZATION_SYNC_CRITERIA,
                JsonUtils.objectToJson(criteria)
        ));
    }

}
