package easydo.technology.controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Comparator;
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.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.date.LocalDateTimeUtil;
import easydo.technology.annotation.WebLog;
import easydo.technology.components.JdbcClient;
import easydo.technology.enums.ChengfaEnum;
import easydo.technology.exception.BizException;
import easydo.technology.model.Message;
import easydo.technology.model.Purchase;
import easydo.technology.model.PurchaseBidNotice;
import easydo.technology.model.PurchaseContract;
import easydo.technology.model.PurchasePlan;
import easydo.technology.model.Supplier;
import easydo.technology.model.SupplierBank;
import easydo.technology.model.SysUser;
import easydo.technology.model.vo.ContractVo;
import easydo.technology.model.vo.GLDMessage;
import easydo.technology.model.vo.MDMDept;
import easydo.technology.model.vo.MDMSupplier;
import easydo.technology.model.vo.MDMUser;
import easydo.technology.system.domain.SysDept;
import easydo.technology.utils.LocalDateUtil;
import easydo.technology.utils.StringUtil;
import lombok.extern.java.Log;

@Log
@RestController
@RequestMapping("/api")
public class ApiController {
    private final String TOKEN = "1253c4fa-e999-46b4-8c41-17645f997a6d";
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;
    @Resource
    PasswordEncoder passwordEncoder;

    @WebLog
    @RequestMapping(value = "/supplier/getList")
    public Object getSupplierList(@RequestBody Map<String, Object> map) throws Exception {
        String token = map.get("token").toString();
        map.remove("token");
        List<Supplier> list = new ArrayList<>();
        if (!TOKEN.equals(token)) {
            return new ResponseEntity<>(list, HttpStatus.OK);
        }
        Connection connection = null;
        try {
            connection = dataSource.getConnection();

            list = jdbcClient.getJdbcList(map, Supplier.class, connection);

            for (Supplier model : list) {
                SupplierBank supplierBank = new SupplierBank();
                supplierBank.setSupplierId(model.getId());
                List<SupplierBank> bankList = jdbcClient.getJdbcList(supplierBank, connection);
                model.setBankList(bankList);
            }
            return new ResponseEntity<>(list, HttpStatus.OK);
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/bidNotice/getList")
    public Object getNoticeList(@RequestBody Map<String, Object> map) throws Exception {
        String token = map.get("token").toString();
        map.remove("token");
        List<PurchaseBidNotice> list = new ArrayList<>();
        if (!TOKEN.equals(token)) {
            return new ResponseEntity<>(list, HttpStatus.OK);
        }
        Connection connection = null;
        try {
            connection = dataSource.getConnection();

            map.put("status", ChengfaEnum.PURCHASE_STATUS_DONE.getValue());
            map.put("projectIdBegin", 0);
            list = jdbcClient.getJdbcList(map, PurchaseBidNotice.class, connection);

            for (PurchaseBidNotice model : list) {
                Purchase purchase = new Purchase();
                purchase.setId(model.getPurchaseId());
                purchase = jdbcClient.getJdbcModelById(purchase, connection);
                model.setPurchaseName(purchase.getName());
                model.setPurchaseNo(purchase.getPurchaseNo());

                PurchasePlan plan = new PurchasePlan();
                plan.setId(purchase.getPlanId());
                plan = jdbcClient.getJdbcModelById(plan, connection);
                model.setContractPlanCode(plan.getContractPlanCode());
                model.setContractPlanName(plan.getContractPlanName());
            }
            return new ResponseEntity<>(list, HttpStatus.OK);
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/contract/push")
    public Object pushContract(@RequestBody ContractVo vo) throws Exception {
        String token = vo.getToken();
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        if (!TOKEN.equals(token)) {
            result.put("message", "no auth");
            return new ResponseEntity<>(result, HttpStatus.OK);
        }
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            if (StringUtil.isEmpty(vo.getPurchaseId())) {

                if (StringUtil.isEmpty(vo.getPurchaseNo())) {
                    result.put("message", "采购编号purchaseNo无效");
                    return new ResponseEntity<>(result, HttpStatus.OK);
                }
                Purchase purchase = new Purchase();
                purchase.setPurchaseNo(vo.getPurchaseNo());
                purchase = jdbcClient.getJdbcModel(purchase, connection);
                if (StringUtil.isEmpty(purchase.getId())) {
                    result.put("message", "采购编号purchaseNo无效");
                    return new ResponseEntity<>(result, HttpStatus.OK);
                }
                vo.setPurchaseId(purchase.getId());
            }

            // PurchaseBidNotice bidNotice = new PurchaseBidNotice();
            // if (StringUtil.isEmpty(vo.getSupplierName())) {
            // bidNotice.setPurchaseId(vo.getPurchaseId());
            // bidNotice = jdbcClient.getJdbcModel(bidNotice, connection);
            // if (StringUtil.isEmpty(bidNotice.getBidCompanyIds())) {
            // throw new BizException("采购数据没有中标单位");
            // }
            // vo.setSupplierId(bidNotice.getBidCompanyIds());
            // vo.setSupplierName(bidNotice.getBidCompanyName());
            // } else {
            Supplier supplier = new Supplier();
            supplier.setSupplierName(vo.getSupplierName());
            supplier = jdbcClient.getJdbcModel(supplier, connection);
            if (StringUtil.isEmpty(supplier.getId())) {
                result.put("message", "供应商名称无效");
                return new ResponseEntity<>(result, HttpStatus.OK);
            }
            vo.setSupplierId(supplier.getId());
            vo.setSupplierName(supplier.getSupplierName());
            vo.setSupplierNo(supplier.getSupplierNo());
            // }

            PurchaseContract contract = new PurchaseContract();
            contract.setContractNo(vo.getContractNo());
            contract.setContractName(vo.getContractName());
            contract.setCreateTime(vo.getContractCreateTime());
            contract.setEndTime(vo.getContractEndTime());
            contract.setProjectId(vo.getProjectId());
            contract.setPurchaseId(vo.getPurchaseId());
            contract.setSignAmount(vo.getContractAmount());
            contract.setSupplierId(vo.getSupplierId());
            contract.setSupplierName(vo.getSupplierName());
            contract.setSupplierNo(vo.getSupplierNo());
            jdbcClient.jdbcInsert(contract, connection);

            result.put("message", "success");
            result.put("code", 1);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            result.put("message", "fail" + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.OK);
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/mdmdept/push")
    public Object pushMdmDept(@RequestBody JSONObject object) throws Exception {
        log.info("接收到MDM的组织数据======>" + object.toJSONString());
        Map<String, Object> result = new HashMap<>();

        JSONArray array = object.getJSONArray("Parameters");
        String json = JSON.toJSONString(array);
        List<MDMDept> mdmDeptList = JSON.parseArray(json, MDMDept.class);
        mdmDeptList = mdmDeptList.stream().sorted(Comparator.comparing(MDMDept::getC_HR_MANAGEMENT_UNIT))
                .collect(Collectors.toList());
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);
            for (MDMDept model : mdmDeptList) {
                SysDept dept = new SysDept();
                dept.setCode(model.getC_INTERNAL_UNIT_CODE());
                dept.setName(model.getC_FULLNAME());
                dept.setFirmAddress(model.getC_ADDRESS());
                dept.setFirmCredit(model.getC_UNIFIED_SOCIALCREDIT_CODE());
                dept.setFirmOfficePhone(model.getC_PHONE());
                if ("1".equals(model.get_STATUS())) {
                    dept.setEnabled(true);
                } else {
                    dept.setEnabled(false);
                }
                dept.setCreateTime(LocalDateUtil.localDateTimeFormatyMdHms(LocalDateTimeUtil.of(Long.valueOf(model.get_CREATE_TIME()))));
                dept.setUpdateTime(dept.getCreateTime());

                SysDept pDept = new SysDept();
                pDept.setCode(model.getC_HR_MANAGEMENT_UNIT());
                pDept = jdbcClient.getJdbcModel(pDept, connection);
                if (StringUtil.isNotEmpty(pDept.getDeptId())) {
                    dept.setPid(pDept.getDeptId());
                }
                pDept.setSubCount(pDept.getSubCount() + 1);
                jdbcClient.jdbcUpdateById(pDept, connection);

                SysDept exist = new SysDept();
                exist.setCode(model.getC_INTERNAL_UNIT_CODE());
                exist = jdbcClient.getJdbcModel(exist, connection);
                if (StringUtil.isEmpty(exist.getDeptId())) {
                    dept.setDeptId((long) 0);
                    jdbcClient.jdbcInsert(dept, connection);
                }else {
                    dept.setDeptId(exist.getDeptId());
                    jdbcClient.jdbcUpdateById(dept, connection);
                }

                connection.commit();
            }
            result.put("code", 200);
            result.put("msg", "成功");
            result.put("result", "S");
            return result;
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/mdmuser/push")
    public Object pushMdmUser(@RequestBody JSONObject object) throws Exception {
        log.info("接收到MDM的用户数据======>" + object.toJSONString());
        Map<String, Object> result = new HashMap<>();

        JSONArray array = object.getJSONArray("Parameters");
        String json = JSON.toJSONString(array);
        List<MDMUser> mdmUserList = JSON.parseArray(json, MDMUser.class);
        mdmUserList = mdmUserList.stream().sorted(Comparator.comparing(MDMUser::getC_INTERNAL_DEPARTMENT))
                .collect(Collectors.toList());
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            for (MDMUser model : mdmUserList) {
                SysUser user = new SysUser();
                user.setCode(model.getC_USER_CODE());
                user.setNickName(model.getC_USER_NAME());
                user.setPhone(model.getC_MOBILEPHONE_NUMBER());
                user.setCreateTime(LocalDateUtil
                        .localDateTimeFormatyMdHms(LocalDateTimeUtil.of(Long.valueOf(model.get_CREATE_TIME()))));
                user.setUpdateTime(user.getCreateTime());
                user.setGender(model.getC_GENDER().substring(0, 1));
                if ("1".equals(model.getSTATUS())) {
                    user.setEnabled(true);
                } else {
                    user.setEnabled(false);
                }
                user.setIdCard(model.getC_IDENTITY_NUMBER());
                user.setOriginPassword(model.getC_USER_CODE());
                user.setPassword(passwordEncoder.encode(model.getC_USER_CODE()));

                SysDept dept = new SysDept();
                dept.setCode(model.getC_INTERNAL_DEPARTMENT().split("_")[0]);
                dept = jdbcClient.getJdbcModel(dept, connection);
                if (StringUtil.isNotEmpty(dept.getDeptId())) {
                    user.setDeptId(dept.getDeptId());
                }

                SysUser exist = new SysUser();
                exist.setUsername(model.getC_USER_CODE());
                jdbcClient.getJdbcModel(exist,connection);
                if (StringUtil.isEmpty(exist.getUserId())) {
                    user.setUserId((long) 0);
                    jdbcClient.jdbcInsert(user, connection);
                } else {
                    user.setUserId(exist.getUserId());
                    jdbcClient.jdbcUpdateById(user, connection);
                }
            }
            result.put("code", 200);
            result.put("msg", "成功");
            result.put("result", "S");
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/mdmsupplier/push")
    public Object pushMdmSupplier(@RequestBody JSONObject object) throws Exception {
        log.info("接收到MDM的供应商数据======>" + object.toJSONString());
        Map<String, Object> result = new HashMap<>();

        JSONArray array = object.getJSONArray("Parameters");
        String json = JSON.toJSONString(array);
        List<MDMSupplier> mdmSupplierList = JSON.parseArray(json, MDMSupplier.class);

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            for (MDMSupplier model : mdmSupplierList) {

                Supplier exist = new Supplier();
                exist.setCreditCode(model.getC_UNISOCIALCREDIT_CODE());
                exist = jdbcClient.getJdbcModel(exist, connection);
                if (StringUtil.isEmpty(exist.getId())) {
                    exist.setSupplierNo(model.getC_EXTERNAL_UNIT_CODE());
                    jdbcClient.jdbcUpdateById(exist, connection);
                }
            }
            result.put("code", 200);
            result.put("msg", "成功");
            result.put("result", "S");
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/message/push")
    public Object pushMessage(@RequestBody GLDMessage gldMessage) throws Exception {
        String token = gldMessage.getToken();
        String type = gldMessage.getRefType();
        String instanceId = gldMessage.getInstanceId();
        if (!TOKEN.equals(token)) {
            return new ResponseEntity<>("no auth", HttpStatus.OK);
        }
        if (StringUtil.isEmpty(gldMessage.getReceiveUserCode()) || StringUtil.isEmpty(instanceId)) {
            return new ResponseEntity<>("参数无效", HttpStatus.OK);
        }
        Connection connection = null;
        String businessId = "";
        ResultSet resultSet = null;
        try {
            connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            Message message = new Message();
            BeanUtils.copyProperties(gldMessage, message);

            SysUser receiveUser = new SysUser();
            receiveUser.setCode(gldMessage.getReceiveUserCode());
            receiveUser = jdbcClient.getJdbcModel(receiveUser, connection);
            message.setReceiveUserId(receiveUser.getUserId());
            message.setReceiveUserName(receiveUser.getNickName());

            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);
            }
            message.setRefId(businessId);
            jdbcClient.jdbcInsert(message, connection);

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