package com.zfire.mall.manager.logic.front;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.front.CustomerOrderTrackTocBean;
import com.zfire.mall.manager.bean.front.EquipmentCodeBatchTo;
import com.zfire.mall.manager.bean.front.EquipmentCodeBatchVO;
import com.zfire.mall.manager.bean.front.EquipmentCodeVO;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.utils.excel.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
@Slf4j
public class EquipmentCodeLogic {


    @Value("${gongdan.url}")
    private String k3CloudURL;

    @Value("${equipment.code.url}")
    private String equipmentCodeUrl;


    @Autowired
    private CommonLogic commonLogic;


    /**
     * 条码核验列表
     * @return
     */
    public IPage<EquipmentCodeVO> list(String barCode, String orderNumber, Integer pageNo, String salesCompany, String address,
                                       String startTime, String endTime, String verificationStartTime, String verificationEndTime, String productName,
                                       String warehouse, String websitNumber, String workerName, Integer pageSize, HttpServletRequest request) {
        try {
            HashMap<String, Object> paramToken = new HashMap<>();
            paramToken.put("key", equipmentCodeUrl);
            String bodyParam = HttpRequest.get(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_GET_TOKEN)
                    .form(paramToken).execute().body();
            Map<String, Object> smsRspParam = JSON.parseObject(bodyParam);

            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("barCode", barCode);
            paramMap.put("orderNumber", orderNumber);
            paramMap.put("pageNo", pageNo);
            paramMap.put("salesCompany", salesCompany);
            paramMap.put("address", address);
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            paramMap.put("verificationStartTime", verificationStartTime);
            paramMap.put("verificationEndTime", verificationEndTime);
            paramMap.put("productName", productName);
            paramMap.put("warehouse", warehouse);
            paramMap.put("websitNumber", websitNumber);
            paramMap.put("workerName", workerName);
            paramMap.put("pageSize", pageSize);
            paramMap.put("request", request);
            String body = HttpRequest.get(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE)
                    .header("token", smsRspParam.get("data").toString())
                    .form(paramMap).execute().body();

            Map<String, Object> smsRsp = JSON.parseObject(body);
            //获取数据
            Object object = JSON.parseObject(smsRsp.get("data").toString()).get("records");
            JSONArray jsonArray = JSONUtil.parseArray(object);
            List<EquipmentCodeVO> equipmentCodeVOS = JSONUtil.toList(jsonArray, EquipmentCodeVO.class);
            IPage<EquipmentCodeVO> equipmentCodeVOIPage = new Page<>();
            equipmentCodeVOIPage.setRecords(equipmentCodeVOS);
            equipmentCodeVOIPage.setTotal(Convert.toLong(JSON.parseObject(smsRsp.get("data").toString()).get("total")));
            equipmentCodeVOIPage.setPages(Convert.toLong(JSON.parseObject(smsRsp.get("data").toString()).get("pages")));
            equipmentCodeVOIPage.setCurrent(Convert.toLong(JSON.parseObject(smsRsp.get("data").toString()).get("current")));
            equipmentCodeVOIPage.setSize(Convert.toLong(JSON.parseObject(smsRsp.get("data").toString()).get("size")));
            return equipmentCodeVOIPage;
        } catch (Exception e) {
            throw new RemoteServiceException(e.getMessage());
        }
    }

    public String importBatch(MultipartFile file, HttpServletRequest request) {
        try {


            //读取excel数据
            Long start, end;
            String batch = IdWorker.getIdStr();

            start = System.currentTimeMillis();

            List<Object> list = ExcelUtils.importExcel(file);

            List<EquipmentCodeBatchTo> equipmentCodeChecks = new ArrayList<>();

            AdminUserCom adminUser = commonLogic.getAdminUser();
            for (int i = 0; i < list.size(); i++) {
                List<String> row = (List<String>) list.get(i);

                if (StringUtils.isEmpty(row.get(0))) {
                    continue;
                }

                EquipmentCodeBatchTo bean = new EquipmentCodeBatchTo();
                bean.setBatch(batch);
                bean.setBarCode(row.get(0));
                bean.setVerificationStatus(2);
                bean.setVerificationTime(new Date());
                bean.setCreateBy("供应链账号校验:"+adminUser.getNickName());
                bean.setCreateByNumber("供应链账号校验:"+adminUser.getNickName());
                bean.setCreateTime(new Date());
                bean.setUpdateTime(new Date());


                equipmentCodeChecks.add(bean);
            }

            String s = JSONUtil.toJsonStr(equipmentCodeChecks);


            HashMap<String, Object> paramToken = new HashMap<>();
            paramToken.put("key", equipmentCodeUrl);
            String bodyParam = HttpRequest.get(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_GET_TOKEN)
                    .form(paramToken).execute().body();
            Map<String, Object> smsRspParam = JSON.parseObject(bodyParam);

            String body = HttpRequest.post(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_IMPORT_BATCH)
                    .header("token", smsRspParam.get("data").toString())
                   .body(s)
                    .execute().body();

            Map<String, Object> smsRsp = JSON.parseObject(body);
            //获取数据
            return smsRsp.get("data").toString();
        } catch (Exception e) {
            throw new RemoteServiceException(e.getMessage());
        }
    }

    public IPage<EquipmentCodeBatchVO> listBatch(String startTimeSingle, String batch, String barCode, Integer pageNo, String startTime,
                                                 String endTime, Integer pageSize, HttpServletRequest request) {
        try {


            HashMap<String, Object> paramToken = new HashMap<>();
            paramToken.put("key", equipmentCodeUrl);
            String bodyParam = HttpRequest.get(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_GET_TOKEN)
                    .form(paramToken).execute().body();
            Map<String, Object> smsRspParam = JSON.parseObject(bodyParam);

            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("barCode", barCode);
            paramMap.put("startTimeSingle", startTimeSingle);
            paramMap.put("pageNo", pageNo);
            paramMap.put("batch", batch);
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            paramMap.put("pageSize", pageSize);
            paramMap.put("request", request);
            String body = HttpRequest.get(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_CHECK)
                    .header("token", smsRspParam.get("data").toString())
                    .form(paramMap).execute().body();

            Map<String, Object> smsRsp = JSON.parseObject(body);
            //获取数据
            Object object = JSON.parseObject(smsRsp.get("data").toString()).get("records");
            JSONArray jsonArray = JSONUtil.parseArray(object);
            List<EquipmentCodeBatchVO> equipmentCodeVOS = JSONUtil.toList(jsonArray, EquipmentCodeBatchVO.class);
            IPage<EquipmentCodeBatchVO> equipmentCodeVOIPage = new Page<>();
            equipmentCodeVOIPage.setRecords(equipmentCodeVOS);
            equipmentCodeVOIPage.setTotal(Convert.toLong(JSON.parseObject(smsRsp.get("data").toString()).get("total")));
            equipmentCodeVOIPage.setPages(Convert.toLong(JSON.parseObject(smsRsp.get("data").toString()).get("pages")));
            equipmentCodeVOIPage.setCurrent(Convert.toLong(JSON.parseObject(smsRsp.get("data").toString()).get("current")));
            equipmentCodeVOIPage.setSize(Convert.toLong(JSON.parseObject(smsRsp.get("data").toString()).get("size")));
            return equipmentCodeVOIPage;
        } catch (Exception e) {
            throw new RemoteServiceException(e.getMessage());
        }
    }

    public ExcelData exportBatch(String startTimeSingle, String batch, String barCode, Integer pageNo, String startTime, String endTime, Integer pageSize, HttpServletRequest request) {
        try {

            if (startTime == null)
                throw new RemoteServiceException("筛选时间必填");


            HashMap<String, Object> paramToken = new HashMap<>();
            paramToken.put("key", equipmentCodeUrl);
            String bodyParam = HttpRequest.get(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_GET_TOKEN)
                    .form(paramToken).execute().body();
            Map<String, Object> smsRspParam = JSON.parseObject(bodyParam);

            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("barCode", barCode);
            paramMap.put("startTimeSingle", startTimeSingle);
            paramMap.put("pageNo", pageNo);
            paramMap.put("batch", batch);
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            paramMap.put("pageSize", pageSize);
            paramMap.put("request", request);
            String body = HttpRequest.get(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_CHECK_EXPORT)
                    .header("token", smsRspParam.get("data").toString())
                    .form(paramMap).execute().body();

            Map<String, Object> smsRsp = JSON.parseObject(body);
            //获取数据
            ExcelData data = JSONUtil.toBean(smsRsp.get("data").toString(), ExcelData.class);

            return data;
        } catch (Exception e) {
            throw new RemoteServiceException(e.getMessage());
        }
    }

    public ExcelData export(String orderNumber, String salesCompany, String barCode, String address, String verificationStartTime, String startTime, String endTime,
                            String verificationEndTime, String productName, String warehouse, String websitNumber, String workerName, HttpServletRequest request) {
        try {

            if (startTime == null)
                throw new RemoteServiceException("筛选时间必填");


            HashMap<String, Object> paramToken = new HashMap<>();
            paramToken.put("key", equipmentCodeUrl);
            String bodyParam = HttpRequest.get(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_GET_TOKEN)
                    .form(paramToken).execute().body();
            Map<String, Object> smsRspParam = JSON.parseObject(bodyParam);


            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("barCode", barCode);
            paramMap.put("orderNumber", orderNumber);
            paramMap.put("salesCompany", salesCompany);
            paramMap.put("address", address);
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            paramMap.put("verificationStartTime", verificationStartTime);
            paramMap.put("verificationEndTime", verificationEndTime);
            paramMap.put("productName", productName);
            paramMap.put("warehouse", warehouse);
            paramMap.put("websitNumber", websitNumber);
            paramMap.put("workerName", workerName);
            paramMap.put("request", request);
            String url = k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_CHECK_EXPORT_CODE;
            String body = HttpRequest.get(url)
                    .header("token", smsRspParam.get("data").toString())
                    .form(paramMap).execute().body();

            Map<String, Object> smsRsp = JSON.parseObject(body);
            //获取数据
            ExcelData data = JSONUtil.toBean(smsRsp.get("data").toString(), ExcelData.class);

            return data;
        } catch (Exception e) {
            throw new RemoteServiceException(e.getMessage());
        }
    }
}
