package com.jeeplus.centerservice.service.ccpm.reimbursement;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeeplus.centerservice.dto.SaveInfoDto;
import com.jeeplus.centerservice.dto.WorkInvoiceDetail;
import com.jeeplus.centerservice.enums.TaskAliasEnum;
import com.jeeplus.centerservice.service.ccpm.CcpmRequest;
import com.jeeplus.centerservice.service.ccpm.flow.FlowRequest;
import com.jeeplus.centerservice.utils.ConvertServiceUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class ReimbursementService {

    @Resource
    private CcpmRequest ccpmRequest;

    @Resource
    private FlowRequest flowRequest;

    /**
     * 查询报销待办详情
     * @param id
     * @param processDefKey  流程key：例如 13、102...
     * @return
     */
    public SaveInfoDto getReimbursementById(String id, String processDefKey) {
        SaveInfoDto saveInfoDto = new SaveInfoDto();
        Object response = ccpmRequest.getById(id, processDefKey); // 报销详情
        if (Objects.nonNull(response)) {
            saveInfoDto = ConvertServiceUtil.convertReim(response); // 格式转换
            if (Objects.nonNull(saveInfoDto) && StringUtils.isNotBlank(saveInfoDto.getProcInsId())) {
                // 流程流向图
                Object flowChart = flowRequest.getFlowChart(saveInfoDto.getProcInsId());
                if (Objects.nonNull(flowChart)) {
                    List<Map<String, Object>> flowCharts = (List)JSONArray.parseArray(JSON.toJSONString(flowChart)); // 格式转换
                    saveInfoDto.setFlowChart(flowCharts);
                }
                // 流程历史
                Object histoicFlow = flowRequest.getHistoicFlowList(saveInfoDto.getProcInsId());
                if (Objects.nonNull(histoicFlow)) {
                    List<Map<String, Object>> histoicFlows = (List)JSONArray.parseArray(JSON.toJSONString(histoicFlow));
                    List<Map<String, Object>> histoicFlowList = ConvertServiceUtil.convertHisFlowList(histoicFlows); // 格式转换
                    saveInfoDto.setHistoicFlowList(histoicFlowList);
                }
            }
        }
        return saveInfoDto;
    }

    /**
     * 报销审核通过、驳回
     * @param id
     * @param flag
     * @return
     */
    public Map<String, Object> reimAudit(String id, String flag, String comment, String processDefKey) {
        Map<String, Object> resultMap = new HashMap<>();
        Object response = ccpmRequest.getById(id, processDefKey); // 报销详情
        if (Objects.nonNull(response)) {
            Map<String, Object> resp = JSONObject.parseObject(JSON.toJSONString(response));
            Object result = ccpmRequest.saveAuditFunc(resp, flag, comment, processDefKey); // 审核通过、审核驳回
            if (Objects.nonNull(result)) {
                resultMap = JSONObject.parseObject(JSON.toJSONString(result));
            } else {
                resultMap.put("success", false);
                resultMap.put("message","操作失败");
            }
        } else {
            resultMap.put("success", false);
            resultMap.put("message","操作失败");
        }
        return resultMap;

    }

    /**
     * 删除报销待办
     * @param id
     * @return
     */
    public Map<String, Object> deleteReim(String id) {
        Map<String, Object> resultMap = new HashMap<>();
        Object result = flowRequest.deleteNotify(id, TaskAliasEnum.REIMBURSEMENT.getCcpmTaskAlias()); // 13代表报销模块
        if (Objects.nonNull(result)) {
            resultMap.putAll(JSONObject.parseObject(JSON.toJSONString(result)));
        } else {
            resultMap.put("code", 0);
            resultMap.put("msg", "报销信息删除失败");
        }
        return resultMap;
    }

    /**
     * 发票审核通过、驳回
     * @param id
     * @param flag
     * @return
     */
    public Map<String, Object> invoiceAudit(String id, String flag, String comment, String processDefKey,String jsonData) {
        Map<String, Object> resultMap = new HashMap<>();
        Object response = ccpmRequest.getInvoiceById(id, processDefKey); // 发票详情
        if (Objects.nonNull(response)) {
            Map<String, Object> respMap = JSONObject.parseObject(JSON.toJSONString(response));
            JSONObject resp = JSON.parseObject(jsonData);
            //将发票详情转为ccpm系统中的字段
            ArrayList<WorkInvoiceDetail> workInvoiceDetails = new ArrayList<>();
            if ("yes".equals(flag) && StringUtils.isNotBlank(resp.getString("workAccountList"))){
                List<WorkInvoiceDetail> workAccountList = JSON.parseArray(resp.getString("workAccountList"),WorkInvoiceDetail.class);
                if (CollectionUtil.isNotEmpty(workAccountList)){
                    for (WorkInvoiceDetail detail : workAccountList) {
                        WorkInvoiceDetail workInvoiceDetail = new WorkInvoiceDetail();
                        workInvoiceDetail.setCode(detail.getCode());//发票代码
                        workInvoiceDetail.setNumber(detail.getNumber());//发票号
                        workInvoiceDetail.setTotalMoney(detail.getAccount());//金额
                        workInvoiceDetail.setTaxRate(detail.getTax());//税率
                        workInvoiceDetail.setTax(detail.getAmount());//税额
                        workInvoiceDetail.setId("");
                        workInvoiceDetail.setState("正常");
                        workInvoiceDetail.setBackSign("正常");
                        workInvoiceDetails.add(workInvoiceDetail);
                    }
                }
                respMap.put("workAccountList",workInvoiceDetails);
                respMap.put("invoiceDate",resp.get("invoiceDate"));//开票时间
                respMap.put("takeDate",resp.get("takeDate"));//领票时间
                respMap.put("drawerName",resp.get("drawerName"));//开票人
            }

            Object result = ccpmRequest.saveInvoiceAuditFunc(respMap, flag, comment, processDefKey); // 审核通过、审核驳回
            if (Objects.nonNull(result)) {
                resultMap = JSONObject.parseObject(JSON.toJSONString(result));
            } else {
                resultMap.put("success", false);
                resultMap.put("message","操作失败");
            }
        } else {
            resultMap.put("success", false);
            resultMap.put("message","操作失败");
        }
        return resultMap;

    }

    /**
     * 查询发票号是否存在
     * @param number
     * @return
     */
    public boolean queryByNumber(String number) {
        boolean response = ccpmRequest.queryByNumber(number); // 查询发票号是否存在
        return response;
    }
}
