package com.inkasso.factoring.salesManagement.web;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.response.SuccessResponseData;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.util.CollectionUtil;
import com.inkasso.auth.exception.ValidatorException;
import com.inkasso.auth.response.ResponseJson;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptanceSignConfirmationElectronicInfo;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptanceSignConfirmationElectronicInfoService;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptanceSignConfirmationService;
import com.inkasso.factoring.common.entity.BusinessHistoricDetailVo;
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.salesManagement.entity.*;
import com.inkasso.factoring.salesManagement.entity.vo.SalesContractBasicVo;
import com.inkasso.factoring.salesManagement.entity.vo.SalesSignConfirmVo;
import com.inkasso.factoring.salesManagement.service.*;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 销售合同管理表 前端控制器
 * </p>
 *
 * @author yafan
 * @since 2023-11-28
 */
@RestController
@RequestMapping("/salesContractManagement")
public class CSalesContractManagementController {

    @Autowired
    private ICSalesContractBasicInfoService salesContractService;
    @Autowired
    private ICSalesContractPersonInfoService salesContractPersonInfoService;
    @Autowired
    private ICSalesContractManagementService salesContractManagementService;
    @Autowired
    private ICSalesSignConfirmationService salesSignConfirmationService;
    @Autowired
    private ICSalesContractSupplementInfoService salesContractSupplementInfoService;
    @Autowired
    private ICSalesContractSupplementBasicInfoService salesContractSupplementBasicInfoService;
    @Autowired
    private ICSalesSupplementSignConfirmationService salesSupplementSignConfirmationService;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private IElectronicSignaturePersonalService electronicSignaturePersonalService;
    @Autowired
    private ICSalesSignConfirmationElectronicInfoService signConfirmationElectronicInfoService;
    @Autowired
    private ICSalesSupplementSignConfirmationElectronicInfoService salesSupplementSignConfirmationElectronicInfoService;
    @Autowired
    private ICAcceptanceSignConfirmationElectronicInfoService  acceptanceSignConfirmationElectronicInfoService;

    @Autowired
    private RestTemplate restTemplate;
    @Value("${trade.salesContractChangeSignBackUrl}")
    private String salesContractChangeSignBackUrl;

    @Value("${trade.salesContractSignBackUrl}")
    private String salesContractSignBackUrl;

    @Value("${trade.acceptanceContractSignBackUrl}")
    private String acceptanceContractSignBackUrl;

    @Value("${sop.synchronizeInformation}")
    private String synchronizeInformation;

    @GetMapping("/list")
    public ResponseJson list(SearchSalesBasic searchSalesBasic) {
        return new ResponseJson(salesContractManagementService.list(searchSalesBasic));
    }

    /**
     * 获取可选择的项目
     *
     * @return
     */
    @GetMapping("/getCreditProject")
    public ResponseJson getCreditProject() {
        return new ResponseJson(salesContractManagementService.getCreditProject());
    }

    /**
     * 解析货物信息Excel接口
     *
     * @param file
     * @return
     */
    @PostMapping("/doImportGoodsInfo")
    public ResponseJson doImportGoodsInfo(@RequestParam("file") MultipartFile file) {
        return new ResponseJson(salesContractService.importGoodsInfo(file));
    }


    /**
     * 获取当前用户下，销售合同审核通过的项目，且没有做过采购合同的项目
     *
     * @return
     */
    @GetMapping("/getCompletedSales")
    public Object getCompletedSales() {
        return new ResponseJson(salesContractManagementService.getCompletedSales());
    }


    /**
     * 销售合同-结算经办人
     *
     * @return
     */
    @RequestMapping("/findSettlementAgentInfo")
    public Object findSettlementAgentInfo(@RequestParam("type") String type) {
        List<CSalesContractPersonInfo> cSalesContractPersonInfos = salesContractPersonInfoService.findSettlementAgentInfoByType(type);
        return new SuccessResponseData(cSalesContractPersonInfos);
    }

    /**
     * 销售合同创建信息
     *
     * @param id
     * @return
     */
    @GetMapping("/create")
    public ResponseJson create(Long id) {
        return new ResponseJson(salesContractManagementService.getView(id));
    }

    /**
     * 创建销售合同
     *
     * @param salesContractManagement
     * @return
     */
    @PostMapping("/doCreate")
    public ResponseJson doAdd(@RequestBody @Validated CSalesContractManagement salesContractManagement) {
        salesContractManagementService.doAdd(salesContractManagement);
        return new ResponseJson("操作成功！");
    }

    /**
     * 获取项目基础信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getProjectBasicInfo")
    public ResponseJson getProjectBasicInfo(Long id) {
        return new ResponseJson(salesContractManagementService.getView(id));
    }

    /**
     * 获取详情
     *
     * @param id
     * @return
     */
    @GetMapping("/getDetail")
    public ResponseJson getDetail(Long id) {
        CSalesContractBasicInfo detail = salesContractService.getDetail(id);
        return new ResponseJson(detail);
    }

    /**
     * 录入
     *
     * @param salesContractBasicInfo
     * @return
     */
    @PostMapping("/doEnter")
    public ResponseJson doEnter(@RequestBody @Validated CSalesContractBasicInfo salesContractBasicInfo) {
        salesContractService.doAdd(salesContractBasicInfo);
        return new ResponseJson("操作成功！");

    }

    /**
     * 签署确认信息
     *
     * @param id
     * @return
     */
    @GetMapping("/sign")
    public ResponseJson sign(Long id) {
        return new ResponseJson(salesSignConfirmationService.add(id));
    }


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

        Enterprise customer = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("fdd_customer_id", customerId));
        ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.lambdaQuery()
                .eq(ElectronicSignaturePersonal::getFddCustomerId, customerId).one();
        if (customer != null) {

            //先从sop更新信息
            ResponseJson forObject = restTemplate.getForObject(synchronizeInformation+"?socialCreditCode="+customer.getSocialCreditCode(), ResponseJson.class);
            Map<String,String> data = (Map) forObject.getData();
            customer.setAuthUrl(data.get("authUrl"));
            customer.setShortAuthUrl(data.get("shortAuthUrl"));
            customer.setCertificateSignUrl(data.get("certificateSignUrl"));
            customer.setCertificateShortSignUrl(data.get("certificateShortSignUrl"));
            customer.setFddCustomerId(data.get("fddCustomerId"));
            customer.setCertificateContractId(data.get("certificateContractId"));
            customer.setCertificateTransactionId(data.get("certificateTransactionId"));
            //更新自动签链接
            customer.setAutoSignUrl(data.get("autoSignUrl"));
            customer.setShortAutoSignUrl(data.get("shortAutoSignUrl"));
            enterpriseService.updateById(customer);

            String result = ElectronicSignatureUtil.getAuthInfo(customer.getSocialCreditCode(), "2");
            if ("1".equals(result)) {
                customer.setAuthStatus(true);
                enterpriseService.updateById(customer);
            }
            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, "刷新认证状态出错！");
    }

    /**
     * 获取文件签署状态
     *
     * @param
     * @return
     */
    @GetMapping("/signType")
    @Transactional(rollbackFor = Exception.class)
    public Object getSignType(String customerId, String contractId, String transactionId) throws ValidatorException {
        boolean result = false;

        List<CSalesSignConfirmationElectronicInfo> signConfirmationElectronicInfos = signConfirmationElectronicInfoService.lambdaQuery()
                .eq(CSalesSignConfirmationElectronicInfo::getContractId, contractId)
                .eq(CSalesSignConfirmationElectronicInfo::getTransactionId, transactionId).list();
        List<CSalesSupplementSignConfirmationElectronicInfo> supplementSignConfirmationElectronicInfos = salesSupplementSignConfirmationElectronicInfoService.lambdaQuery()
                .eq(CSalesSupplementSignConfirmationElectronicInfo::getContractId, contractId)
                .eq(CSalesSupplementSignConfirmationElectronicInfo::getTransactionId, transactionId).list();
        List<CAcceptanceSignConfirmationElectronicInfo> acceptanceSignConfirmationElectronicInfos = acceptanceSignConfirmationElectronicInfoService.lambdaQuery()
            .eq(CAcceptanceSignConfirmationElectronicInfo::getContractId, contractId).eq(CAcceptanceSignConfirmationElectronicInfo::getTransactionId, transactionId).list();
        Enterprise enterprise = enterpriseService.lambdaQuery().eq(Enterprise::getCertificateTransactionId, transactionId).eq(Enterprise::getCertificateContractId, contractId).one();
        String signResult = ElectronicSignatureUtil.getSignInfo(customerId, contractId, transactionId);
        if (signResult.equals("3000")) {
            result = true;
            //更新该批次的所有签署状态
            if (CollectionUtil.isNotEmpty(signConfirmationElectronicInfos)) {
                signConfirmationElectronicInfos.forEach(c -> {
                    c.setSignStatus(1);
                    //签署确认回调
                    restTemplate.postForObject(salesContractSignBackUrl, c, ResponseJson.class);
                    signConfirmationElectronicInfoService.updateById(c);
                });
            } else if (CollectionUtil.isNotEmpty(supplementSignConfirmationElectronicInfos)) {
                supplementSignConfirmationElectronicInfos.forEach(c -> {
                    c.setSignStatus(1);
                    //签署确认回调
                    restTemplate.postForObject(salesContractChangeSignBackUrl, c, ResponseJson.class);
                    salesSupplementSignConfirmationElectronicInfoService.updateById(c);
                });
            }else if(enterprise != null){
                enterprise.setCertificateSignStatus(1);
                enterpriseService.updateById(enterprise);
            } else if (CollectionUtil.isNotEmpty(acceptanceSignConfirmationElectronicInfos)) {
                acceptanceSignConfirmationElectronicInfos.forEach(c->{
                    restTemplate.postForObject(acceptanceContractSignBackUrl, c, ResponseJson.class);
                });
            }else {
                throw new ValidatorException(CodeUtil.FAIL, "无法获取合同信息！");
            }

        }
        return new ResponseJson(result);
    }

    /**
     * 签署确认提交
     *
     * @param salesSignConfirmation
     * @return
     */
    @PostMapping("/doSign")
    public ResponseJson doSign(@RequestBody CSalesSignConfirmation salesSignConfirmation) {
        salesSignConfirmationService.doAdd(salesSignConfirmation);
        return new ResponseJson("操作成功！");
    }

    /**
     * 下载销售合同货物信息模板
     *
     * @return
     */
    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletResponse response) {
        salesContractService.downloadTemplateFile(response);
    }

    /**
     * 查看
     */
    @GetMapping("/getView")
    public ResponseJson getView(Long id) {
        List<BusinessHistoricDetailVo> list = new ArrayList<>();

        //创建
        SalesContractBasicVo contractBasicVo = salesContractManagementService.getView(id);
        if (contractBasicVo != null) {
            BusinessHistoricDetailVo log1 = new BusinessHistoricDetailVo();
            log1.setFormBusinessName("销售合同创建");
            log1.setObj(contractBasicVo);
            list.add(log1);
        }

        //录入
        CSalesContractBasicInfo contractBasicInfo = salesContractService
                .lambdaQuery().eq(CSalesContractBasicInfo::getcSalesContractManagementId, id).one();
        if (contractBasicInfo!=null){
            CSalesContractBasicInfo salesContractBasicInfo = salesContractService.getDetail(id);
            if (salesContractBasicInfo != null) {
                BusinessHistoricDetailVo log2 = new BusinessHistoricDetailVo();
                log2.setFormBusinessName("销售合同录入");
                log2.setObj(salesContractBasicInfo);
                list.add(log2);
            }
        }

        //签署
        Object signConfirmation = salesSignConfirmationService.getView(id);
        if (signConfirmation != null) {
            BusinessHistoricDetailVo log3 = new BusinessHistoricDetailVo();
            log3.setFormBusinessName("签署确认");
            log3.setObj(signConfirmation);
            list.add(log3);
        }

        //变更创建
        List<CSalesContractSupplementInfo> supplementInfoList = salesContractSupplementInfoService
                .lambdaQuery().eq(CSalesContractSupplementInfo::getcSalesContractManagementId, id).list();
        if (CollectionUtil.isNotEmpty(supplementInfoList)) {

            supplementInfoList.forEach(supplement->{
                CSalesContractSupplementInfo supplementInfo = salesContractSupplementInfoService.getView(supplement.getId());
                if (supplementInfo != null) {
                    BusinessHistoricDetailVo log4 = new BusinessHistoricDetailVo();
                    log4.setFormBusinessName("变更合同创建");
                    log4.setObj(supplementInfo);
                    list.add(log4);
                }

                //变更录入
                CSalesContractSupplementBasicInfo supplementBasicInfo = salesContractSupplementBasicInfoService.getView(supplement.getId());
                if (supplementBasicInfo != null) {
                    BusinessHistoricDetailVo log5 = new BusinessHistoricDetailVo();
                    log5.setFormBusinessName("变更信息录入");
                    log5.setObj(supplementBasicInfo);
                    list.add(log5);
                }

                //变更签署

                Object supplementSignConfirmation = salesSupplementSignConfirmationService.getView(supplement.getId());
                if (supplementSignConfirmation != null) {
                    BusinessHistoricDetailVo log6 = new BusinessHistoricDetailVo();
                    log6.setFormBusinessName("变更签署确认");
                    log6.setObj(supplementSignConfirmation);
                    list.add(log6);
                }
            });


        }


        return new ResponseJson(list);
    }


}
