zm
2020-05-18 a18bfacbf56b401f6e0fdae8710fbca4df8cff77
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package com.changhong.epc.parsing.service.asset.account;
 
import com.changhong.epc.bean.admin.Account;
import com.changhong.epc.bean.admin.AssetDepreciation;
import com.changhong.epc.bean.admin.CorresElField;
import com.changhong.epc.bean.form.SectoralAssets;
import com.changhong.epc.bean.tenant.asset.FixedAsset;
import com.changhong.epc.bean.tenant.asset.FixedSummary;
import com.changhong.epc.bean.tenant.sunCloud.AccountData;
import com.changhong.epc.bean.tenant.sunCloud.OrderInfo;
import com.changhong.epc.bean.tenant.sunCloud.PayInfo;
import com.changhong.epc.bean.tenant.system.SystemConfig;
import com.changhong.epc.bean.tenant.system.SystemForm;
import com.changhong.epc.constter.admin.AdminUrlConst;
import com.changhong.epc.constter.base.BaseConst;
import com.changhong.epc.constter.exception.EPCServiceException;
import com.changhong.epc.constter.form.budget.BudgetMsg;
import com.changhong.epc.constter.system.SystemClients;
import com.changhong.epc.constter.system.SystemConst;
import com.changhong.epc.constter.system.run.EpcRestInterface;
import com.changhong.epc.parsing.mapper.tenant.asset.FixedAssetMapper;
import com.changhong.epc.parsing.mapper.tenant.asset.FixedSummaryMapper;
import com.changhong.epc.parsing.mapper.tenant.asset.SectoralAssetsMapper;
import com.changhong.epc.parsing.service.asset.AssetHandle;
import com.changhong.epc.rely.api.bean.*;
import com.changhong.epc.rely.api.epc.admin.CorresElFieldApi;
import com.changhong.epc.rely.api.epc.admin.asset.AssetDepreciationApi;
import com.changhong.epc.rely.api.epc.tenant.SystemConfigApi;
import com.changhong.epc.rely.api.service.CscApiService;
import com.iemsoft.framework.cloud.core.base.ResMsg;
import com.iemsoft.framework.cloud.core.thread.ThreadData;
import com.iemsoft.framework.cloud.core.tools.*;
import com.iemsoft.framework.cloud.ribbon.RestInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 记账处理
 */
@Service
@Scope("prototype")
@Slf4j
public class AccountHandleImpl implements AssetHandle, BaseConst, SystemConst, BudgetMsg, SystemClients {
 
    //报销说明
    private static final String DESC = "固定资产折旧";
 
    //贷方文本
    private static final String CREDITITEM = "creditItem";
 
    //借方文本
    private static final String DEBITITEM = "debitItem";
 
    private static final String BILL_CODE = "billModelCode";
 
    //业务系统
    private static final Integer SERVICE_ID = 8;
 
    //当前业务类型code
    private static final String ORDER_COST_TYPE = "orderCostType";
 
    //报销单标号首字母
    private static final String D = "D";
 
    //申请单标号首字母
    private static final String S = "S";
 
    //编号固定位数
    private static final Integer NUM = 10;
 
    @Resource
    private FixedSummaryMapper fixedSummaryMapper;
 
    @Resource
    private SectoralAssetsMapper sectoralAssetsMapper;
 
    @Resource
    private CorresElFieldApi corresElFieldApi;
 
    @Resource
    private SystemConfigApi systemConfigApi;
 
    @Resource
    private CscApiService cscApiService;
 
    @Resource
    private FixedAssetMapper fixedAssetMapper;
 
    @Resource
    private AssetDepreciationApi assetDepreciationApi;
 
    private String yesCode;
 
    private boolean account;
 
    private String formId;
 
    private SectoralAssets sectoralAsset;
 
    private Organization orgInfo;
 
    private String date;
 
    private AssetDepreciation assetDepreciation;
 
    @Override
    public boolean validate(AssetDepreciation assetDepreciation) {
        log.debug("开始验证记账");
        yesCode = corresElFieldApi.getVal(ASSET_IS_SECTORAL, CorresElField::getMdCode);
        account = assetDepreciationApi.assetIsAccount();
        formId = systemConfigApi.getVal(SystemConfig.ofKey(FORM_INFO, SystemForm.ASSET_FORM_ID.name()), SystemConfig::getCvalue);
 
        FixedSummary fixedSummary = fixedSummaryMapper.getMaxDateFixedSummary(FixedSummary.of(assetDepreciation.getOrgCode()));
        // 计提成功过的才可以记账
        if(!Objects.equals(fixedSummary.getCountingState(), DEPRECIATION_SUCCESS)){
            throw new EPCServiceException(ACCOUNT_NOT_DEPRECIATION);
        }
        // 有新资产未计提不可以记账
        if(notAssetDepreciation(assetDepreciation)){
            throw new EPCServiceException(NEW_ASSET_NOT_DEPRECIATION);
        }
        // 需要启用固定资产记账
        if(!account){
            throw new EPCServiceException(NOT_ACCOUNT_SERVER);
        }
        return true;
    }
 
    private boolean notAssetDepreciation(AssetDepreciation assetDepreciation) {
        return fixedAssetMapper.notAssetDepreciation(
                assetDepreciation.getOrgCode()
                , assetDepreciation.getDate()
                , yesCode
                , formId
        ) != 0;
 
    }
 
    public PayInfo to(FixedAsset fixedAsset){
        PayInfo pay = new PayInfo();
        pay.setAgent(fixedAsset.getKeepingUserName());
        pay.setBatchAmount(String.valueOf(fixedAsset.getCurrentDepreciation()));
        pay.setDebitItem(getItemInfo(CREDITITEM, orgInfo, date));
        pay.setExpenDept(fixedAsset.getUseDepartmentName());
        pay.setAssetCategory(fixedAsset.getAssetsTypeName());
        return pay;
    }
 
    @Override
    public void handle(AssetDepreciation assetDepreciation) {
        date = assetDepreciation.getDate();
        this.assetDepreciation = assetDepreciation;
        orgInfo = cscApiService.findOneOrgByOrgCode(assetDepreciation.getOrgCode());
        String curr = systemConfigApi.getSystemConfig(SystemConfig.ofKey(UNIT_CURRENCY, UNIT_CURRENCY)).getCvalue();
 
        Map<String,Object> data = new HashMap<>();
        sectoralAsset = sectoralAssetsMapper.findOrgAssert(date, orgInfo.getCode());
 
        List<FixedAsset> fixedAssets = fixedAssetMapper.select(FixedAsset.of(assetDepreciation.getOrgCode(), assetDepreciation.getDate()));
 
        List<PayInfo> list =
                Optional.ofNullable(fixedAssets)
                .orElse(new ArrayList<>())
                .stream()
                .map(this::to)
                .collect(Collectors.toList());
 
        FixedSummary fixedSummary = new FixedSummary();
 
        //获取报销单Code
        String reqCode = generateCode(date,orgInfo.getId(),D);
        AccountData accountData = new AccountData();
 
        accountData.setExpenDept(Optional.ofNullable(orgInfo).map(Organization::getName).orElse(""));
        accountData.setOrderCode(createOrderCode(date, orgInfo.getCode(), sectoralAsset));
        accountData.setBillModelCode(getConstant(BILL_CODE));
        accountData.setExpenDesc(DESC);
        accountData.setMoney(sectoralAsset.getCurrentDepreciation());
        accountData.setDepreciationPeriod(sectoralAsset.getCalculationData());
        accountData.setExNumber(reqCode);
        //贷方文本
        accountData.setCreditItem(getItemInfo(DEBITITEM, orgInfo, date));
        //币种
        accountData.setCurrencyCode(curr);
        //处理参数,开始记账
        accountData.setPayInfos(list);
 
        String openId = ThreadData.get(OPEN_ID);
        data.put("openId",openId);
        log.debug("openId:"+openId);
        data.put("accountData", accountData);
        log.debug("固定资产记账, 编号:{}, 内容:{}", reqCode, JSONTool.toJson(data));
        Map<String,Object> res = cscApiService.orderAccountFyy(data);
        if(res!=null && res.get("orderCode") != null && !"".equals(res.get("orderCode"))) {
            assetDepreciation.setOrderCode(Objects.toString(res.get("orderCode")));
            fixedSummary.setOrderCode(assetDepreciation.getOrderCode());
            log.debug("记账成功!");//状态改为记账中
//            fixedSummary.setBookkeepingState(DEPRECIATION_SUCCESS);
            //向订单配置表里 添加
            Account account = new Account();
            account.setTenantId(ThreadData.get(TENANT_ID));
            account.setDataRowNum(String.valueOf(sectoralAsset.getId()));
            account.setCompanyId(String.valueOf(ThreadData.get(COMPANY_ID)));
            account.setOpenId(openId);
            account.setOrderCode(res.get("orderCode").toString());
            account.setDataStart(4);
            account.initParam();
            RestInterface restInterface = SpringUtil.getBean(SERVER_ADMIN.getBeanName(), RestInterface.class);
            restInterface.post(AdminUrlConst.ACCOUNT_ADD,account , ResMsg.class, EpcRestInterface.getEpcHeads()).getData();
        }else {
            log.debug("记账异常!");
            fixedSummary.setBookkeepingState(ACCOUNT_ERROR);
        }
 
        fixedSummary.setNumber(reqCode);
 
        fixedSummary.setUseDepartment(assetDepreciation.getOrgCode());
        fixedSummary.setBookkeepingData(DateTool.currentFormatDate(DateTool.DATE_PATTERN));
        fixedSummary.setCalculationPeriod(assetDepreciation.getDate());
        fixedSummaryMapper.updateFixedSummary(fixedSummary);
    }
 
    private String getItemInfo(String key, Organization org, String date) {
        Date ym = DateTool.stringToDate(date);
        return MessageFormat.format(
                systemConfigApi.getVal(SystemConfig.ofKey(ASSET, key), SystemConfig::getCvalue)
                , Optional.ofNullable(org).map(Organization::getName).orElse("")
                , DateTool.dateToString(ym, "YYYY")
                , DateTool.dateToString(ym, "MM"));
    }
 
    /**
     * 获取订单号
     */
    public String createOrderCode(String date, String orgCode,SectoralAssets sectoralAsset){
        //创建订单所需参数
        String tenantId = ThreadData.get(TENANT_ID);
        Organizations orgs = cscApiService.findRelationDetail();
        TenantsAndCompanys tenantsAndCompanys = cscApiService.findTenantsAndCompanys();
        Tenant t = tenantsAndCompanys.getTenants().stream().filter(key->key.getId()==Integer.parseInt(tenantId))
            .findFirst().orElse(new Tenant());
        log.debug("当前折旧租户:"+JSONTool.toJson(t));
        Company company = t.getCompanys().stream().filter(key->key.getId()==ThreadData.get(COMPANY_ID))
                .findFirst().orElse(new Company());
        log.debug("当前折旧公司:"+ JSONTool.toJson(company));
        OrderInfo orderInfo = new OrderInfo();
        getId(orgs.getOrgs(),orderInfo,ThreadData.get(OPEN_ID));
        orderInfo.setOrgCode(company.getOrgCode());
        orderInfo.setTenantId(tenantId);
        orderInfo.setCompanyId(company.getHotInfoCompanyId());
//        申请单号
        orderInfo.setReqBillCode(generateCode(date,Objects.toString(sectoralAsset.getId()), S));
        //是否加急
        orderInfo.setUrgent(0);
        //订单说明
        orderInfo.setRemark(DESC);
        //业务类型id
        orderInfo.setBussTypeId(
                SpringUtil.getBean(SystemConfigApi.class)
                        .getVal(SystemConfig.ofKey(ASSET, ORDER_COST_TYPE), SystemConfig::getCvalue));
        //业务系统id费用云为8
        orderInfo.setSource(SERVICE_ID);
        String orderCode = cscApiService.addOrder(JSONTool.toObj(JSONTool.toJson(orderInfo),Map.class));
        log.debug("创建订单返回orderCode:"+orderCode);
        Assert.condition(orderCode == null, CREATE_ORDERCODE_ERR);
        return orderCode;
    }
 
    /**
     * 生成申请单编号
     */
    public String generateCode(String date,String id,String c){
        String a = id+date.replaceAll("-","");
        //编号固定
        StringBuffer code = new StringBuffer(c);
        for(int i=1;i<NUM-a.length();i++){
            code.append("0");
        }
        code.append(a);
        return code.toString();
    }
 
 
    public String getConstant(String key){
        CorresElField corresElField = corresElFieldApi.getCorresElField(key);
        if(ObjectUtil.empty(corresElField)) {
            return "";
        }else{
            return corresElField.getMdCode();
        }
    }
 
 
    public String getId(List<Organization> children,OrderInfo pro,String openId){
        boolean flag = true;
        if (ObjectUtil.empty(children)) {
            return null;
        }
        for(Organization o :children){
            if(!ObjectUtil.empty(o.getUsers())){
                for(User u: o.getUsers()){
                    if(openId.equals(u.getOpenId())){
                        pro.setCscUserId(u.getId());
                        flag = false;
                        break;
                    }
                }
            }
            if(flag && !ObjectUtil.empty(o.getChildren())){
                this.getId(o.getChildren(), pro, openId);
            }
 
        }
        return null;
    }
}