package com.malk.ruisi.service.impl;

import com.alibaba.fastjson.JSON;
import com.malk.ruisi.service.RSService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McException;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class RSImplService implements RSService {

    @Autowired
    private YDService ydService;

    @Autowired
    private YDClient ydClient;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private DDClient ddClient;

    @Autowired
    private static final long DEPT_ID = 933074211L; // 合作加盟校区


    /// 创建企业账号: loginI/userId 都为 SHR 工号
    private void createExclusiveUser(String loginId, String name) {

        final String PASS_WORD = "tzr@111111";

        Map info = UtilMap.map("userid", loginId);
        ddClient_contacts.createUser_dingTalk(ddClient.getAccessToken(), loginId, PASS_WORD, name, Arrays.asList(DEPT_ID), info);
    }

    /**
     * 同步钉钉企业账号
     */
    @Override
    public void syncDingTalk_exclusive() {

        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .formUuid("FORM-11B80FC621CA4DB9A35364CFBFF7287538KR")
                .build());
        dataList.forEach(data -> {
            if (!"是".equals(UtilMap.getString(data, "radioField_m0hlup9w"))) {
                String userId = UtilMap.getString(data, "textField_lztc6k3k");
                String message = "";
                try {
                    this.createExclusiveUser(userId, UtilMap.getString(data, "textField_lxsm8xow"));
                } catch (McException e) {
                    message = e.getMessage();
                    log.error(e.getMessage(), e);
                }
                ydClient.operateData(YDParam.builder()
                        .formInstanceId(UtilMap.getString(data, "instanceId"))
                        .useLatestVersion(true)
                        .updateFormDataJson(JSON.toJSONString(UtilMap.map("radioField_m0hlup9w, employeeField_m0hlup9v, textareaField_m0hs4k90", "是", Arrays.asList(userId), message)))
                        .build(), YDConf.FORM_OPERATION.update);
            }
        });
    }
    
    /**
     * 重置企业账号密码
     */
    @Override
    public void resetPwd(Map data) {
        ddClient_contacts.updateUser_dingTalk(ddClient.getAccessToken(), UtilMap.getString(data, "userId"), Arrays.asList(DEPT_ID), UtilMap.map("init_password", UtilMap.getString(data, "password")));
    }
}
