package com.sifang.modules.customer.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.sifang.modules.completionrectification.dao.CompletionDao;
import com.sifang.modules.completionrectification.dao.RectificationDao;
import com.sifang.modules.completionrectification.dao.RectificationInfoDetailDao;
import com.sifang.modules.completionrectification.entity.CrmCompletionInfo;
import com.sifang.modules.completionrectification.entity.CrmRectificationInfo;
import com.sifang.modules.completionrectification.entity.CrmRectificationInfoDetail;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.dao.CrmCustomerIncomingApplicationDao;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CrmCustomerIncomingApplication;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.partner.service.GuangfaOperatingService;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.entity.Operator;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @title: GuangFaAcceptReformedService
 * @Author Tan
 * @Date: 2024/10/14 13:50
 * @Version 1.0
 */
@Service
public class GuangFaAcceptReformedService extends BaseService {

    @Autowired
    private GuangfaOperatingService guangfaOperatingService;

    @Autowired
    private CompletionDao completionDao;

    @Autowired
    private RectificationDao rectificationDao;

    @Autowired
    private RectificationInfoDetailDao rectificationInfoDetailDao;

    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    CustomerEntryDao customerDao;

    @Autowired
    private CustomerEntryMsgService msgService;

    Logger logger = LoggerFactory.getLogger(getClass());

    //竣工状态查询
    @Transactional(rollbackFor = Exception.class)
    public void acceptResultQry(String acceptNoList){
        Operator operator = Operator.of("1", "资方-广发", "资方");
        Map<String,Object> map = new HashMap<>();
        map.put("acceptNoList",acceptNoList);
        //调用竣工查询接口
        JSONArray jsonArrayAccept = guangfaOperatingService.acceptResultQry(map);
        logger.info("竣工查询接口返回："+jsonArrayAccept);
        if(jsonArrayAccept.size() > 0) {
            for (int k = 0; k < jsonArrayAccept.size(); k++) {
                JSONObject arrayAccept = jsonArrayAccept.getJSONObject(k);
                String acceptNo = arrayAccept.getString("acceptNo");
                String checkState = arrayAccept.getString("checkState");
                CrmCompletionInfo completionInfo = completionDao.findCompletionByCompletionNo(acceptNo);
                String completionStatus = completionInfo.getCompletionStatus();
                //获取进件编号
                String inputPieceIdsStr = "";
                String[] idArr = completionInfo.getEntryId().split(",");
                for (String entryId : idArr) {
                    if("40".equals(checkState)){
                        CustomerEntry customerEntry = customerDao.get(entryId);
                        customerEntry.setIsCheckAccept("2");
                        customerDao.save(customerEntry);
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ACCEPT_SUCESS, "竣工进件通过", null);
                    }else if("-11".equals(checkState)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ACCEPT_INCOMING_FAIL, "竣工提交失败", null);
                    }else if("10".equals(checkState)  && !"10".equals(completionStatus)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ACCEPT_INCOMING_ING, "竣工提交中", null);
                    }else if("20".equals(checkState)  && !"20".equals(completionStatus)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ACCEPT_INCOMING_CHECKING, "竣工验收中", null);
                    }else if("30".equals(checkState)  && !"30".equals(completionStatus)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ACCEPT_INCOMING_WAITCHECK, "竣工待审核", null);
                    }
                    CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entryId);
                    inputPieceIdsStr += application.getInputPieceId() + ",";
                }
                inputPieceIdsStr = inputPieceIdsStr.substring(0, inputPieceIdsStr.length() - 1);
                //状态值判断
                completionInfo.setCompletionStatus(checkState);
                //保存竣工信息
                completionDao.save(completionInfo);
                if (checkState != "40" || checkState != "-11") {
                    JSONArray jsonArray = arrayAccept.getJSONArray("reformedInfos");
                    logger.info("reformedInfos=======："+jsonArray);
                    if (jsonArray != null) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject arrayObject = jsonArray.getJSONObject(i);
                            String reformedInNo = arrayObject.getString("reformedNo");//整改单号
                            //String checkState = arrayObject.getString("checkState");
                            Map<String, Object> mapRe = new HashMap<>();
                            mapRe.put("reformedNoList", reformedInNo);
                            //调用整改查询接口
                            JSONArray jsonReformedArray = guangfaOperatingService.queryReformedList(mapRe);
                            logger.info("整改查询接口返回："+jsonReformedArray);
                            if(jsonReformedArray != null){
                                for(int s = 0; s < jsonReformedArray.size(); s++){
                                    JSONObject jsonReformed = jsonReformedArray.getJSONObject(s);
                                    String reformedDes = jsonReformed.getString("reformedDes");//整改整体描述
                                    String reformedCheckState = jsonReformed.getString("checkState");//整改状态
                                    JSONArray reformedArray = jsonReformed.getJSONArray("stationList");
                                    if (reformedArray != null) {
                                        for (int j = 0; j < reformedArray.size(); j++) {
                                            JSONObject arrayReformed = reformedArray.getJSONObject(j);
                                            String inputPieceId = arrayReformed.getString("inputPieceId");//进件编号
                                            CrmRectificationInfo rectificationInfo = new CrmRectificationInfo();
                                            rectificationInfo.setCompletionNo(acceptNo);
                                            rectificationInfo.setRectificationNo(reformedInNo);
                                            rectificationInfo.setInputPieceId(inputPieceIdsStr);
                                            rectificationInfo.setCreateTime(new Date());
                                            rectificationInfo.setRectificationStatus(reformedCheckState);
                                            //判断是否存在该整改单号
                                            CrmRectificationInfo rectification = rectificationDao.findRectificationByRectificationNo(reformedInNo);
                                            if (rectification == null) {
                                                //保存整改基本信息
                                                rectificationDao.save(rectificationInfo);
                                                JSONArray reformedItem = arrayReformed.getJSONArray("reformedItem");
                                                if (reformedItem != null) {
                                                    for (int t = 0; t < reformedItem.size(); t++) {
                                                        JSONObject arrayItem = reformedItem.getJSONObject(t);
                                                        String itemDes = arrayItem.getString("itemDes");//整改项描述
                                                        JSONArray reformedBeforePic = arrayItem.getJSONArray("reformedBeforePic");//整改前照片
                                                        String rectificationBeforeImg = StringUtils.join(reformedBeforePic, ","); // 数组转字符串
                                                        CrmRectificationInfoDetail detail = new CrmRectificationInfoDetail();
                                                        detail.setRectificationNo(reformedInNo);
                                                        detail.setInputPieceId(inputPieceId);
                                                        detail.setRectificationFeedback(reformedDes);
                                                        detail.setRectificationBeforeImg(rectificationBeforeImg);
                                                        detail.setRectificationTerm(itemDes);
                                                        //保存整改详情信息
                                                        rectificationInfoDetailDao.save(detail);
                                                    }
                                                }
                                                //过程信息
                                                for(String entryId : idArr){
                                                    if("-26".equals(reformedCheckState)){
                                                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_INCOMING_FAIL, "整改提交失败", null);
                                                    }else if("-31".equals(reformedCheckState)){
                                                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_CHECK_FAIL, "整改核实不通过", null);
                                                    }else if("10".equals(reformedCheckState)){
                                                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_INCOMING, "整改创建中", null);
                                                    }else if("20".equals(reformedCheckState)){
                                                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_ING, "整改中", null);
                                                    }else if("25".equals(reformedCheckState)){
                                                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_SUBMIT_ING, "整改提交中", null);
                                                    }else if("30".equals(reformedCheckState)){
                                                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_CHECKING, "核实中", null);
                                                    }else if("40".equals(reformedCheckState)){
                                                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_SUCESS, "整改完成", null);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    //整改状态查询
    @Transactional(rollbackFor = Exception.class)
    public void queryReformedList(String reformedNoList){
        Operator operator = Operator.of("1", "资方-广发", "资方");
        Map<String,Object> map = new HashMap<>();
        map.put("reformedNoList",reformedNoList);
        //调用整改查询接口
        JSONArray jsonReformedArray = guangfaOperatingService.queryReformedList(map);
        if(jsonReformedArray.size() > 0){
            for(int s = 0; s < jsonReformedArray.size(); s++){
                JSONObject jsonReformed = jsonReformedArray.getJSONObject(s);
                String reformedNo = jsonReformed.getString("reformedNo");//整改整体描述
                String reformedDes = jsonReformed.getString("reformedDes");//整改整体描述
                String reformedCheckState = jsonReformed.getString("checkState");//整改状态
                JSONArray reformedArray = jsonReformed.getJSONArray("stationList");
                //判断是否存在该整改单号
                CrmRectificationInfo rectification = rectificationDao.findRectificationByRectificationNo(reformedNo);
                if (reformedArray.size() > 0) {
                    for (int j = 0; j < reformedArray.size(); j++) {
                        JSONObject arrayReformed = reformedArray.getJSONObject(j);
                        String inputPieceId = arrayReformed.getString("inputPieceId");//进件编号
                        if("40".equals(reformedCheckState)){
                            rectification.setCompletionTime(new Date());//完成时间
                        }
                        rectification.setRectificationStatus(reformedCheckState);
                        //String updateTime = jsonReformed.getString("updateTime");//修改时间
                        rectification.setFianlUpdateTime(new Date());//最后修改时间
                        rectification.setRectificationStatus(reformedCheckState);
                        //保存整改基本信息
                        rectificationDao.save(rectification);
                        if (rectification != null && "-31".equals(reformedCheckState)) {// -31:核实不通过
                            Db.update("delete from crm_rectification_info_detail where rectification_no = "+"'"+reformedNo+"'");
                            JSONArray reformedItem = arrayReformed.getJSONArray("reformedItem");
                            if (reformedItem.size() > 0) {
                                for (int t = 0; t < reformedItem.size(); t++) {
                                    JSONObject arrayItem = reformedItem.getJSONObject(t);
                                    String itemDes = arrayItem.getString("itemDes");//整改项描述
                                    JSONArray reformedBeforePic = arrayItem.getJSONArray("reformedBeforePic");//整改前照片
                                    String rectificationBeforeImg = StringUtils.join(reformedBeforePic, ","); // 数组转字符串
                                    CrmRectificationInfoDetail detail = new CrmRectificationInfoDetail();
                                    detail.setRectificationNo(reformedNo);
                                    detail.setInputPieceId(inputPieceId);
                                    detail.setRectificationFeedback(reformedDes);
                                    detail.setRectificationBeforeImg(rectificationBeforeImg);
                                    detail.setRectificationTerm(itemDes);
                                    //保存整改详情信息
                                    rectificationInfoDetailDao.save(detail);
                                }
                            }
                        }
                    }
                }
                CrmCompletionInfo crmCompletionInfo = completionDao.findCompletionByCompletionNo(rectification.getCompletionNo());
                String[] idArr = crmCompletionInfo.getEntryId().split(",");
                //过程信息
                for(String entryId : idArr){
                    if("-26".equals(reformedCheckState)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_INCOMING_FAIL, "整改提交失败", null);
                    }else if("-31".equals(reformedCheckState)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_CHECK_FAIL, "整改核实不通过", null);
                    }else if("10".equals(reformedCheckState)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_INCOMING, "整改创建中", null);
                    }else if("20".equals(reformedCheckState)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_ING, "整改中", null);
                    }else if("25".equals(reformedCheckState)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_SUBMIT_ING, "整改提交中", null);
                    }else if("30".equals(reformedCheckState)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_CHECKING, "核实中", null);
                    }else if("40".equals(reformedCheckState)){
                        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.REFORMED_SUCESS, "整改完成", null);
                    }
                }
            }
        }
    }

}