package com.sunxung.factoring.web.settlement;

import com.alibaba.fastjson.JSONObject;
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.ConstantUtil;
import com.sunxung.factoring.component.util.ThreadLocalUtil;
import com.sunxung.factoring.component.util.ValidatorUtil;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.ResponseJson;
import com.sunxung.factoring.entity.ValidatorEntity;
import com.sunxung.factoring.entity.customerinformation.Customer;
import com.sunxung.factoring.entity.settlement.SettlementApproval;
import com.sunxung.factoring.entity.settlement.SettlementBasicInfo;
import com.sunxung.factoring.entity.settlement.SettlementElectronicInfo;
import com.sunxung.factoring.entity.settlement.SettlementGoodsInfo;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.sys.FileStorageDO;
import com.sunxung.factoring.entity.vo.ConditionVo;
import com.sunxung.factoring.service.customerinformation.CustomerService;
import com.sunxung.factoring.service.settlement.SettlementBasicInfoService;
import com.sunxung.factoring.service.settlement.SettlementManagementService;
import com.sunxung.factoring.service.sys.FileService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 结算单Controller
 *
 * @author liutao
 * @date 2021.09.22
 */
@Controller
@RequestMapping("bill")
public class SettlementController {

    @Autowired
    private SettlementManagementService settlementManagementService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private SettlementBasicInfoService settlementBasicInfoService;

    @Autowired
    private FileService fileService;

    /**
     * 初始化参数数组长度最大值
     * @param binder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setAutoGrowNestedPaths(true);
        binder.setAutoGrowCollectionLimit(1024);
    }


    /**
     * 跳转添加页面
     * 2.0
     *
     * @return
     */
    @RequestMapping("addPage")
    public String addPage(Model model) {
        List<Customer> suppliers = customerService.getLocalUserSuppliers();
        model.addAttribute("suppliers", suppliers);
        return ConstantUtil.SETTLE_MANAGEMENT + "entry";
    }

    /**
     * 跳转待我处理页面
     * 2.0
     *
     * @return
     */
    @RequestMapping("pendingList")
    public String pendingList(Long businessBasicId, Model model) {
        model.addAttribute("businessBasicId", businessBasicId);
        return ConstantUtil.SETTLE_MANAGEMENT + "pendingList";
    }

    /**
     * 跳转我已处理页面
     * 2.0
     *
     * @return
     */
    @RequestMapping("findMyCompletedList")
    public String findMyCompletedList(Long businessBasicId, Model model) {
        model.addAttribute("businessBasicId", businessBasicId);
        return ConstantUtil.SETTLE_MANAGEMENT + "processedList";
    }

    /**
     * 跳转财务审核页面
     * 2.0
     *
     * @return
     */
    @RequestMapping("approval")
    @ResponseBody
    public Object approval(String taskId, Long businessKey, Model model) {
        List<FileStorageDO> files = fileService.findByBusinessId(businessKey,FileModuleDict.ChildEnum.SETTLEMENT_UPSTREAM_UNSIGNED_FILE.getCode());
//        model.addAttribute("file", files);
//        model.addAttribute("taskId", taskId);
//        model.addAttribute("businessKey", businessKey);
//        model.addAttribute("billBasicInformationId", businessKey);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("file", files);
        jsonObject.put("taskId", taskId);
        jsonObject.put("businessKey", businessKey);
        jsonObject.put("billBasicInformationId", businessKey);
        return new ResponseJson(jsonObject);
    }

    /**
     * 跳转全部页面
     * 2.0
     *
     * @return
     */
    @RequestMapping("allList")
    public String allList(Long businessBasicId, Model model) {
        model.addAttribute("businessBasicId", businessBasicId);
        return ConstantUtil.SETTLE_MANAGEMENT + "allList";
    }

    /**
     * 法务退回业务修改
     * 2.0
     *
     * @param taskId
     * @param businessKey 结算单ID
     * @param model
     * @return
     */
    @RequestMapping("create")
    public String add(String taskId, Long businessKey, Model model) {
        SettlementBasicInfo settlementBasicInfo = settlementManagementService.getDetail(businessKey);
        List<Customer> suppliers = customerService.getLocalUserSuppliers();
        model.addAttribute("suppliers", suppliers);
        model.addAttribute("billBasicInformation", settlementBasicInfo);
        model.addAttribute("taskId", taskId);
        model.addAttribute("businessKey", businessKey);
        return ConstantUtil.SETTLE_MANAGEMENT + "update";
    }

    /**
     * 获取结算货物集合
     *
     * @param businessKey
     * @return
     */
    @GetMapping("getGoodsInfoList")
    @ResponseBody
    public ResponseJson getGoodsInfoList(Long businessKey) {
        List<SettlementGoodsInfo> goodsInfoList = settlementManagementService.getGoodsInfoList(businessKey);
        return new ResponseJson(goodsInfoList);
    }

    /**
     * 跳转签署页面
     *
     * @param taskId
     * @param businessKey
     * @param model
     * @return
     */
    @RequestMapping("sign")
    public String signPage(String taskId, Long businessKey, Model model) {
        SettlementElectronicInfo settlementElectronicInfo = settlementManagementService.autoSign(businessKey, taskId);
        model.addAttribute("settlementElectronicInfo", settlementElectronicInfo);
        model.addAttribute("taskId", taskId);
        model.addAttribute("businessKey", businessKey);
        return ConstantUtil.SETTLE_MANAGEMENT + "contractSign";
    }

    /**
     * 获取文件签署状态
     *
     * @param electronicInfoId
     * @return
     */
    @PostMapping("/signType")
    @ResponseBody
    public ResponseJson getSignType(String electronicInfoId, String taskId, String basicId) throws ValidatorException {
        return new ResponseJson(settlementManagementService.getSignTppe(electronicInfoId, taskId, basicId));
    }

    /**
     * 结算单签署
     *
     * @return
     */
    @PostMapping("/finalStatementsign")
    @ResponseBody
    public ResponseJson billSign(@RequestBody JSONObject jsonObject) {
        String electronicInfoId = jsonObject.getString("electronicInfoId");
        String taskId = jsonObject.getString("taskId");
        return new ResponseJson(settlementManagementService.billSign(electronicInfoId, taskId));
    }

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

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

    /**
     * 新建结算单
     * 2.0
     *
     * @param settlementBasicInfo
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("addBillBasicInformation")
    @OperationLog(operationModule = "结算单",operationType = OperationTypeEnum.INSERT,description = "新建结算单")
    public ResponseJson add(@RequestBody SettlementBasicInfo settlementBasicInfo, HttpServletRequest request) throws Exception {
        settlementManagementService.add(settlementBasicInfo, request);
        return new ResponseJson("添加成功");
    }

    /**
     * 财务验收新建结算单
     *
     * @param settlementApproval
     * @return
     */
    @ResponseBody
    @RequestMapping("financeReview")
    @OperationLog(operationModule = "结算单",operationType = OperationTypeEnum.INSERT,description = "财务验收新建结算单")
    public ResponseJson financeReview(SettlementApproval settlementApproval) {
        ValidatorUtil.validator(ValidatorEntity.ValidatorType.ADD, settlementApproval);
        flowableService.claimTask(settlementApproval.getTaskId(), ThreadLocalUtil.getUserId(), ConstantUtil.LEGAL_SPECIALIST);
        settlementManagementService.financeReview(settlementApproval);
        return new ResponseJson("审核完成");
    }

    /**
     * 修改结算
     *
     * @param settlementBasicInfo
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("updateBill")
    @OperationLog(operationModule = "结算单",operationType = OperationTypeEnum.INSERT,description = "修改结算")
    public ResponseJson updateBill(SettlementBasicInfo settlementBasicInfo, HttpServletRequest request) throws IOException {
        settlementManagementService.updateBill(settlementBasicInfo, request);
        return new ResponseJson("修改成功");
    }

    /**
     * C端调用修改结算
     *
     * @param settlementBasicInfo
     * @return
     */
    @ResponseBody
    @RequestMapping("c_updateBill")
    @OperationLog(operationModule = "结算单",operationType = OperationTypeEnum.INSERT,description = "修改结算")
    public ResponseJson c_updateBill( @RequestBody SettlementBasicInfo settlementBasicInfo) throws IOException {
        settlementManagementService.c_updateBill(settlementBasicInfo);
        return new ResponseJson("修改成功");
    }

    /**
     * 获取业务相关验收单未结算的货物
     * 2.0
     *
     * @param conditionVo
     * @return
     */
//    @ResponseBody
//    @RequestMapping("getAcceptanceGoods")
//    public GridPage getAcceptanceGoods(@RequestBody ConditionVo conditionVo) {
//        return settlementManagementService.getCanBeBillGoodsInformation(conditionVo);
//    }

    /**
     * 一键计算质保金
     * 2.0
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("calculation")
    public ResponseJson calculation(@RequestBody  SettlementBasicInfo settlementBasicInfo) {
        return settlementManagementService.calculation(settlementBasicInfo);
    }

    /**
     * 生成PDF保存并预览(未签署)
     * 2.0
     *
     * @param settlementBasicInfo
     * @param response
     * @return
     */
    @RequestMapping("downloadPdf")
    @ResponseBody
    @OperationLog(operationModule = "结算单",operationType = OperationTypeEnum.OTHER,description = "生成PDF保存并预览(未签署)")
    public ResponseJson downloadPdf(@RequestBody SettlementBasicInfo settlementBasicInfo, HttpServletResponse response) {
        return new ResponseJson(settlementManagementService.downloadPdf(settlementBasicInfo, response));
    }

    /**
     * 下载（已签署）
     * 2.0
     *
     * @return
     */
    @RequestMapping("downloadPdfSign")
    @OperationLog(operationModule = "结算单",operationType = OperationTypeEnum.OTHER,description = "下载（已签署）")
    public void downloadPdfSign(Long settlementBasicInfoId, HttpServletResponse res) {
        settlementManagementService.downloadPdfSign(settlementBasicInfoId, res);
    }

    /**
     * 下载结算单出证
     * 2.0
     *
     * @return
     */
    @RequestMapping("download/report")
    @ResponseBody
    @OperationLog(operationModule = "结算单",operationType = OperationTypeEnum.OTHER,description = "下载结算单出证")
    public void downloadReport(Long id, HttpServletResponse res) {
         settlementManagementService.downloadReport(id, res);
    }

    /**
     * 计算对账日期
     * 2.0
     *
     * @param settlementBasicInfo
     * @return
     */
    @ResponseBody
    @RequestMapping("getExpectedSettlementDate")
    public ResponseJson getExpectedSettlementDate(@RequestBody  SettlementBasicInfo settlementBasicInfo) {
        return new ResponseJson(settlementManagementService.getExpectedSettlementDate(settlementBasicInfo));
    }

    /**
     * 一键下载
     *
     * @param id
     * @param response
     */
    @RequestMapping("downloadAllSettlementFile")
    @OperationLog(operationModule = "结算单",operationType = OperationTypeEnum.OTHER,description = "一键下载")
    public void downloadAllSettlementFile(Long id, HttpServletResponse response) {
        settlementBasicInfoService.downloadAllSettlementFile(id, response);
    }
    /**
     * 结算单单价调整提交
     *
     */
    @RequestMapping("unitPriceAdjust")
    @ResponseBody
    @OperationLog(operationModule = "单价修改",operationType = OperationTypeEnum.OTHER,description = "单价变更")
    public ResponseJson billUnitPriceAdjust(@RequestBody SettlementBasicInfo settlementBasicInfo) throws IOException {
        settlementManagementService.billUnitPriceAdjust(settlementBasicInfo);
        return new ResponseJson("修改成功");
    }

}
