package com.inkasso.factoring.purchManagement.web;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.auth.exception.ValidatorException;
import com.inkasso.factoring.common.entity.ResponseJson;
import com.inkasso.factoring.common.util.ElectronicSignatureUtil;
import com.inkasso.factoring.creditmanagement.entity.Enterprise;
import com.inkasso.factoring.creditmanagement.service.IEnterpriseService;
import com.inkasso.factoring.electronicSignature.entity.ElectronicSignaturePersonal;
import com.inkasso.factoring.electronicSignature.service.IElectronicSignaturePersonalService;
import com.inkasso.factoring.purchManagement.entity.CPurchContractElectronicInfo;
import com.inkasso.factoring.purchManagement.entity.CPurchContractSignConclusion;
import com.inkasso.factoring.purchManagement.service.ICPurchContractElectronicInfoService;
import com.inkasso.factoring.purchManagement.service.ICPurchContractManagementService;
import com.inkasso.factoring.purchManagement.service.ICPurchContractSignConclusionService;
import com.inkasso.factoring.purchManagement.service.ICPurchContractSupplementElectronicInfoService;
import com.inkasso.factoring.tradingPlatform.entity.Platform;
import com.inkasso.factoring.tradingPlatform.service.ITradingPlatformService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * <p>
 * 采购合同 合同的签署结论 前端控制器
 * </p>
 *
 * @author yafan
 * @since 2023-12-13
 */
@RestController
@RequestMapping("/purchContract/confirm")
public class PurchContractSignController {

    private static Logger logger = LogManager.getLogger(PurchContractSignController.class);

    @Autowired
    private ICPurchContractSignConclusionService purchContractSignConclusionService;
    @Autowired
    private ICPurchContractElectronicInfoService purchContractElectronicInfoService;
    @Autowired
    private ITradingPlatformService platformService;
    @Autowired
    private IEnterpriseService customerService;
    @Autowired
    private IElectronicSignaturePersonalService electronicSignaturePersonalService;
    @Autowired
    private ICPurchContractSupplementElectronicInfoService supplementElectronicInfoService;
    @Autowired
    private ICPurchContractManagementService purchContractService;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${trade.purchContractChangeSignBackUrl}")
    private String purchContractChangeSignBackUrl;

    /**
     * 跳转签署页面
     *
     * @param id 采购合同Id
     * @return
     */
    @RequestMapping("/add")
    public ResponseJson add(Long id) {
        return new ResponseJson(purchContractSignConclusionService.signPage(id));
    }

    /**
     * 删除电子合同信息  以生成新的合同链接
     *
     * @param businessKey
     * @return
     */
    @RequestMapping("/flush/url")
    public ResponseJson flushUrl(Long businessKey) {
        //签署后流程
        purchContractElectronicInfoService.flushUrl(businessKey);
        return new ResponseJson("链接刷新成功！");
    }


    /**
     * 签署确认
     *
     * @return
     */
    @RequestMapping("/sign")
    public ResponseJson doAdd(@RequestBody CPurchContractSignConclusion purchContractSignConclusion) {
        //签署后流程
        purchContractSignConclusionService.sign(purchContractSignConclusion);
        return new ResponseJson("签署确认完成");
    }


    /**
     * 认证回调
     *
     * @param customerId
     * @return
     */
    @PostMapping("/doAuth")
    @CrossOrigin
    public synchronized void doAuthBack(String customerId) {
        Platform platform = platformService.lambdaQuery().eq(Platform::getFddCustomerId,customerId).one();
        Enterprise customer = customerService.lambdaQuery().eq(Enterprise::getFddCustomerId,customerId).one();
        ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.lambdaQuery().eq(ElectronicSignaturePersonal::getFddCustomerId, customerId).one();
        if (platform != null) {
            platform.setAuthStatus(1);
            platformService.updateById(platform);
        } else if (customer != null) {
            customer.setAuthStatus(true);
            customerService.updateById(customer);
            purchContractElectronicInfoService.lambdaUpdate()
                    .eq(CPurchContractElectronicInfo::getFddCustomerId, customer.getFddCustomerId())
                    .set(CPurchContractElectronicInfo::getCertifyStatus, 1)
                    .update();
        } else if (electronicSignaturePersonal != null) {
            String authDeatil = electronicSignaturePersonalService.getAuthDeatil(customerId);
            JSONObject json = (JSONObject) JSONObject.parse(authDeatil);
            if (!"1".equals(json.getString("code"))) {
                throw new BusinessException(CodeUtil.FAIL, "法大大获取实名信息出现异常：" + json.getString("msg"));
            } else {
                String status = json.getJSONObject("data").getJSONObject("person").getString("status");
                if ("2".equals(status)) {
                    String idCard = json.getJSONObject("data").getJSONObject("person").getString("idCard");
                    electronicSignaturePersonal.setSocialCreditCode(idCard);
                } else {
                    throw new BusinessException(CodeUtil.FAIL, "法大大获取实名信息出现异常：" + json.getString("msg"));
                }
            }
            electronicSignaturePersonal.setAuthStatus(1);
            electronicSignaturePersonalService.updateById(electronicSignaturePersonal);
        }
    }


    /**
     * 获取文件签署状态
     *
     * @param electronicInfoId
     * @return
     */
    @GetMapping("/signType")
    @Transactional(rollbackFor = Exception.class)
    public ResponseJson getSignType(String electronicInfoId, Integer contractType) throws ValidatorException {

        return restTemplate.getForObject(purchContractChangeSignBackUrl + "?electronicInfoId="
                + electronicInfoId + "&contractType=" + contractType, ResponseJson.class);
    }


    /**
     * 刷新认证状态
     *
     * @param customerId
     * @return
     */
    @GetMapping("/getAuthStatus")
    public Object getAuthStatus(String customerId) {
        if (StringUtil.isEmpty(customerId)) {
            throw new ValidatorException(CodeUtil.FAIL, "参数不能为空!");
        }

        Enterprise customer = customerService.getOne(new QueryWrapper<Enterprise>().eq("fdd_customer_id", customerId));
        ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.lambdaQuery().eq(ElectronicSignaturePersonal::getFddCustomerId, customerId).one();
        if (customer != null) {
            String result = ElectronicSignatureUtil.getAuthInfo(customer.getSocialCreditCode(), "2");
            if ("1".equals(result)) {
                customer.setAuthStatus(true);
                customerService.updateById(customer);
                purchContractElectronicInfoService.lambdaUpdate()
                        .eq(CPurchContractElectronicInfo::getFddCustomerId, customer.getFddCustomerId())
                        .set(CPurchContractElectronicInfo::getCertifyStatus, true)
                        .update();
            }
            return new ResponseJson(customer);
        }
        if (electronicSignaturePersonal != null) {
            String authDeatil = electronicSignaturePersonalService.getAuthDeatil(customerId);
            JSONObject json = (JSONObject) JSONObject.parse(authDeatil);
            if (!"1".equals(json.getString("code"))) {
                throw new BusinessException(CodeUtil.FAIL, "法大大获取实名信息出现异常：" + json.getString("msg"));
            } else {
                String status = json.getJSONObject("data").getJSONObject("person").getString("status");
                if ("2".equals(status)) {
                    String idCard = json.getJSONObject("data").getJSONObject("person").getString("idCard");
                    electronicSignaturePersonal.setSocialCreditCode(idCard);
                } else {
                    throw new BusinessException(CodeUtil.FAIL, "法大大获取实名信息出现异常：" + json.getString("msg"));
                }
            }
            electronicSignaturePersonal.setAuthStatus(1);
            electronicSignaturePersonalService.updateById(electronicSignaturePersonal);
            return new ResponseJson(electronicSignaturePersonal);
        }

        throw new ValidatorException(CodeUtil.FAIL, "刷新认证状态出错！");
    }


}
