/**
 * Project Name:tuia-youtui-web<br>
 * File Name:InsuranceResponseFactory.java<br>
 * Package Name:com.duiba.tuia.youtui.web.biz.land.param<br>
 * Date:2017年4月19日下午3:12:47<br>
 * Copyright (c) 2017, duiba.com.cn All Rights Reserved.<br>
 */
package com.duiba.tuia.youtui.web.biz.land.param;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.duiba.tuia.youtui.web.constant.LandChannel;
import com.duiba.tuia.youtui.web.model.rsp.InsuranceResultRsp;


/**
 * ClassName: InsuranceResponseFactory <br/>
 * Function: 保险返回格式生成s. <br/>
 * Reason: . <br/>
 * date: 2017年4月19日 下午3:12:47 <br/>
 *
 * @author wubo
 * @version
 * @since JDK 1.7
 */
@Component
public class InsuranceResponseFactory {

    public InsuranceResultRsp getInsuranceResult(String channel, String response) {
        switch (channel) {
            case LandChannel.HEINIU:
                return getInsuranceResultFromHeiniu(response);
            case LandChannel.NEWTANK:
                return getInsuranceResultFromNewTank(response);
            default:
                return null;
        }
    }

    private InsuranceResultRsp getInsuranceResultFromHeiniu(String response) {
        InsuranceResultRsp rs = new InsuranceResultRsp();
        JSONObject json = JSONObject.parseObject(response);
        JSONObject data = json.getJSONObject("data");
        rs.setStatus(json.getString("status"));
        rs.setDesc(json.getString("msg"));
        rs.setInsuredOrder(data.getString("policy_no"));
        rs.setInsuredUrl(data.getString("url"));
        rs.setPolicyName(data.getString("policy_name"));
        rs.setCompanyName(data.getString("company_name"));
        
        return rs;
    }
    
    private InsuranceResultRsp getInsuranceResultFromNewTank(String response){
        InsuranceResultRsp rs = new InsuranceResultRsp();
        JSONObject json = JSONObject.parseObject(response);
        if(json!=null){
            rs.setStatus(json.getString("status"));
            rs.setDesc(json.getString("message"));
            rs.setInsuredOrder(json.getString("policyNo"));
            rs.setInsuredUrl(json.getString("resultUrl"));
            rs.setUid(json.getString("uid"));

            //业务逻辑：返回状态码是成功的保险名称与产品名称
            // status：0 表示成功
            JSONArray details =  json.getJSONArray("detailMessage");
            if (details != null && details.size() > 0) {
                int size = details.size();
                for (int i = 0; i < size; i++) {
                    JSONObject detail = details.getJSONObject(i);
                    if ("0".equals(detail.getString("status"))) {
                        rs.setPolicyName(detail.getString("productName"));
                        rs.setCompanyName(detail.getString("companyName"));
                        break;
                    }
                }


            }
        }

        
        return rs;
    }

}
