//package com.gree.mall.miniapp.logic.common;
//
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
//import com.baomidou.mybatisplus.core.toolkit.IdWorker;
//
//import com.gree.mall.miniapp.bean.order.WorkerOrderInfo;
//import com.gree.mall.miniapp.constant.Constant;
//import com.gree.mall.miniapp.exception.RemoteServiceException;
//import com.gree.mall.miniapp.plus.entity.OrderDetail;
//import com.gree.mall.miniapp.plus.entity.OrderInfo;
//import com.gree.mall.miniapp.plus.entity.OrderRequest;
//import com.gree.mall.miniapp.plus.service.OrderDetailService;
//import com.gree.mall.miniapp.plus.service.OrderInfoService;
//import com.gree.mall.miniapp.plus.service.OrderRequestService;
//import com.gree.mall.miniapp.utils.AESUtils;
//import com.gree.mall.miniapp.utils.RedisUtil;
//import com.gree.mall.miniapp.utils.http.HttpUtils;
//import com.gree.mall.miniapp.utils.refund.Base64Util;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.junit.Test;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.scheduling.annotation.Async;
//import org.springframework.stereotype.Service;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
///**
// * 对接工单系统
// */
//@Slf4j
//@Service
//public class GongdanLogic {
//
//    @Value("${gongdan.token.get.url}")
//    private String getTokenUrl;
//    @Value("${gongdan.install.create.url}")
//    private String createInstallUrl;
//    @Value("${gongdan.repair.create.url}")
//    private String createRepairUrl;
//    @Value("${gongdan.install.detail.url}")
//    private String detailInstallUrl;
//    @Value("${gongdan.repair.detail.url}")
//    private String detailRepairUrl;
//    @Value("${gongdan.client_name}")
//    private String clientName;
//    @Value("${gongdan.password}")
//    private String password;
//    @Value("${gongdan.key}")
//    private String key;
//
//    @Autowired
//    OrderInfoService orderInfoService;
//    @Autowired
//    OrderDetailService orderDetailService;
//    @Autowired
//    OrderRequestService orderRequestService;
//
//    @Autowired
//    RedisUtil redisUtil;
//
//    /**
//     * 获取工单token
//     * @return
//     * @throws RemoteServiceException
//     */
//    public String getGongdanToken() throws Exception {
//        redisUtil.del(Constant.RedisPrefix.TOKEN_GONGDAN);
//        if(redisUtil.hasKey(Constant.RedisPrefix.TOKEN_GONGDAN)){
//            String token = (String)redisUtil.get(Constant.RedisPrefix.TOKEN_GONGDAN);
//            log.info("【获取工单token】：{}",token);
//            return (String)redisUtil.get(Constant.RedisPrefix.TOKEN_GONGDAN);
//        }
//        Map<String,Object> dataContents = new HashMap<>();
//        dataContents.put("password",password);
//        //请求php服务
//        JSONObject jsonObject = this.doPhpSevice(dataContents,null, getTokenUrl);
//        JSONObject data = (JSONObject) jsonObject.get("data");
//        //String time = (String) jsonObject.get("time");
//        long time = new Date().getTime() / 1000;
//        Integer exp = (Integer) data.get("exp");
//        String token = (String)data.get("token");
//        String prefix = (String)data.get("prefix");
//        redisUtil.set(Constant.RedisPrefix.TOKEN_GONGDAN,prefix+token,exp - time - 100);
//
//        return token;
//    }
//
//
//    /**
//     * 创建安装工单
//     * @param orderInfo
//     * @param mainNumber
//     * @return
//     * @throws Exception
//     */
//    @Async
//    public String installOrder(OrderInfo orderInfo, List<OrderDetail> orderDetailList, String mainNumber) throws Exception {
//        if(!orderInfo.getWorkOrder()){
//            return null;
//        }
//        List<OrderDetail> orderDetail = orderDetailList.stream().filter(o -> o.getMainNumber().equals(mainNumber)).collect(Collectors.toList());
//        if(CollectionUtils.isEmpty(orderDetail)){
//            return null;
//        }
//        List<Integer> marketingIds = orderDetail.stream().map(OrderDetail::getMarketingId).distinct().collect(Collectors.toList());
//        for(Integer marketingId : marketingIds) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("websit_number", orderInfo.getWebsitNumber());
//            map.put("websit_worker_mobile", orderInfo.getWorkerPhone());
//            map.put("user_name", orderInfo.getReceUserName());
//            map.put("user_phone", orderInfo.getRecePhone());
//            map.put("user_phone2", orderInfo.getPhone());
//            map.put("sales_order_no", orderInfo.getOrderId());
//            if (orderInfo.getExchangeOrder()) {
//                map.put("sales_type_id", 10);
//            }
//            map.put("buy_datetime", orderInfo.getPayTime().getTime() / 1000);
//            map.put("province", orderInfo.getProvince());
//            map.put("city", orderInfo.getCity());
//            map.put("area", orderInfo.getArea());
//            map.put("street", orderInfo.getStreet());
//            map.put("address", orderInfo.getReceAddress()+orderInfo.getHouseNo());
//            map.put("request_no", IdWorker.getIdStr());
//            map.put("dispatch_type",orderInfo.getDispatchType());
//            String remark = "";
//            if(StringUtils.isNotBlank(orderInfo.getWorkerPhone()) && orderInfo.getCompanyWechatId().equals(Constant.GD_COMPANY_WECHAT_ID)){
//                remark += "师傅名称:"+orderInfo.getWorkerName() + "(" + orderInfo.getWorkerPhone() + ")";
//            }
//            if(StringUtils.isNotBlank(orderInfo.getBuyerMsg())){
//                remark += ",买家留言:"+orderInfo.getBuyerMsg();
//            }
//            if(StringUtils.isNotBlank(orderInfo.getRemark())){
//                remark +=",商家备注："+orderInfo.getRemark();
//            }
//            if(StringUtils.isNotBlank(orderInfo.getDispatchType())){
//                remark +=",工单派单方式："+orderInfo.getDispatchType();
//            }
//            if (StringUtils.isNotBlank(remark)) {
//                map.put("remark", remark);
//            }
//            if(marketingId != null && marketingId !=0) {
//                map.put("marketing_id", marketingId);
//            }
//            List<Map<String, Object>> productList = new ArrayList<>();
//            List<String> orderDetailIds = new ArrayList<>();
//            for (OrderDetail detail : orderDetail) {
//                if (!mainNumber.equals(detail.getMainNumber()) || marketingId != detail.getMarketingId()) {
//                    continue;
//                }
//                Map<String, Object> pMap = new HashMap<>();
//                pMap.put("name", detail.getGoodsName());
//                pMap.put("main_id", detail.getMainNumber());
//                pMap.put("small_id",StringUtils.isBlank(detail.getSmallNumber())?"0":detail.getSmallNumber());
//                pMap.put("number", detail.getNum() - detail.getRefundNum());
//                pMap.put("price", detail.getPayAmount().subtract(detail.getRefundAmount()));
//                pMap.put("pic_url",detail.getImgUrl());
//                productList.add(pMap);
//
//                orderDetailIds.add(detail.getOrderDetailId());
//            }
//            if (productList.size() == 0) {
//                return null;
//            }
//            map.put("product_list", productList);
//            if(orderInfo.getCompanyWechatId().equals("1")) {
//                map.put("order_source", 7);//3=分销商城
//            }else{
//                map.put("order_source",8);
//            }
//            Map<String, String> header = new HashMap<>();
//            header.put("Authorization", this.getGongdanToken());
//
//            JSONObject jsonObject = this.doPhpSevice(map, header, createInstallUrl);
//
//            JSONObject data = (JSONObject) jsonObject.get("data");
//            String workerOrderNo = (String) data.get("worker_order_no");
//            Integer workerOrderId = (Integer)data.get("id");
//
//            OrderRequest orderRequest = new OrderRequest();
//            orderRequest.setCreateTime(new Date());
//            orderRequest.setMainNumber(mainNumber);
//            orderRequest.setOrderId(orderInfo.getOrderId());
//            orderRequest.setOrderType("INSTALL");
//            orderRequest.setUserId(orderInfo.getUserId());
//            orderRequest.setWorkerOrderId(workerOrderId);
//            orderRequest.setWorkerOrderNo(workerOrderNo);
//            orderRequest.insert();
//
//            //记录工单详情的工单号
//            orderDetailService.lambdaUpdate().set(OrderDetail::getWorkerOrderNo,workerOrderNo).in(OrderDetail::getOrderDetailId,orderDetailIds).update();
//        }
//        return "";
//    }
//
//
//
//    /**
//     * 安装工单列表
//     */
//    public List<WorkerOrderInfo> getInstallOrderList(String orderId,String workerOrderNo,List<String> workerOrderNos) throws Exception {
//
//        List<WorkerOrderInfo> workerOrderInfos = new ArrayList<>();
//        try{
//            Map<String,Object> map = new HashMap<>();
//            if(StringUtils.isNotBlank(orderId)) {
//                map.put("request_order_no", orderId);
//            }
//            if(StringUtils.isNotBlank(workerOrderNo)){
//                map.put("worker_order_no",workerOrderNo);
//            }
//            if(CollectionUtils.isNotEmpty(workerOrderNos)){
//                map.put("worker_order_no_arr",workerOrderNos);
//            }
//            Map<String,String> header = new HashMap<>();
//            header.put("Authorization",this.getGongdanToken());
//            JSONObject jsonObject  = this.doPhpSevice(map, header, detailInstallUrl);
//            JSONArray datas = (JSONArray)jsonObject.get("data");
//            for(Object o : datas) {
//                JSONObject data = (JSONObject)o;
//                WorkerOrderInfo workerOrderInfo = new WorkerOrderInfo();
//                workerOrderInfo.setWorkerOrder(data.getString("worker_order_no"));
//                workerOrderInfo.setPgid(data.getString("pgid"));
//                workerOrderInfo.setWorkerName(data.getString("worker_name"));
//                workerOrderInfo.setWorkerPhone(data.getString("worker_phone"));
//                workerOrderInfo.setInstallNumber(data.getString("install_number"));
//                workerOrderInfo.setInstallName(data.getString("install_name"));
//                workerOrderInfo.setOrderStateInt(data.getInteger("order_state"));
//                workerOrderInfo.setOrderState(data.getString("order_state"));
//                workerOrderInfo.setOrderReceTime(data.getString("receive_time_text"));
//                workerOrderInfo.setFinishTime(data.getString("finish_time_text"));
//                workerOrderInfo.setReserveTime(data.getString("reserve_datetime_text"));
//                workerOrderInfo.setServerContent("安装服务");
//                workerOrderInfo.setBracket(data.getString("bracket"));
//                workerOrderInfo.setPipe(data.getString("pipe"));
//                workerOrderInfo.setSwitchFlag(data.getString("switch_flag"));
//                workerOrderInfo.setHighAltitude(data.getString("high_altitude"));
//                workerOrderInfo.setHole(data.getString("hole"));
//                workerOrderInfo.setRemark(data.getString("remark"));
//                workerOrderInfo.setPayTime(data.getString("buy_datetime_text"));
//                workerOrderInfo.setOrderId(data.getString("sales_order_no"));
//                workerOrderInfo.setMainName(data.getString("main_name"));
//                workerOrderInfo.setCreateTime(data.getString("appoint_datetime_text"));
//                //产品
//                List<Map<String, String>> products = (List<Map<String, String>>)data.get("order_install_product");
//                workerOrderInfo.setGoods(products);
//                //辅助人员
//                List<Map<String, String>> assist = (List<Map<String, String>>) data.get("assist_data_list");
//                if(CollectionUtils.isNotEmpty(assist)){
//                    workerOrderInfo.setAssistName(assist.get(0).get("name"));
//                }
//                //操作类型
//                List<WorkerOrderInfo.Fkxx> fkxxs = new ArrayList<>();
//                List<Map<String, String>> operators = (List<Map<String, String>>) data.get("order_install_operating_log");
//                if (CollectionUtils.isNotEmpty(operators)) {
//                    for (Map<String, String> operator : operators) {
//                        WorkerOrderInfo.Fkxx fkxx = new WorkerOrderInfo.Fkxx();
//                        fkxx.setOperatorType(operator.get("type"));
//                        fkxx.setOperatorContent(operator.get("content"));
//                        fkxx.setLastOperatorTime(operator.get("updatetime"));
//                        fkxx.setOperatorName(operator.get("operator"));
//                        fkxx.setOperatorWebsit(operator.get("operate_websit"));
//                        fkxx.setResult(operator.get("feedback"));
//                        fkxxs.add(fkxx);
//                    }
//                    workerOrderInfo.setFkxxs(fkxxs);
//                }
//                List<Map<String, Object>> stocks = (List<Map<String, Object>>) data.get("stock_order");
//                if (CollectionUtils.isNotEmpty(stocks)) {
//                    //辅材信息
//                    List<WorkerOrderInfo.Fcxx> fcxxs = new ArrayList<>();
//                    for (Map<String, Object> stock : stocks) {
//                        WorkerOrderInfo.Fcxx fcxx = new WorkerOrderInfo.Fcxx();
//                        fcxx.setId((Integer)stock.get("id"));
//                        fcxx.setOrderNo((String) stock.get("docnum"));
//                        fcxx.setOperatorWebsit((String) stock.get("websit_name"));
//                        fcxx.setOperatorName((String) stock.get("worker_name"));
//                        fcxx.setPayStatus((String) stock.get("pay_status_text"));
//                        fcxx.setPayTime((String) stock.get("paytime_text"));
//                        fcxx.setAmount((String) stock.get("total_amount"));
//                        fcxx.setRemark((String) stock.get("remark"));
//
//                        List<Map<String, Object>> details = (List<Map<String, Object>>) stock.get("stock_order_goods");
//                        fcxx.setDetails(details);
//                        fcxxs.add(fcxx);
//                    }
//                    workerOrderInfo.setFcxxs(fcxxs);
//                }
//
//                workerOrderInfos.add(workerOrderInfo);
//            }
//        }catch(Exception e){
//            log.error("获取安装工单列表失败",e);
//        }
//        return workerOrderInfos;
//
//    }
//
//
//    /**
//     * 维修工单列表
//     */
//    public List<WorkerOrderInfo> getRepairOrderList(String orderId,String workerOrderNo,List<String> repairWorkerOrderNos) throws Exception {
//
//        List<WorkerOrderInfo> workerOrderInfos = new ArrayList<>();
//        try {
//            Map<String, Object> map = new HashMap<>();
//            if(StringUtils.isNotBlank(orderId)) {
//                map.put("request_order_no", orderId);
//            }
//            if(StringUtils.isNotBlank(workerOrderNo)){
//                map.put("worker_order_no",workerOrderNo);
//            }
//            if(CollectionUtils.isNotEmpty(repairWorkerOrderNos)){
//                map.put("worker_order_no_arr",repairWorkerOrderNos);
//            }
//            Map<String, String> header = new HashMap<>();
//            header.put("Authorization", this.getGongdanToken());
//            JSONObject jsonObject = this.doPhpSevice(map, header, detailRepairUrl);
//            JSONArray datas = (JSONArray) jsonObject.get("data");
//            for (Object o : datas) {
//                JSONObject data = (JSONObject) o;
//                WorkerOrderInfo workerOrderInfo = new WorkerOrderInfo();
//                workerOrderInfo.setWorkerOrder(data.getString("worker_order_no"));
//                workerOrderInfo.setPgid(data.getString("pgid"));
//                workerOrderInfo.setWorkerName(data.getString("woname"));
//                workerOrderInfo.setWorkerPhone(data.getString("wophone"));
//                workerOrderInfo.setInstallNumber(data.getString("after_number"));
//                workerOrderInfo.setInstallName(data.getString("after_wname"));
//                workerOrderInfo.setOrderStateInt(data.getInteger("order_state"));
//                workerOrderInfo.setOrderState(data.getString("order_state"));
//                workerOrderInfo.setOrderReceTime(data.getString("receive_time_text"));
//                workerOrderInfo.setFinishTime(data.getString("finish_time_text"));
//                workerOrderInfo.setServerContent("清洗服务");
//                workerOrderInfo.setBracket(data.getString("bracket"));
//                workerOrderInfo.setReserveTime(data.getString("reserve_datetime_text"));
//                workerOrderInfo.setPipe(data.getString("pipe"));
//                workerOrderInfo.setSwitchFlag(data.getString("switch_flag"));
//                workerOrderInfo.setHighAltitude(data.getString("high_altitude"));
//                workerOrderInfo.setHole(data.getString("hole"));
//                workerOrderInfo.setRemark(data.getString("remark"));
//                workerOrderInfo.setPayTime(data.getString("buy_datetime_text"));
//                workerOrderInfo.setOrderId(data.getString("sales_order_no"));
//                workerOrderInfo.setMainName(data.getString("main_name"));
//                workerOrderInfo.setCreateTime(data.getString("appoint_datetime_text"));
//                //操作类型
//                List<WorkerOrderInfo.Fkxx> fkxxs = new ArrayList<>();
//                List<Map<String, String>> operators = (List<Map<String, String>>) data.get("order_install_operating_log");
//                if (CollectionUtils.isNotEmpty(operators)) {
//                    for (Map<String, String> operator : operators) {
//                        WorkerOrderInfo.Fkxx fkxx = new WorkerOrderInfo.Fkxx();
//                        fkxx.setOperatorType(operator.get("type"));
//                        fkxx.setOperatorContent(operator.get("content"));
//                        fkxx.setLastOperatorTime(operator.get("updatetime"));
//                        fkxx.setOperatorName(operator.get("operator"));
//                        fkxx.setOperatorWebsit(operator.get("operate_websit"));
//                        fkxx.setResult(operator.get("feedback"));
//                        fkxxs.add(fkxx);
//                    }
//                    workerOrderInfo.setFkxxs(fkxxs);
//                }
//                List<Map<String, Object>> stocks = (List<Map<String, Object>>) data.get("stock_order");
//                if (CollectionUtils.isNotEmpty(stocks)) {
//                    //辅材信息
//                    List<WorkerOrderInfo.Fcxx> fcxxs = new ArrayList<>();
//                    for (Map<String, Object> stock : stocks) {
//                        WorkerOrderInfo.Fcxx fcxx = new WorkerOrderInfo.Fcxx();
//                        fcxx.setId((int)stock.get("id"));
//                        fcxx.setOrderNo((String) stock.get("docnum"));
//                        fcxx.setOperatorWebsit((String) stock.get("websit_name"));
//                        fcxx.setOperatorName((String) stock.get("worker_name"));
//                        fcxx.setPayStatus((String) stock.get("pay_status_text"));
//                        fcxx.setPayTime((String) stock.get("paytime_text"));
//                        fcxx.setAmount((String) stock.get("total_amount"));
//                        fcxx.setRemark((String) stock.get("remark"));
//
//                        List<Map<String, Object>> details = (List<Map<String, Object>>) stock.get("stock_order_goods");
//                        fcxx.setDetails(details);
//                        fcxxs.add(fcxx);
//                    }
//                    workerOrderInfo.setFcxxs(fcxxs);
//                }
//
//                workerOrderInfos.add(workerOrderInfo);
//            }
//        }catch(Exception e){
//            log.error("获取维修工单列表失败",e);
//        }
//        return workerOrderInfos;
//
//    }
//
//
//
//
//    private JSONObject doPhpSevice(Map<String,Object> dataContents,Map<String,String> header,String url) throws Exception {
//        return this.doPhpSevice(dataContents,header,url,"POST");
//    }
//
//    /**
//     * 通用请求
//     * @param dataContents
//     * @param header
//     * @param url
//     * @return
//     * @throws Exception
//     */
//    private JSONObject doPhpSevice(Map<String,Object> dataContents,Map<String,String> header,String url,String method) throws Exception {
//        String ivValue = get16Random();
//        String iv = Base64Util.encode(ivValue.getBytes());
//
//        //dataContents.put("password",password);
//        String dataJson = JSONObject.toJSONString(dataContents);
//        log.info("【请求工单服务】request...：dataContents:{},iv:{},client_name:{}",dataJson,ivValue,clientName);
//        byte[] bytes = AESUtils.encryptAES(dataJson,ivValue,key).getBytes();
//        String encode = Base64Util.encode(bytes);
//
//        Map<String,String> map = new HashMap<>();
//        map.put("client_name",clientName);
//        map.put("data_contents",encode);
//        map.put("iv",iv);
//
//        log.info("【请求工单服务，加密】request...：{}",JSONObject.toJSONString(map));
//        String s = "";
//        if(StringUtils.equals(method,"POST")) {
//            s = HttpUtils.requestPostForm(url, map, header);
//        }else{
//            s = HttpUtils.requestGet(url, map, header);
//        }
//        log.info("【请求工单服务】response...：{}",s);
//        JSONObject jsonObject = JSONObject.parseObject(s);
//        if(jsonObject == null || !jsonObject.get("code").toString().equals("1")){
//            throw new RemoteServiceException("对接工单系统失败,请联系相关开发人员");
//        }
//        return jsonObject;
//    }
//
//
//
//
//    public static String get16Random(){
//        //随机生成一位整数
//        int random = (int) (Math.random()*9+1);
//        String valueOf = String.valueOf(random);
//        //生成uuid的hashCode值
//        int hashCode = UUID.randomUUID().toString().hashCode();
//        //可能为负数
//        if(hashCode<0){
//            hashCode = -hashCode;
//        }
//        String value = valueOf + String.format("%015d", hashCode);
//        return value;
//    }
//
//
//    public String checkSign(String data,String iv,String lKey){
//        String s = "";
//        log.info("【工单进度通知】content:{},iv:{},lKey:{}",data,iv,lKey);
//        try{
//            String rIv = new String(Base64Util.decode(iv));
//            //String data = new String(Base64Util.decode(content));
//            if(StringUtils.isBlank(lKey)){
//                lKey = key;
//            }
//            s = AESUtils.decryptAES(data, rIv, lKey);
//        }catch (Exception e){
//            throw new RemoteServiceException("解密失败");
//        }
//        if(StringUtils.isBlank(s)){
//            throw new RemoteServiceException("解密失败");
//        }
//        return s;
//    }
//
//
//
//
//
//}
