package com.sunxung.factoring.web.signconfirmation;


import com.sunxung.factoring.component.annotation.OperationLog;
import com.sunxung.factoring.component.enums.OperationTypeEnum;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.ConstantUtil;
import com.sunxung.factoring.component.util.ElectronicSignatureUtil;
import com.sunxung.factoring.component.util.ThreadLocalUtil;
import com.sunxung.factoring.entity.ResponseJson;
import com.sunxung.factoring.entity.acceptance.AcceptanceSignConfirmationElectronicInfo;
import com.sunxung.factoring.entity.signconfirmation.SignConfirmation;
import com.sunxung.factoring.entity.signconfirmation.SignConfirmationApproval;
import com.sunxung.factoring.entity.signconfirmation.SignConfirmationElectronicInfo;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.service.acceptancesheet.IAcceptanceSignConfirmationElectronicInfoService;
import com.sunxung.factoring.service.signconfirmation.ISignConfirmationAddFlowService;
import com.sunxung.factoring.service.signconfirmation.ISignConfirmationElectronicInfoService;
import com.sunxung.factoring.service.signconfirmation.ISignConfirmationService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * --销售合同审核人员信息历史表 前端控制器
 * </p>
 *
 * @author liutao
 * @since 2023-05-16
 */
@Controller
@RequestMapping("/sign/confirmation")
public class SignConfirmationController {

    @Autowired
    private ISignConfirmationService signConfirmationService;

    @Autowired
    private ISignConfirmationAddFlowService signConfirmationAddFlowService;

    @Autowired
    private ISignConfirmationElectronicInfoService signConfirmationElectronicInfoService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private IAcceptanceSignConfirmationElectronicInfoService acceptanceSignConfirmationElectronicInfoService;

    /**
     * 跳转待我处理页面、
     *
     * @return
     */
    @RequestMapping("pendingList")
    public String pendingList() {
        return ConstantUtil.SIGN_CONFIRM_PREFIX + "pendingList";
    }

    /**
     * 跳转我已处理页面
     *
     * @return
     */
    @RequestMapping("findMyCompletedList")
    public String findMyCompletedList() {
        return ConstantUtil.SIGN_CONFIRM_PREFIX + "processedList";
    }

    /**
     * 跳转全部页面
     *
     * @return
     */
    @RequestMapping("allList")
    public String allList(Model model) {
        model.addAttribute("status", dictionaryService.findByParentCode("projectInitiationStatus"));
        return ConstantUtil.SIGN_CONFIRM_PREFIX + "allList";
    }

    /**
     * 跳转到查看页面
     *
     * @return
     */
    @RequestMapping("basicView")
    public String basicView() {
        return ConstantUtil.SIGN_CONFIRM_PREFIX + "basicView";
    }

    /**
     * 跳转到历史页面
     * 2.0
     *
     * @return
     */
    @RequestMapping("history")
    public String history() {
        return ConstantUtil.SIGN_CONFIRM_PREFIX + "history";
    }

    /**
     * 跳转签署确认页面
     *
     * @return
     */
    @RequestMapping("add")
    public String addPage(Long businessKey, Model model, String taskId) {
        SignConfirmation signConfirmation = signConfirmationAddFlowService.getView(businessKey);
        model.addAttribute("signConfirmation", signConfirmation);
        model.addAttribute("taskId", taskId);
        model.addAttribute("businessKey", businessKey);
        return ConstantUtil.SIGN_CONFIRM_PREFIX + "signConfirmation";
    }

    /**
     * 签署确认
     *
     * @param signConfirmation
     * @return
     */
    @ResponseBody
    @RequestMapping("confirm")
    @OperationLog(operationModule = "签署确认",operationType = OperationTypeEnum.INSERT,description = "签署确认")
    public ResponseJson confirm(SignConfirmation signConfirmation) {
        signConfirmationService.confirm(signConfirmation);
        return new ResponseJson("提交成功！");
    }

    /**
     * 跳转法务审核页面
     *
     * @return
     */
    @RequestMapping("approval")
    public String approval(String taskId, Long businessKey, Model model) {
        model.addAttribute("taskId", taskId);
        model.addAttribute("businessKey", businessKey);
        List<SignConfirmationElectronicInfo> signConfirmationElectronicInfos = signConfirmationElectronicInfoService.lambdaQuery()
                .eq(SignConfirmationElectronicInfo::getSignConfirmationId, businessKey).list();
        List<FileStorage> fileStorages = signConfirmationElectronicInfos.stream().map(r -> {
            FileStorage old = fileStorageService.get(r.getFileId());
            FileStorage fileStorage = fileStorageService.get(r.getBackFileId());
            fileStorage.setOriginalName(old.getOriginalName());
            return fileStorage;
        }).collect(Collectors.toList());
        model.addAttribute("files", fileStorages);
        return ConstantUtil.SIGN_CONFIRM_PREFIX + "check";
    }

    /**
     * 法务审核
     *
     * @param signConfirmationApproval
     * @return
     */
    @ResponseBody
    @RequestMapping("check")
    @OperationLog(operationModule = "签署确认",operationType = OperationTypeEnum.INSERT,description = "法务审核")
    public ResponseJson check(SignConfirmationApproval signConfirmationApproval) {
        flowableService.claimTask(signConfirmationApproval.getTaskId(), ThreadLocalUtil.getUserId(), ConstantUtil.LEGAL_SPECIALIST);
        signConfirmationService.approval(signConfirmationApproval);
        return new ResponseJson("提交成功！");
    }

    /**
     * 获取文件签署状态
     *
     * @param
     * @return
     */
    @GetMapping("/signType")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Object getSignType(String customerId, String contractId, String transactionId) throws ValidatorException {
        boolean result = false;
        SignConfirmationElectronicInfo signConfirmationElectronicInfo = signConfirmationElectronicInfoService.lambdaQuery().eq(SignConfirmationElectronicInfo::getContractId, contractId).eq(SignConfirmationElectronicInfo::getTransactionId, transactionId).one();
        AcceptanceSignConfirmationElectronicInfo acceptanceSignConfirmationElectronicInfo = acceptanceSignConfirmationElectronicInfoService.lambdaQuery().eq(AcceptanceSignConfirmationElectronicInfo::getContractId, contractId).eq(AcceptanceSignConfirmationElectronicInfo::getTransactionId, transactionId).one();
        String signResult = ElectronicSignatureUtil.getSignInfo(customerId, contractId, transactionId);
        if (signResult.equals("3000")) {
            result = true;
            if (signConfirmationElectronicInfo != null) {
                signConfirmationElectronicInfo.setSignStatus(1);
                //签署确认回调
                signConfirmationElectronicInfoService.doSignCallBack(signConfirmationElectronicInfo);
                signConfirmationElectronicInfoService.updateById(signConfirmationElectronicInfo);
            } else if (acceptanceSignConfirmationElectronicInfo != null) {
               // acceptanceSignConfirmationElectronicInfo.setSignStatus(1);
                //签署确认回调
                acceptanceSignConfirmationElectronicInfoService.doSignCallBack(acceptanceSignConfirmationElectronicInfo);
               // acceptanceSignConfirmationElectronicInfoService.updateById(acceptanceSignConfirmationElectronicInfo);
            }else {
                throw new ValidatorException(CodeUtil.FAIL, "无法获取合同信息！");
            }
        }
        return new ResponseJson(result);
    }

    /**
     * 资料下载
     *
     * @param response
     * @param id
     */
    @GetMapping("/downloadFileZip")
    @ResponseBody
    @OperationLog(operationModule = "签署确认",operationType = OperationTypeEnum.OTHER,description = "资料下载")
    public ResponseJson downloadFileZip(HttpServletResponse response, Long id) {
        signConfirmationService.downloadAllFile(response, id);
        return new ResponseJson("下载成功！");
    }

    /**
     * 出证下载
     *
     * @param response
     * @param id
     */
    @GetMapping("/downloadReportFileZip")
    @ResponseBody
    @OperationLog(operationModule = "签署确认",operationType = OperationTypeEnum.OTHER,description = "出证下载")
    public ResponseJson downloadReportFileZip(HttpServletResponse response, Long id) {
        signConfirmationService.downloadReportFileZip(response, id);
        return new ResponseJson("下载成功！");
    }
}
