package com.ghy.web.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.ghy.common.utils.security.Md5Utils;
import com.ghy.customer.domain.CustomerAddress;
import com.ghy.customer.service.CustomerAddressService;
import com.ghy.order.domain.OrderDetail;
import com.ghy.order.domain.OrderDetailInsuranceUser;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.service.IOrderDetailInsuranceUserService;
import com.ghy.order.service.OrderDetailService;
import com.ghy.order.service.OrderMasterService;
import com.ghy.web.pojo.vo.CertNoTwoElementReq;
import com.ghy.web.pojo.vo.InsuranceOrderEditReq;
import com.ghy.web.pojo.vo.InsuranceOrderReq;
import com.ghy.web.service.InsuranceService;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.domain.WorkerCertification;
import com.ghy.worker.service.IWorkerCertificationService;
import com.ghy.worker.service.WorkerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class InsuranceServiceImpl implements InsuranceService {

    private final static String Key = "96ndsd26k25jm";

    private final static String baseUrl = "https://pre-hbhp-xianding.hzins.com/api/external/";

    @Autowired
    private OrderMasterService orderMasterService;

    @Autowired
    private CustomerAddressService customerAddressService;

    @Autowired
    private WorkerService workerService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private IOrderDetailInsuranceUserService orderDetailInsuranceUserService;

    @Override
    public void orderInsurance(String orderCode) throws Exception{
        InsuranceOrderReq req = new InsuranceOrderReq();
        OrderMaster master = orderMasterService.selectByCode(orderCode);
        if(master.getInsuranceId() == null){
            return;
        }
        req.setOrderNumber(master.getCode());
        req.setRequestNo(master.getCode() + System.currentTimeMillis());
        req.setSign(Md5Utils.hash(req.getRequestNo() + req.getChannelCode() + Key));
        // 查询客户地址信息
        CustomerAddress customerAddress = customerAddressService.selectByCustomerAddressId(master.getAddressId());
        req.setCustomerAddress(customerAddress.getAddress());
        req.setCustomerPhone(customerAddress.getPhone());
        // 查师傅信息
        Worker worker = workerService.selectById(master.getWorkerId());
        CertNoTwoElementReq certNoTwoElementReq = JSONUtil.toBean(worker.getRemark(), CertNoTwoElementReq.class);
        req.setWorkerID(certNoTwoElementReq.getCertNo());
        req.setWorkName(certNoTwoElementReq.getCertName());
        req.setOrderStartat(DateUtil.format(DateUtil.offset(new Date(), DateField.SECOND, 30), DatePattern.NORM_DATETIME_PATTERN));
        req.setOrderEndat(DateUtil.format(DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, 30),DatePattern.NORM_DATETIME_PATTERN));
        log.info("调用保险请求url:{},内容:{}", baseUrl+"/platInterface/order", JSONUtil.toJsonStr(req));
        String result = HttpUtil.post(baseUrl+"/platInterface/order", JSONUtil.toJsonStr(req));
        log.info("调用保险返回内容:{}", result);
        if(!"1".equals(JSONObject.parseObject(result).getString("code")) && !JSONObject.parseObject(result).getString("msg").contains("已存在该工单")){
            throw new Exception(JSONObject.parseObject(result).getString("msg"));
        }
    }

    @Override
    public void editInsurance(OrderDetailInsuranceUser orderDetailInsuranceUser) throws Exception {
        // 查询子单
        OrderDetail detail = orderDetailService.selectById(orderDetailInsuranceUser.getOrderDetailId());
        // 查询主单
        OrderMaster master = orderMasterService.selectById(detail.getOrderMasterId());
        // 查师傅信息
        Worker worker = workerService.selectById(master.getWorkerId());
        CertNoTwoElementReq certNoTwoElementReq = JSONUtil.toBean(worker.getRemark(), CertNoTwoElementReq.class);
        // 查询主单下的所有子单
        List<OrderDetail> detailList = orderDetailService.selectByOrderMasterId(detail.getOrderMasterId());
        StringBuilder workerName = new StringBuilder();
        StringBuilder workerId = new StringBuilder();
        // 拼上主单信息
        workerName.append(certNoTwoElementReq.getCertName());
        workerId.append(certNoTwoElementReq.getCertNo());
        detailList.forEach(model->{
            OrderDetailInsuranceUser param = new OrderDetailInsuranceUser();
            param.setOrderDetailId(model.getId());
            List<OrderDetailInsuranceUser> users = orderDetailInsuranceUserService.selectOrderDetailInsuranceUserList(param);
            if(!CollectionUtils.isEmpty(users)){
                users.forEach(user->{
                    workerName.append(",").append(user.getName());
                    workerId.append(",").append(user.getIdCardNum());
                });
            }
        });
        // 再拼上 现在要加入的师傅的信息
        workerName.append(",").append(orderDetailInsuranceUser.getName());
        workerId.append(",").append(orderDetailInsuranceUser.getIdCardNum());
        InsuranceOrderEditReq editReq = new InsuranceOrderEditReq();
        editReq.setOrderNumber(master.getCode());
        editReq.setRequestNo(master.getCode() + System.currentTimeMillis());
        editReq.setSign(Md5Utils.hash(editReq.getRequestNo() + editReq.getChannelCode() + Key));
        editReq.setOrderNumber(master.getCode());
        editReq.setWorkName(workerName.toString());
        editReq.setWorkerID(workerId.toString());
        log.info("调用保险请求url:{},内容:{}", baseUrl+"/platInterface/updateOrder", JSONUtil.toJsonStr(editReq));
        String result = HttpUtil.post(baseUrl+"/platInterface/updateOrder", JSONUtil.toJsonStr(editReq));
        log.info("调用保险返回内容:{}", result);
        if(!"1".equals(JSONObject.parseObject(result).getString("code"))){
            throw new Exception(JSONObject.parseObject(result).getString("msg"));
        }
    }

    @Override
    public void clockInsurance(Long orderDetailId) throws Exception {
        // 查询子单
        OrderDetail detail = orderDetailService.selectById(orderDetailId);
        // 查询主单
        OrderMaster master = orderMasterService.selectById(detail.getOrderMasterId());
        if(master.getInsuranceId() != null){
            InsuranceOrderEditReq editReq = new InsuranceOrderEditReq();
            editReq.setOrderNumber(master.getCode());
            editReq.setRequestNo(master.getCode() + System.currentTimeMillis());
            editReq.setSign(Md5Utils.hash(editReq.getRequestNo() + editReq.getChannelCode() + Key));
            editReq.setOrderNumber(master.getCode());
            editReq.setShangmenTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
            editReq.setShangmenNum("1");
            log.info("调用保险请求url:{},内容:{}", baseUrl+"/platInterface/service", JSONUtil.toJsonStr(editReq));
            String result = HttpUtil.post(baseUrl+"/platInterface/service", JSONUtil.toJsonStr(editReq));
            log.info("调用保险返回内容:{}", result);
            if(!"1".equals(JSONObject.parseObject(result).getString("code"))){
                throw new Exception(JSONObject.parseObject(result).getString("msg"));
            }
        }
    }
}
