package com.xjrsoft.module.asset.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.asset.entity.WfAssetManage;
import com.xjrsoft.module.asset.entity.WfAssetManageInventory;
import com.xjrsoft.module.asset.mapper.WfAssetManageInventoryMapper;
import com.xjrsoft.module.asset.service.IWfAssetManageInventoryService;
import com.xjrsoft.module.asset.service.IWfAssetManageService;
import com.xjrsoft.module.asset.vo.BaseOfficeBuildVo;
import com.xjrsoft.module.base.entity.BaseOfficeBuild;
import com.xjrsoft.module.concat.service.IXjrUserService;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.entity.Role;
import com.xjrsoft.module.organization.entity.UserRoleRelation;
import com.xjrsoft.module.organization.service.IDepartmentService;
import com.xjrsoft.module.system.entity.File;
import com.xjrsoft.module.system.service.IFileService;
import com.xjrsoft.module.teacher.entity.XjrUser;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @title: 资产管理盘点
* @Author szs
* @Date: 2024-04-07
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class WfAssetManageInventoryServiceImpl extends MPJBaseServiceImpl<WfAssetManageInventoryMapper, WfAssetManageInventory> implements IWfAssetManageInventoryService {

    private final IFileService fileService;

    private final IWfAssetManageService wfAssetManageService;

    private final IXjrUserService xjrUserService;

    private final IDepartmentService departmentService;

    @Override
    public void dataCache(Long formId) {
        WfAssetManageInventory wfAssetManageInventory = this.getById(formId);

        if(wfAssetManageInventory != null){
            List<File> fileList = fileService.list(Wrappers.<File>query().lambda().eq(File::getFolderId, wfAssetManageInventory.getFolderId()));
            List<WfAssetManage> wfAssetManageList = new ArrayList<>();

            //部门信息
            List<Department> departmentList = departmentService.list();
            Map<String, Department> departmentListMap = departmentList.stream().collect(Collectors.toMap(Department::getName, a -> a, (k1, k2) -> k1));

            //教职工信息
            List<XjrUser> xjrUserList = xjrUserService.list(new MPJLambdaWrapper<XjrUser>()
                    .disableSubLogicDel()
                    .select(XjrUser::getId)
                    .select(XjrUser.class, x -> VoToColumnUtil.fieldsToColumns(XjrUser.class).contains(x.getProperty()))
                    .leftJoin(UserRoleRelation.class, UserRoleRelation::getUserId, XjrUser::getId)
                    .leftJoin(Role.class, Role::getId, UserRoleRelation::getRoleId)
                    .eq(Role::getId, 2)
            );
            Map<String, XjrUser> xjrUsersMap = xjrUserList.stream().collect(Collectors.toMap(XjrUser::getName, a -> a, (k1, k2) -> k1));

            ObjectMapper objectMapper = new ObjectMapper();

            for (int i = 0; i < fileList.size(); i++) {
                InputStream inputStream = null;
                try {
                    URL url = new URL(fileList.get(i).getFileUrl());
                    URLConnection conn = url.openConnection();
                    inputStream = conn.getInputStream();

                    List<Map<Integer, Object>> dataList = EasyExcel.read(inputStream).sheet().headRowNumber(0).doReadSync();
                    if(!dataList.isEmpty()){
                        Map<Integer, Object> head = dataList.get(0);
                        for (int j = 1; j < dataList.size(); j++){
                            Map<Integer, Object> eachRecord = dataList.get(j);

                            WfAssetManage wfAssetManage = new WfAssetManage();
                            wfAssetManage.setAssetType((String) eachRecord.get(0));
                            wfAssetManage.setAssetCategory((String) eachRecord.get(1));
                            wfAssetManage.setAssetSpecies((String) eachRecord.get(2));
                            wfAssetManage.setName((String) eachRecord.get(3));
                            if(eachRecord.get(4) != null){
                                XjrUser xjrUser = xjrUsersMap.get((String) eachRecord.get(4));
                                if(xjrUser != null){
                                    wfAssetManage.setUserId(xjrUser.getId());
                                }
                            }
                            if(eachRecord.get(5) != null){
                                Department department = departmentListMap.get((String) eachRecord.get(5));
                                if(department != null){
                                    wfAssetManage.setDeptId(department.getId());
                                }
                            }
                            wfAssetManage.setAmount(new BigDecimal((String) eachRecord.get(6)));

                            Map<String, Object> extendJsonMap = new HashMap<>();
                            for (int k = 7; k < head.size(); k++) {
                                extendJsonMap.put((String) head.get(k), eachRecord.get(k));
                            }

                            String extendJson = objectMapper.writeValueAsString(extendJsonMap);
                            wfAssetManage.setExtendJson(extendJson);
                            wfAssetManageList.add(wfAssetManage);
                        }
                        wfAssetManageService.saveBatch(wfAssetManageList);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }finally {
                    try {
                        if(inputStream != null){
                            inputStream.close();
                        }
                    }catch (IOException ignored){

                    }
                }
            }
        }
    }
}
