package easydo.technology.controller;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import easydo.technology.annotation.WebLog;
import easydo.technology.components.JdbcClient;
import easydo.technology.enums.ChengfaEnum;
import easydo.technology.exception.BizException;
import easydo.technology.model.OaPurchaseInfo;
import easydo.technology.model.Purchase;
import easydo.technology.model.PurchaseAnswerSign;
import easydo.technology.model.PurchaseBidNotice;
import easydo.technology.model.PurchaseBidSign;
import easydo.technology.model.PurchaseContract;
import easydo.technology.model.PurchaseMatter;
import easydo.technology.model.PurchasePlan;
import easydo.technology.model.SysUser;
import easydo.technology.service.OAService;
import easydo.technology.utils.StringUtil;

@RestController
@RequestMapping("/purchase")
public class PurchaseController {

    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;
    @Value("${PURCHASE.redirectUrl}")
    String redirectUrl;
    @Resource
    OAService oaService;

    @WebLog
    @RequestMapping(value = "/getPage")
    public Object getPage(@RequestBody Map<String, Object> map)throws Exception {
        Connection connection = null;
        Map<String, Object> paramMap = new HashMap<>();
        try {
            connection = dataSource.getConnection();
            List<Purchase> filter = jdbcClient.getJdbcList(paramMap, Purchase.class, connection);
            List<String> purchaseIdList = filter.stream().map(Purchase::getId).collect(Collectors.toList());

            boolean isNeedIdFilter = false;
            if (map.containsKey("contractNo") && StringUtil.isNotEmpty(map.get("contractNo"))) {
                String contractNo = map.get("contractNo").toString();
                map.remove("contractNo");
                paramMap.put("contractNoLike", contractNo);
                isNeedIdFilter = true;
            }
            if (map.containsKey("contractName") && StringUtil.isNotEmpty(map.get("contractName"))) {
                String contractName = map.get("contractName").toString();
                map.remove("contractName");
                paramMap.put("contractNameLike", contractName);
                isNeedIdFilter = true;
            }
            if (map.containsKey("signAmountBegin") && StringUtil.isNotEmpty(map.get("signAmountBegin"))) {
                BigDecimal signAmountBegin = new BigDecimal(map.get("signAmountBegin").toString());
                map.remove("signAmountBegin");
                paramMap.put("signAmountBegin", signAmountBegin);
                isNeedIdFilter = true;
            }
            if (map.containsKey("signAmountEnd") && StringUtil.isNotEmpty(map.get("signAmountEnd"))) {
                BigDecimal signAmountEnd = new BigDecimal(map.get("signAmountEnd").toString());
                map.remove("signAmountEnd");
                paramMap.put("signAmountEnd", signAmountEnd);
                isNeedIdFilter = true;
            }
            if (map.containsKey("contractCreateTimeBegin")
                    && StringUtil.isNotEmpty(map.get("contractCreateTimeBegin"))) {
                String contractCreateTimeBegin = map.get("contractCreateTimeBegin").toString();
                map.remove("contractCreateTimeBegin");
                paramMap.put("createTimeBegin", contractCreateTimeBegin);
                isNeedIdFilter = true;
            }
            if (map.containsKey("contractCreateTimeEnd") && StringUtil.isNotEmpty(map.get("contractCreateTimeEnd"))) {
                String contractCreateTimeEnd = map.get("contractCreateTimeEnd").toString();
                map.remove("contractCreateTimeEnd");
                paramMap.put("createTimeEnd", contractCreateTimeEnd);
                isNeedIdFilter = true;
            }
            if (map.containsKey("contractEndTimeBegin") && StringUtil.isNotEmpty(map.get("contractEndTimeBegin"))) {
                String contractEndTimeBegin = map.get("contractEndTimeBegin").toString();
                map.remove("contractEndTimeBegin");
                paramMap.put("endTimeBegin", contractEndTimeBegin);
                isNeedIdFilter = true;
            }
            if (map.containsKey("contractEndTimeEnd") && StringUtil.isNotEmpty(map.get("contractEndTimeEnd"))) {
                String contractEndTimeEnd = map.get("contractEndTimeEnd").toString();
                map.remove("contractEndTimeEnd");
                paramMap.put("endTimeEnd", contractEndTimeEnd);
                isNeedIdFilter = true;
            }
            if (paramMap.size() > 0) {
                List<PurchaseContract> list = jdbcClient.getJdbcList(paramMap, PurchaseContract.class, connection);
                List<String> purchaseIds = list.stream().map(PurchaseContract::getPurchaseId)
                        .collect(Collectors.toList());
                purchaseIdList = purchaseIdList.stream()
                        .filter(purchaseIds::contains)
                        .collect(Collectors.toList());
            }

            paramMap.clear();
            if (map.containsKey("bidSignCreateTimeBegin") && StringUtil.isNotEmpty(map.get("bidSignCreateTimeBegin"))) {
                String bidSignCreateTimeBegin = map.get("bidSignCreateTimeBegin").toString();
                map.remove("bidSignCreateTimeBegin");
                paramMap.put("createTimeBegin", bidSignCreateTimeBegin);
                isNeedIdFilter = true;
            }
            if (map.containsKey("bidSignCreateTimeEnd") && StringUtil.isNotEmpty(map.get("bidSignCreateTimeEnd"))) {
                String bidSignCreateTimeEnd = map.get("bidSignCreateTimeEnd").toString();
                map.remove("bidSignCreateTimeEnd");
                paramMap.put("createTimeEnd", bidSignCreateTimeEnd);
                isNeedIdFilter = true;
            }
            if (map.containsKey("bidSignEndTimeBegin") && StringUtil.isNotEmpty(map.get("bidSignEndTimeBegin"))) {
                String bidSignEndTimeBegin = map.get("bidSignEndTimeBegin").toString();
                map.remove("bidSignEndTimeBegin");
                paramMap.put("endTimeBegin", bidSignEndTimeBegin);
                isNeedIdFilter = true;
            }
            if (map.containsKey("bidSignEndTimeEnd") && StringUtil.isNotEmpty(map.get("bidSignEndTimeEnd"))) {
                String bidSignEndTimeEnd = map.get("bidSignEndTimeEnd").toString();
                map.remove("bidSignEndTimeEnd");
                paramMap.put("endTimeEnd", bidSignEndTimeEnd);
                isNeedIdFilter = true;
            }
            if (paramMap.size() > 0) {
                List<PurchaseBidSign> list = jdbcClient.getJdbcList(paramMap, PurchaseBidSign.class, connection);
                List<String> purchaseIds = list.stream().map(PurchaseBidSign::getPurchaseId)
                        .collect(Collectors.toList());
                purchaseIdList = purchaseIdList.stream()
                        .filter(purchaseIds::contains)
                        .collect(Collectors.toList());
            }

            paramMap.clear();
            if (map.containsKey("bidNoticeEndTimeBegin") && StringUtil.isNotEmpty(map.get("bidNoticeEndTimeBegin"))) {
                String bidNoticeEndTimeBegin = map.get("bidNoticeEndTimeBegin").toString();
                map.remove("bidNoticeEndTimeBegin");
                paramMap.put("endTimeBegin", bidNoticeEndTimeBegin);
                isNeedIdFilter = true;
            }
            if (map.containsKey("bidNoticeEndTimeEnd") && StringUtil.isNotEmpty(map.get("bidNoticeEndTimeEnd"))) {
                String bidNoticeEndTimeEnd = map.get("bidNoticeEndTimeEnd").toString();
                map.remove("bidNoticeEndTimeEnd");
                paramMap.put("endTimeEnd", bidNoticeEndTimeEnd);
                isNeedIdFilter = true;
            }
            if (paramMap.size() > 0) {
                List<PurchaseBidNotice> list = jdbcClient.getJdbcList(paramMap, PurchaseBidNotice.class, connection);
                List<String> purchaseIds = list.stream().map(PurchaseBidNotice::getPurchaseId)
                        .collect(Collectors.toList());
                purchaseIdList = purchaseIdList.stream()
                        .filter(purchaseIds::contains)
                        .collect(Collectors.toList());
            }

            paramMap.clear();
            if (map.containsKey("matterCreateTimeBegin") && StringUtil.isNotEmpty(map.get("matterCreateTimeBegin"))) {
                String matterCreateTimeBegin = map.get("matterCreateTimeBegin").toString();
                map.remove("matterCreateTimeBegin");
                paramMap.put("createTimeBegin", matterCreateTimeBegin);
                isNeedIdFilter = true;
            }
            if (map.containsKey("matterCreateTimeEnd") && StringUtil.isNotEmpty(map.get("matterCreateTimeEnd"))) {
                String matterCreateTimeEnd = map.get("matterCreateTimeEnd").toString();
                map.remove("matterCreateTimeEnd");
                paramMap.put("createTimeEnd", matterCreateTimeEnd);
                isNeedIdFilter = true;
            }
            if (paramMap.size() > 0) {
                List<PurchaseMatter> list = jdbcClient.getJdbcList(paramMap, PurchaseMatter.class, connection);
                List<String> purchaseIds = list.stream().map(PurchaseMatter::getPurchaseId)
                        .collect(Collectors.toList());
                purchaseIdList = purchaseIdList.stream()
                        .filter(purchaseIds::contains)
                        .collect(Collectors.toList());
            }

            if (isNeedIdFilter) {
                if (!purchaseIdList.isEmpty()) {
                    map.put("idIn", purchaseIdList);
                } else {
                    purchaseIdList.add("0");
                    map.put("idIn", purchaseIdList);
                }
            }

            Map<String, Object> page = jdbcClient.getJdbcPage(map, Purchase.class, connection);
            List<Purchase> list = (List<Purchase>) page.get("records");
            for (Purchase model : list) {
                OaPurchaseInfo purchaseInfo = new OaPurchaseInfo();
                purchaseInfo.setId(model.getId());
                purchaseInfo = jdbcClient.getJdbcModelById(purchaseInfo, connection);

                PurchasePlan plan = new PurchasePlan();
                plan.setId(model.getPlanId());
                plan = jdbcClient.getJdbcModelById(plan, connection);

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

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

                PurchaseBidSign bidSign = new PurchaseBidSign();
                bidSign.setPurchaseId(model.getId());
                bidSign = jdbcClient.getJdbcModel(bidSign, connection);

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

                PurchaseContract contract = new PurchaseContract();
                contract.setPurchaseId(model.getId());
                List<PurchaseContract> contractList = jdbcClient.getJdbcList(contract, connection);

                model.setOaStatus(purchaseInfo.getStatus());
                model.setPlan(plan);
                model.setMatter(matter);
                model.setAnswerSign(answerSign);
                model.setBidSign(bidSign);
                model.setBidNotice(bidNotice);
                model.setContractList(contractList);
            }

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

    @WebLog
    @GetMapping("/getDetail")
    public ModelAndView getDetail(@RequestParam String type, @RequestParam(required = false) String businessId,
            @RequestParam(required = false) String taskId, @RequestParam String path,
            @RequestParam(required = false) String ticket, @RequestParam(required = false) String v5ticket)
            throws Exception {
        if (StringUtil.isEmpty(businessId) && StringUtil.isEmpty(taskId)) {
            throw new BizException("关键参数缺失");
        }
        if (StringUtil.isEmpty(businessId) && StringUtil.isNotEmpty(taskId)) {
            if (ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE_PLAN.getValue().equals(type)) {
                PurchasePlan plan = new PurchasePlan();
                plan.setProcessTaskId(taskId);
                plan = jdbcClient.getJdbcModel(plan);
                businessId = plan.getId();
            } else if (ChengfaEnum.BUS_APPROVE_TYPE_SUPPLIER_EVALUATE.getValue().equals(type)) {

            } else {
                // Purchase purchase = new Purchase();
                // purchase.setProcessTaskId(taskId);
                // purchase = jdbcClient.getJdbcModel(purchase);
                // businessId = purchase.getId();
            }
        }
        int userId = 1;
        if (StringUtil.isNotEmpty(ticket)) {
            String username = oaService.getUsername(ticket);
            if (StringUtil.isNotEmpty(username)) {
                String telnumber = oaService.getTelNumber(username);
                SysUser sysUser = new SysUser();
                sysUser.setPhone(telnumber);
                sysUser = jdbcClient.getJdbcModel(sysUser);
                if (StringUtil.isNotEmpty(sysUser.getUserId())) {
                    userId = sysUser.getUserId().intValue();
                } else {
                    userId = 0;
                }

            }
        } else if (StringUtil.isNotEmpty(v5ticket)) {
            String username = oaService.getUsername(v5ticket);
            if (StringUtil.isNotEmpty(username)) {
                String telnumber = oaService.getTelNumber(username);
                SysUser sysUser = new SysUser();
                sysUser.setPhone(telnumber);
                sysUser = jdbcClient.getJdbcModel(sysUser);
                if (StringUtil.isNotEmpty(sysUser.getUserId())) {
                    userId = sysUser.getUserId().intValue();
                } else {
                    userId = 0;
                }
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView
                .setViewName(
                        "redirect:" + redirectUrl + "?userId=" + userId + "&type=" + type + "&businessId=" + businessId
                                + "&path=" + path);
        return modelAndView;
    }

    @WebLog
    @RequestMapping(value = "/getBusinessId")
    public Object getBusinessId(@RequestBody Map<String, Object> map)throws Exception {
        String type = map.get("type").toString();
        String instanceId = map.get("instanceId").toString();
        Connection connection = null;
        String businessId = "";
        ResultSet resultSet = null;
        try {
            connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            if (type.equals(ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE_PLAN.getValue())
                    || type.equals(ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE.getValue())) {
                String sql = "select id from " + type + " where process_instance_id = '" + instanceId + "' limit 1";
                resultSet = statement.executeQuery(sql);

            } else {
                String sql = "select purchase_id from " + type + " where process_instance_id = '" + instanceId
                        + "' limit 1";
                resultSet = statement.executeQuery(sql);
            }
            while (resultSet.next()) {
                businessId = resultSet.getString(1);
            }

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

    @WebLog
    @RequestMapping(value = "/getTongji")
    public Object getTongji(@RequestBody Map<String, Object> map) throws Exception{
        Map<String, Object> result = new HashMap<>();
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            String sql = "select sum(sign_amount) as sign_amount from purchase_contract";

            Map<String, Object> paramMap = new HashMap<>();
            PurchaseContract contract = jdbcClient.getJdbcModelByMap(paramMap, sql, PurchaseContract.class, connection);
            result.put("contractAmount", contract.getSignAmount());

            sql = "select sum(budget_amount) as budget_amount from purchase";
            Purchase purchase = jdbcClient.getJdbcModelByMap(paramMap, sql, Purchase.class, connection);
            result.put("purchaseAmount", purchase.getBudgetAmount());

            sql = "select sum(bid_amount) as bid_amount,sum(control_amount) as control_amount from purchase_bid_notice";
            PurchaseBidNotice bidNotice = jdbcClient.getJdbcModelByMap(paramMap, sql, PurchaseBidNotice.class, connection);
            result.put("bidAmount", bidNotice.getBidAmount());
            result.put("controlAmount", bidNotice.getControlAmount());

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

    public static void main(String[] args) {
        String viewSql = "SELECT\n" +
                "`sir`.`id` AS `id`,\n" +
                "`sir`.`project_id` AS `project_id`,\n" +
                "`sir`.`type` AS `type`,\n" +
                "`sir`.`point_id` AS `point_id`,\n" +
                "`sir`.`level` AS `level`,\n" +
                "`sir`.`part_engineering` AS `part_engineering`,\n" +
                "`sir`.`risk_num` AS `risk_num`,\n" +
                "`sir`.`risk_name` AS `risk_name`,\n" +
                "`sir`.`danger_des` AS `danger_des`,\n" +
                "`sir`.`accident_type` AS `accident_type`,\n" +
                "`sir`.`control_level` AS `control_level`,\n" +
                "`sir`.`duty_person` AS `duty_person`,\n" +
                "`sir`.`engineering_measure` AS `engineering_measure`,\n" +
                "`sir`.`control_measures` AS `control_measures`,\n" +
                "`sir`.`train_content` AS `train_content`,\n" +
                "`sir`.`individual_protection` AS `individual_protection`,\n" +
                "`sir`.`emergency_measures` AS `emergency_measures`,\n" +
                "`sir`.`relieve_status` AS `relieve_status`,\n" +
                "`sir`.`content` AS `content`,\n" +
                "`sir`.`standard_require` AS `standard_require`,\n" +
                "`sir`.`create_id` AS `create_id`,\n" +
                "`sir`.`create_time` AS `create_time`,\n" +
                "`sir`.`update_time` AS `update_time`,\n" +
                "`sir`.`ref_type` AS `ref_type`,\n" +
                "`sir`.`deleted` AS `deleted`,\n" +
                "`sir`.`is_push` AS `is_push`,\n" +
                "`su`.`nick_name` AS `create_name`,\n" +
                "`ip`.`id` AS `push_id`,\n" +
                "`ip`.`environment_type` AS `environment_type` \n" +
                "from `safe_inspect_risk` `sir`\n" +
                "LEFT JOIN `sys_user` `su` ON `sir`.`create_id` = `su`.`user_id`\n" +
                "LEFT JOIN `interface_push_v2` `ip` ON ( `sir`.`id` = `ip`.`data_id` AND `ip`.`data_type` = 'safe_inspect_risk' AND `ip`.`environment_type` = '#{environmentType}' )";

        System.out.println(viewSql);
    }
}
