package easydo.technology.controller;

import easydo.technology.annotation.WebLog;
import easydo.technology.components.JdbcClient;
import easydo.technology.components.ZeroSpringFolderComponent;
import easydo.technology.enums.ChengfaEnum;
import easydo.technology.exception.BizException;
import easydo.technology.model.BusApprove;
import easydo.technology.model.Purchase;
import easydo.technology.model.PurchaseAnswerSign;
import easydo.technology.model.PurchaseBidNotice;
import easydo.technology.model.PurchaseBidSign;
import easydo.technology.model.PurchaseMatter;
import easydo.technology.model.vo.GLDApproveVo;
import easydo.technology.service.FlowNoService;
import easydo.technology.service.GLDApproveService;
import easydo.technology.utils.StringUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/purchaseApply")
public class PurchaseApplyController {
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;
    @Resource
    FlowNoService flownoService;
    @Resource
    GLDApproveService gldApproveService;

    @WebLog
    @RequestMapping(value = "/getPage")
    public Object getPage(@RequestBody Map<String, Object> map) throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();

            Map<String, Object> page = jdbcClient.getJdbcPage(map, Purchase.class, connection);
            // List<Purchase> list = (List<Purchase>) page.get("records");
            // for (Purchase model : list) {
            // ZeroSpringFolderComponent.build(dataSource).fetch(model);
            // }

            return new ResponseEntity<>(page, HttpStatus.OK);
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/getList")
    public Object getList(@RequestBody Map<String, Object> map) throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();

            List<Purchase> list = jdbcClient.getJdbcList(map, Purchase.class, connection);
            // for (Purchase model : list) {
            // ZeroSpringFolderComponent.build(dataSource).fetch(model);
            // }
            return new ResponseEntity<>(list, HttpStatus.OK);
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/save")
    public Object save(@RequestBody Purchase model) throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            model.setPurchaseNo(flownoService.getFlowNo(ChengfaEnum.FLOWNO_TYPE_PURCHASE.getValue(), connection));
            jdbcClient.jdbcInsert(model, connection);
            connection.commit();
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/saveApprove")
    public Object saveApprove(@RequestBody Purchase model) throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            if (StringUtil.isEmpty(model.getId())) {
                model.setPurchaseNo(flownoService.getFlowNo(ChengfaEnum.FLOWNO_TYPE_PURCHASE.getValue(), connection));
                jdbcClient.jdbcInsert(model, connection);
            } else {
                checkData(model, connection);
                jdbcClient.jdbcUpdateById(model, connection);
            }

            GLDApproveVo vo = new GLDApproveVo();
            vo.setTargetId(0);
            vo.setTargetType(ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE.getValue());
            vo.setTemplateId(model.getTemplateId());
            String taskId = gldApproveService.startApprove(vo);
            vo.setTaskId(taskId);
            vo = gldApproveService.getApproveInfo(vo);

            model.setProcessInstanceId(vo.getInstanceId());
            model.setProcessState(vo.getState());
            model.setProcessTaskId(vo.getTaskId());
            model.setProcessTemplateId(vo.getTemplateId());

            model.setStep(ChengfaEnum.PURCHASE_STEP_PURCHASE_APPLY.getValue());
            model.setStatus(ChengfaEnum.PURCHASE_STATUS_APPROVE.getValue());
            jdbcClient.jdbcUpdateById(model, connection);

            connection.commit();
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/update")
    public Object update(@RequestBody Purchase model) throws Exception {

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);
            checkData(model, connection);

            jdbcClient.jdbcUpdateById(model, connection);
            connection.commit();
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    public void checkData(Purchase model, Connection connection) throws Exception {
        Purchase purchase = new Purchase();
        purchase.setId(model.getId());
        purchase = jdbcClient.getJdbcModelById(purchase, connection);
        if (ChengfaEnum.PURCHASE_STEP_PURCHASE_APPLY.getValue().equals(purchase.getStep())) {
            throw new BizException("此采购申请已经发起采购申请审批，请勿操作");
        }

        BusApprove busApprove = new BusApprove();
        busApprove.setBusId(model.getId());
        busApprove.setBusType(ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE.getValue());
        busApprove.setApproveStatus(ChengfaEnum.BUS_APPROVE_APPROVE_STATUS_DONE.getValue());
        busApprove.setApproveResult(ChengfaEnum.BUS_APPROVE_APPROVE_RESULT_Y.getValue());
        int count = jdbcClient.getJdbcCount(busApprove, connection);
        if (count > 0) {
            throw new BizException("此采购申请已经发起采购申请审批，请勿重复操作");
        }
    }

    @WebLog
    @RequestMapping(value = "/getById")
    public Object getById(@RequestBody Purchase model) throws Exception {
        Map<String, Object> result = new HashMap<>();
        Connection connection = null;
        try {
            connection = dataSource.getConnection();

            model = jdbcClient.getJdbcModelById(model, connection);
            ZeroSpringFolderComponent.build(dataSource).fetch(model);

            PurchaseMatter matter = new PurchaseMatter();
            matter.setPurchaseId(model.getId());
            matter = jdbcClient.getJdbcModel(matter, connection);

            PurchaseBidSign bidSign = new PurchaseBidSign();
            bidSign.setPurchaseId(model.getId());
            bidSign = jdbcClient.getJdbcModel(bidSign, connection);
            if (StringUtil.isNotEmpty(bidSign.getId())) {
                ZeroSpringFolderComponent.build(dataSource).fetch(bidSign);
            }

            PurchaseAnswerSign answerSign = new PurchaseAnswerSign();
            answerSign.setPurchaseId(model.getId());
            answerSign = jdbcClient.getJdbcModel(answerSign, connection);

            PurchaseBidNotice bidNotice = new PurchaseBidNotice();
            bidNotice.setPurchaseId(model.getId());
            bidNotice = jdbcClient.getJdbcModel(bidNotice, connection);

            result.put("purchase", model);
            result.put("matter", matter);
            result.put("bidSign", bidSign);
            result.put("answerSign", answerSign);
            result.put("bidNotice", bidNotice);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/remove")
    public Object remove(@RequestBody Purchase model) throws Exception {

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            model = jdbcClient.getJdbcModelById(model, connection);
            if (StringUtil.isNotEmpty(model.getStatus())
                    || StringUtil.isNotEmpty(model.getStep())) {
                throw new BizException("此采购申请已经发起申请审批，请勿删除");
            }

            jdbcClient.jdbcRemoveById(model, connection);
            connection.commit();
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }
}
