package com.fjhx.task.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fjhx.entity.stock.StockInoutbill;
import com.fjhx.stock.service.StockInoutbillService;
import com.fjhx.task.mapper.ScheduleTaskMapper;
import com.fjhx.task.service.ScheduleTaskService;
import org.springblade.core.launch.BladeApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
public class ScheduleTaskServiceImpl implements ScheduleTaskService {

    private static final RestTemplate restTemplate;

    private static final String GET_ACCESS_TOKEN_ACTION_URL;

    private static final String STOCK_ACCEPT_ACTION;

    private static final String SELECT_PUBLISHED_SQL;
    private static final String UPDATE_PUBLISHED_SQL;

    @Autowired
    private ScheduleTaskMapper scheduleTaskMapper;

    @Autowired
    private StockInoutbillService stockInoutbillService;

    static {
        restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        if (BladeApplication.isLocalDev()) {
            GET_ACCESS_TOKEN_ACTION_URL = "http://106.14.146.72:8087/portal/getAccessTokenAction.do?AppId=1&AppSecret=a2b1c2d3";
            STOCK_ACCEPT_ACTION = "http://106.14.146.72:8087/SrmWeb/stockAcceptAction.do?action=custom&access_token=";
            SELECT_PUBLISHED_SQL = "select Id id,Content content from `cap.published_copy1` where handle is null";
            UPDATE_PUBLISHED_SQL = "UPDATE `cap.published_copy1` SET handle=1 WHERE id=";
        } else {
            GET_ACCESS_TOKEN_ACTION_URL = "http://mes.cfmfactory.com:8087/portal/getAccessTokenAction.do?AppId=1&AppSecret=a2b1c2d3";
            STOCK_ACCEPT_ACTION = "http://mes.cfmfactory.com:8087/SrmWeb/stockAcceptAction.do?action=custom&access_token=";
            SELECT_PUBLISHED_SQL = "select Id id,Content content from `cap.published` where handle is null";
            UPDATE_PUBLISHED_SQL = "UPDATE `cap.published` SET handle=1 WHERE id=";
        }
    }

    @Override
    public void stockAcceptActionTask() {

        List<Map<String, Object>> selectPublishedList = scheduleTaskMapper.selectPublished(SELECT_PUBLISHED_SQL);

        // 获取token
        String token = getToken(GET_ACCESS_TOKEN_ACTION_URL);

        for (Map<String, Object> stringStringMap : selectPublishedList) {

            String content = stringStringMap.get("content").toString();
            // 内容
            JSONObject contentMap = JSONObject.parseObject(content);
            JSONObject value = contentMap.getJSONObject("Value");
            String userId = value.getString("UserId");

            Map<String, String> userIdAndJobNo = scheduleTaskMapper.selectUserIdAndJobNo(userId);

            String id = userIdAndJobNo.get("id");
            String jobNo = userIdAndJobNo.get("jobNo");

            if (ObjectUtil.isEmpty(id) || ObjectUtil.isEmpty(jobNo) || id.equals(jobNo)) {
                scheduleTaskMapper.updatePublished(UPDATE_PUBLISHED_SQL + stringStringMap.get("id"));
                continue;
            }

            try {
                // 获取排班物料
                HashMap<String, String> map = new HashMap<>();

                map.put("material", value.getString("MaterialCode"));
                map.put("type", value.getString("Type"));
                map.put("begNum", value.getString("BegNum"));
                map.put("endNum", value.getString("EndNum"));
                map.put("count", value.getString("Qty"));
                map.put("userId", jobNo);
                map.put("createDate", value.getString("CreateDate"));

                ResponseEntity<String> stockAcceptActionResult = restTemplate.postForEntity(STOCK_ACCEPT_ACTION + token, map, String.class);
                String stockAcceptActionBody = stockAcceptActionResult.getBody();

                if (JSONObject.parseObject(stockAcceptActionBody).getBoolean("success")) {
                    scheduleTaskMapper.updatePublished(UPDATE_PUBLISHED_SQL + stringStringMap.get("id"));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public synchronized void schedulingTask() {

        // 请求v3接口获取token
        String token = getToken("http://mes.cfmfactory.com:8087/portal/getAccessTokenAction.do?AppId=1&AppSecret=a2b1c2d3");

        // 请求v3接口获取所有人领料信息
        Date date = new Date();

        String beginDate = DateUtil.format(DateUtil.offsetDay(date, -2), "yyyy-MM-dd 00:00:00");
        // beginDate = "2022-06-01 00:00:00";
        String endDate = DateUtil.format(date, "yyyy-MM-dd 23:59:59");

        String url = "http://mes.cfmfactory.com:8087/MesWeb/planPersonOutAction.do?action=list&beginDate=" + beginDate
                + "&endDate=" + endDate + "&access_token=" + token;

        String resultStr = restTemplate.getForEntity(url, String.class).getBody();
        JSONObject resultMap = JSONObject.parseObject(resultStr);
        // 接收到的消息
        List<JSONObject> items = (List<JSONObject>) resultMap.get("items");

        stockInoutbillService.remove(Wrappers.<StockInoutbill>lambdaQuery().between(StockInoutbill::getDeviationTime, beginDate, endDate));

        Map<String, StockInoutbill> flagMap = new HashMap<>();

        Date newDate = new Date();

        // 循环领料信息
        items.forEach(item -> {
            // 喷印人员工号
            long distributor = Long.parseLong(item.get("distributor").toString());
            // 打纸人员工号
            long paperMan = Long.parseLong(item.get("paperMan").toString());
            // 排班面积
            BigDecimal plantotalsquare = new BigDecimal(item.get("plantotalsquare").toString());
            // 物料名称
            String material = item.get("material").toString();
            // 排班时间
            String planDate = item.get("planDate").toString();

            // 喷印人员工号添加领料记录标记
            addOrEditFlagMap(flagMap, distributor, plantotalsquare, planDate, material, newDate);

            // 打纸人员工号添加领料记录标记
            if (paperMan > 0) {
                addOrEditFlagMap(flagMap, paperMan, plantotalsquare, planDate, "热转印纸", newDate);
            }

        });

        // 更新当天的出库单
        stockInoutbillService.saveBatch(new ArrayList<>(flagMap.values()));
    }

    private String getToken(String url) {
        // 获取token
        String result = restTemplate.getForEntity(url, String.class).getBody();
        if (ObjectUtil.isEmpty(result)) return null;
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("token");
    }

    private void addOrEditFlagMap(Map<String, StockInoutbill> flagMap, Long jobNo, BigDecimal plantotalsquare, String planDate, String material, Date date) {
        String key = jobNo + material + planDate;
        StockInoutbill stockInoutbill = flagMap.get(key);

        if (stockInoutbill == null) {
            stockInoutbill = new StockInoutbill();
            stockInoutbill.setJobNo(jobNo);
            stockInoutbill.setSchedulingMaterial(material);
            stockInoutbill.setDeviationTime(DateUtil.parse(planDate));
            stockInoutbill.setQuantity(plantotalsquare);
            stockInoutbill.setCreateTime(date);

            flagMap.put(key, stockInoutbill);
        } else {
            BigDecimal quantity = stockInoutbill.getQuantity();
            stockInoutbill.setQuantity(quantity.add(plantotalsquare));
        }

    }

//    public static void main(String[] args) {
//
//        List<String> strings1 = Arrays.asList(
//                "01.002.0116",
//                "01.002.0023",
//                "01.002.0128",
//                "01.002.0050",
//                "01.002.0076",
//                "01.002.0042",
//                "01.002.0126",
//                "01.002.0096",
//                "01.002.0043",
//                "01.002.0177",
//                "01.002.0123",
//                "01.002.0095",
//                "01.002.0037",
//                "01.002.0052",
//                "01.001.0045",
//                "01.002.0038",
//                "01.002.0174",
//                "01.002.0079",
//                "01.001.0087",
//                "01.002.0120",
//                "01.003.0003",
//                "01.002.0094",
//                "01.004.0002",
//                "01.002.0059",
//                "01.001.0059",
//                "01.002.0021",
//                "01.002.0383",
//                "01.001.0006",
//                "01.001.0055",
//                "01.001.0033",
//                "01.001.0044",
//                "01.002.0049",
//                "01.001.0009",
//                "01.002.0017",
//                "01.002.0039"
//        );
//
//        List<String> strings2 = Arrays.asList(
//                "10.00",
//                "100.00",
//                "162.00",
//                "0.00",
//                "50.00",
//                "80.00",
//                "15.00",
//                "0.00",
//                "434.00",
//                "0.00",
//                "34.00",
//                "0.00",
//                "40.00",
//                "70.00",
//                "130.00",
//                "929.00",
//                "55.00",
//                "20.00",
//                "45.00",
//                "95.00",
//                "40.00",
//                "0.00",
//                "90.00",
//                "15.00",
//                "0.00",
//                "967.00",
//                "236.40",
//                "15.00",
//                "260.00",
//                "70.00",
//                "120.00",
//                "60.00",
//                "75.00",
//                "0.00",
//                "105.00"
//        );
//
//
//        // 获取token
//        ResponseEntity<String> entity
//                = restTemplate.getForEntity(
//                "http://mes.cfmfactory.com:8087/portal/getAccessTokenAction.do?AppId=1&AppSecret=a2b1c2d3", String.class);
//        String body = entity.getBody();
//        if (ObjectUtil.isEmpty(body)) return;
//        JSONObject jsonObject = JSONObject.parseObject(body);
//        String token = jsonObject.get("token").toString();
//        if (ObjectUtil.isEmpty(token)) return;
//
//
//        for (int i = 0; i < strings1.size(); i++) {
//            // 获取排班物料
//            HashMap<String, String> map = new HashMap<>();
//
//            map.put("material", strings1.get(i));
//            map.put("type", "1");
//            map.put("begNum", "0.00");
//            map.put("endNum", strings2.get(i));
//            map.put("count", strings2.get(i));
//            map.put("userId", "2206008");
//            map.put("createDate", LocalDateTime.now().toString());
//
//            ResponseEntity<String> stockAcceptActionResult =
//                    restTemplate.postForEntity("http://mes.cfmfactory.com:8087/SrmWeb/stockAcceptAction.do?action=custom&access_token=" + token, map, String.class);
//            String stockAcceptActionBody = stockAcceptActionResult.getBody();
//            System.out.println(map);
//            System.out.println(stockAcceptActionBody);
//            System.out.println();
//            System.out.println();
//        }
//    }

}
