package com.foreverwin.mesnac.dataimport.handler;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mesnac.common.dto.UsrDto;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.service.UserService;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.dataimport.handler.base.BaseHandler;
import com.foreverwin.mesnac.dataimport.reader.FileReader;
import com.foreverwin.mesnac.dataimport.reader.FileReaderBuilder;
import com.foreverwin.mesnac.dataimport.reader.RowVisitor;
import com.foreverwin.mesnac.dataimport.service.MasterObjectDefine;
import com.foreverwin.mesnac.dispatch.mapper.UserResourceMapper;
import com.foreverwin.mesnac.dispatch.model.UserResource;
import com.foreverwin.mesnac.dispatch.service.UserResourceService;
import com.foreverwin.mesnac.meapi.mapper.NwaUserMapper;
import com.foreverwin.mesnac.meapi.mapper.ResrceMapper;
import com.foreverwin.mesnac.meapi.model.Resrce;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.I18nUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


/**
 * @Description TODO
 * @Author zhaojiawei
 * @Since 2021-07-29
 */
public class UserResourceHandler extends BaseHandler {

    @Autowired
    private ResrceMapper resrceMapper;

    @Autowired
    private UserResourceService userResourceService;

    @Autowired
    private NwaUserMapper nwaUserMapper;

    @Autowired
    private UserResourceMapper userResourceMapper;

    @Autowired
    private UserService userService;

    @Override
    public String importFile(String site, InputStream inputStream, String fileType, String mode) throws Exception {
        int row = 0;
        StringBuffer buffer = new StringBuffer();
        Integer[] failedNumber = new Integer[]{0};

        try {
            FileReader fileReader = new FileReaderBuilder().build(fileType);
            RowVisitor<JSONObject> visitor = getRowVisitor(site, mode, buffer, failedNumber);
            row = fileReader.visitor(visitor).read(inputStream, getHeaders());
        } catch (Exception e) {
            buffer.append(e.getMessage() + "\n");
        }

//        if (buffer.length() > 0) {
//            buffer.insert(0, I18nUtil.getI18nText("MaterData.import.Summary", new Object[]{row + failedNumber[0], row, failedNumber[0]}) + "\n");
//            throw BusinessException.build(buffer.toString());
//        }
        buffer.insert(0, I18nUtil.getI18nText("MaterData.import.Summary", new Object[]{row + failedNumber[0], row, failedNumber[0]}) + "\n");

        return buffer.toString();
    }

    @Override
    public Map<String, String> getHeaders() {
        return MasterObjectDefine.getHeadsMapping("USER_RESOURCE");
    }

    public RowVisitor<JSONObject> getRowVisitor(String site, String mode, StringBuffer buffer, Integer[] failedNumber) {

        return new RowVisitor<JSONObject>() {

            @Override
            public int visit(long index, JSONObject jsonObject) {

                Object[] params = new Object[10];
                params[0] = index;
                params[1] = jsonObject.getString("resrce");

                String resultMessage = null;

                LocalDateTime now = LocalDateTime.now();
                String user = CommonMethods.getUser();
                String resrce = StringUtil.toString(jsonObject.getString("resrce"));
               // String resrceDescription = StringUtil.toString(jsonObject.getString("resrceDescription"));
                String userId = StringUtil.toString(jsonObject.getString("userId"));
                String userDescription = StringUtil.toString(jsonObject.getString("userDescription"));
                String temporaryUser = StringUtil.toString(jsonObject.getString("temporaryUser"));
                String status = StringUtil.toString(jsonObject.getString("status"));
                UserResource userResource = new UserResource();
                userResource.setHandle(HandleEnum.USER_RESOURCE.getHandle(site, resrce, userId));
                userResource.setSite(site);
                userResource.setResourceBo(HandleEnum.RESOURCE.getHandle(site,resrce));
                userResource.setResrce(resrce);
              //  userResource.setResrceDescription(resrceDescription);
                userResource.setUserId(userId);
                userResource.setUserDescription(userDescription);
                if("是".equals(temporaryUser)){
                    userResource.setTemporaryUser("true");
                }else {
                    userResource.setTemporaryUser("false");
                }

                if("否".equals(status)){
                    userResource.setStatus("false");
                }else {
                    userResource.setStatus("true");
                }

                //判断是否是更新还是插入，如果是更新，则没有创建时间和人员
                UserResource result = userResourceMapper.selectById(userResource.getHandle());
                if(result == null){
                    userResource.setCreatedUser(user);
                    userResource.setCreatedDateTime(now);
                }
                userResource.setModifiedUser(user);
                userResource.setModifiedDateTime(now);
                //如果资源为空或者员工编号为空，则直接跳过
                if (StringUtil.notEmpty(resrce) && StringUtil.notEmpty(userId)) {
                    //站点
                    jsonObject.put("site", site);
                    //不管用户选啥模式，都是更新和插入
                    resultMessage = updateAndInsert(userResource,index);
                    if (resultMessage != null) {
                        params[2] = resultMessage;
                        failedNumber[0]++;
                        buffer.append("第" + index + "行：" + I18nUtil.getI18nText("MaterData.import.update.fail", params) + "\n");
                        return 0;
                    }
                    return 1;
                }
                return 0;
            }

            @Override
            public String[] getHeader() {
                return null;
            }
        };
    }

    String updateAndInsert(UserResource userResource, Long index){
        //判断资源是否存在
        Resrce resrce = resrceMapper.selectById(userResource.getResourceBo());

        if(resrce == null){
            return  "第"+index+"行的资源不存在";
        }
        //设置资源描述
        userResource.setResrceDescription(resrce.getDescription());
        userResource.setExistUser("false");
        //设置员工描述
        List<UsrDto> userList = userService.findList(userResource.getUserId());
        if(userList != null && userList.size() > 0){
            userResource.setUserDescription(userList.get(0).getFullName());
            userResource.setExistUser("true");
        }else if("true".equals(userResource.getTemporaryUser())){
            //不做任何操作
        }else{
            return "第"+index+"行的用户不存在，必须为临时员工";
        }
        userResourceService.saveOrUpdate(userResource);
        return null;
    }

}
