package com.sifang.modules.customer.controller;

import com.google.common.collect.ImmutableList;
import com.google.gson.Gson;
import com.jfinal.kit.HashKit;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.monitor.ginlong.GinlongApiService;
import com.sifang.modules.monitor.ginlong.dto.addstation.AddStationReq;
import com.sifang.modules.monitor.ginlong.dto.inverterday.GetInverterDayReq;
import com.sifang.modules.sys.common.global.Global;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.insurance.IRet;
import com.sifang.modules.sys.util.insurance.InsuranceApiService;
import com.sifang.modules.sys.util.insurance.InsuranceBizService;
import com.sifang.modules.sys.util.insurance.InsuranceConst;
import com.sifang.modules.sys.util.insurance.form.InsuranceConfig;
import com.sifang.modules.sys.util.insurance.form.endorse.EndorseInsured;
import com.sifang.modules.sys.util.insurance.form.endorse.EndorseReq;
import com.sifang.modules.sys.util.insurance.form.endorsequery.EndorseQueryReq;
import com.sifang.modules.sys.util.insurance.form.insuresubmit.*;
import com.sifang.modules.sys.util.insurance.form.orderquery.OrderQueryReq;
import com.sifang.modules.sys.util.insurance.form.ordersubmit.*;
import com.sifang.modules.sys.util.insurance.form.upload.FileUploadReq;
import com.sifang.modules.sys.util.insurance.form.upload.FileUploadResp;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("${adminPath}/main/ins")
@RestController
public class InsuranceTestController {

    @Autowired
    InsuranceApiService apiService;

    @Autowired
    InsuranceBizService bizService;

    @Autowired
    CustomerEntryDao customerEntryDao;

    @Autowired
    GinlongApiService ginlongApiService;


    @RequestMapping(value = "inverterDay")
    public Object inverterDay() throws IOException {
        GetInverterDayReq req = new GetInverterDayReq();
        // 对应电站id:  1299184320438796693
//        req.setId("1299184088035530778");
        req.setId("1299184088035530844"); // sn: 2016010233070199, inverterId: 1299184088035530844
        req.setMoney("CNY");
        req.setTime("2024-02-04");
        req.setTimeZone(8);
        return ginlongApiService.inverterDay(req);
    }

    /**
     * B0120 NMI exist
     * B0122 NMI Invalid Forma
     */
    @RequestMapping(value = "addStation")
    public Object addStation(@RequestBody AddStationReq req) throws IOException {
        return ginlongApiService.addStation(req);
    }

    @RequestMapping("/order/submit1")
    public Object orderSubmit1(@RequestParam String id) throws IOException {
        bizService.push(customerEntryDao.get(id), null, null, null,"0");
        return "push ok";
    }

    /**
     * {
     *     "code": "200000",
     *     "msg": "经纪系统:已存在该单,保单状态不支持重新下单",
     *     "success": false,
     *     "data": {
     *         "orderNo": "SHNH0118FD9999999999",
     *         "requestNo": "cbf181b7a65248f797c4fc948b3eee3d"
     *     }
     * }
     */
    @RequestMapping("/order/submit")
    public Object orderSubmit() throws IOException {
        String requestNo = IdGen.uuid();
        String channelCode = Global.getConfig("insurance.channelCode");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, 1);

        OrderSubmitReq obj = new OrderSubmitReq();

        BaseInfo baseInfo = new BaseInfo();
        baseInfo.setStartDate(df.format(c.getTime()));
        c.add(Calendar.YEAR, 1);
        baseInfo.setEndDate(df.format(c.getTime()));
        baseInfo.setSumAmount("100");
        baseInfo.setSumQuantity("1");
        baseInfo.setRemark("合肥思方网聚科技发展有限公司");
        List<String> codeList = new ArrayList<>();
        codeList.add("3216");
        codeList.add("3132");
        codeList.add("3136");
        baseInfo.setChoose(codeList);
        obj.setBaseInfo(baseInfo);


//        insuredFlag
//        identifyNumber
//        insuredName
//        identifyType
//        address

        Insured insured1 = new Insured();
        insured1.setInsuredFlag(InsuranceConst.INSURE_FLAG_INSURED); // 被保险人
        insured1.setIdentifyNumber("91340104MA2T24AE73");
        insured1.setInsuredName("合肥思方网聚科技发展有限公司");
        insured1.setIdentifyType(InsuranceConst.ID_TYPE_BIZ_LICENSE);
        insured1.setInsuredType(InsuranceConst.INSURE_TYPE_ENTERPRISE); // 单位
        insured1.setMobile("18656153956");
        insured1.setInsuredNature(InsuranceConst.INSURE_NATURE_LEGAL_PERSON); // 法人
        insured1.setEmail(null);
        insured1.setIsInsuredRelation(InsuranceConst.INSURE_REL_OTHER); // 其他

        Insured insured2 = new Insured();
        insured2.setInsuredFlag(InsuranceConst.INSURE_FLAG_INSURE_PAYER); // 投保人
        insured2.setIdentifyNumber("91340104MA2T0QDQ33(1-1)");
        insured2.setInsuredName("安徽思方众联网络科技有限公司");
        insured2.setIdentifyType(InsuranceConst.ID_TYPE_BIZ_LICENSE);
        insured2.setInsuredType(InsuranceConst.INSURE_TYPE_ENTERPRISE); // 单位
        insured2.setMobile("18656153957");
        insured2.setInsuredNature(InsuranceConst.INSURE_NATURE_LEGAL_PERSON); // 法人
        insured2.setEmail(null);
        insured2.setIsInsuredRelation(InsuranceConst.INSURE_REL_SELF); // 其他
        obj.setInsuredList(Arrays.asList(insured1, insured2));

        HouseDetails details = new HouseDetails();
        details.setProvince("安徽省");
        details.setCity("合肥市");
        details.setCounty("蜀山区");
        details.setAddress("正大广场");
        obj.setHouseDetailsList(Collections.singletonList(details));

//        FileUploadReq req = new FileUploadReq();
//        req.setRequestNo(IdGen.uuid());
//        req.setChannelCode(channelCode);
//        File file = new File("/home/gaols/Pictures/cat.jpg");
//        req.setFileName(file.getName());
//        byte[] bytes = FileUtils.readFileToByteArray(file);
//        req.setFileBase64(Base64.getEncoder().encodeToString(bytes));
//        req.setSign(HashKit.md5(req.getRequestNo() + req.getChannelCode() + Global.getConfig("insurance.key")));

        FileUploadReq req1 = createReq("/home/gaols/Codes/share/nh/zz1.jpg");
        FileUploadReq req2 = createReq("/home/gaols/Codes/share/nh/zz2.jpg");
        IRet<FileUploadResp> fileRet1 = apiService.fileUpload(req1);
        IRet<FileUploadResp> fileRet2 = apiService.fileUpload(req2);
        FileInfo fileInfo1 = new FileInfo();
        fileInfo1.setFileId(fileRet1.getData().getFileId());
        fileInfo1.setFileName("zz1.jpg");
        FileInfo fileInfo2 = new FileInfo();
        fileInfo2.setFileId(fileRet2.getData().getFileId());
        fileInfo2.setFileName("zz2.jpg");
        obj.setFileInfos(Arrays.asList(fileInfo1, fileInfo2));

        obj.setOrderNo(channelCode+"7777777777777");
        obj.setChannelCode(channelCode);
        obj.setRequestNo(requestNo);
        obj.setSign(HashKit.md5(obj.getRequestNo() + channelCode + Global.getConfig("insurance.key")));
        obj.setItemNo("23111409494444"); // 电站编号
        obj.setProductPlan(Global.getConfig("insurance.productPlan"));
        return apiService.orderSubmit(obj);
    }

    @RequestMapping("/projectInsure/submit")
    public Object projectInsure() {
        String requestNo = IdGen.uuid();
        String channelCode = Global.getConfig("insureSubmit.channelCode");
        InsureSubmitReq req = new InsureSubmitReq();
        req.setRequestNo(requestNo);
        req.setChannelCode(channelCode);
        req.setSign(HashKit.md5(req.getRequestNo() + channelCode + Global.getConfig("insureSubmit.key")));
        req.setProductPlan(Global.getConfig("insureSubmit.productPlan"));
        String orderNo = channelCode + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        req.setOrderNo(orderNo);
//        req.setItemNo("23111409494444");// 电站编号
        //基本信息
        ProjectInsureBaseInfo baseInfo = new ProjectInsureBaseInfo();
        baseInfo.setStartDate("2025-01-01 00:00:00");
        baseInfo.setInuredDuration("366");
        baseInfo.setSumAmount("1000000");
        baseInfo.setSumQuantity("1");
        req.setBaseInfo(baseInfo);
        Map<String, Object> extraInfo = new HashMap<>();
        //投保人信息
        List<PolicyholderInfo> list1 = new ArrayList<>();
        PolicyholderInfo info1 = new PolicyholderInfo();
        info1.setInsuredType(InsuranceConst.INSURE_TYPE_ENTERPRISE); // 单位
        info1.setMobile("18656153957");
        info1.setIdentifyType(InsuranceConst.ID_TYPE_BIZ_LICENSE);
        info1.setIdentifyNumber("91340104MA2T0QDQ33(1-1)");
        info1.setInsuredNature(InsuranceConst.INSURE_NATURE_LEGAL_PERSON); // 法人
        info1.setInsuredName("安徽思方众联网络科技有限公司");
        info1.setEmail(null);
        list1.add(info1);
        extraInfo.put("10", list1);
        //被保人信息
        List<InsuredInfo> list2 = new ArrayList<>();
        InsuredInfo insuredInfo = new InsuredInfo();
        insuredInfo.setInsuredType(InsuranceConst.INSURE_TYPE_ENTERPRISE); // 单位
        insuredInfo.setMobile("18656153957");
        insuredInfo.setIdentifyType(InsuranceConst.ID_TYPE_BIZ_LICENSE);
        insuredInfo.setIsInsuredRelation("00");
        insuredInfo.setIdentifyNumber("91340104MA2T0QDQ33(1-1)");
        insuredInfo.setInsuredNature(InsuranceConst.INSURE_NATURE_LEGAL_PERSON); // 法人
        insuredInfo.setInsuredName("安徽思方众联网络科技有限公司");
        insuredInfo.setEmail(null);
        list2.add(insuredInfo);
        extraInfo.put("20", list2);
        //其他信息
        List<OtherInfo> list3 = new ArrayList<>();
        OtherInfo otherInfo = new OtherInfo();
        otherInfo.setItemNo("23111409494444");//电站编码
        otherInfo.setEntranceTime("2024-11-13 14:08:05");//进件时间
        otherInfo.setProjectName("测试001");//工程名称
        otherInfo.setProjectAddress("安徽省合肥市蜀山区正大广场");//工程地址
        otherInfo.setProjectStatus("1");//工程状态 下单传0  开工传1  完工传2
//        otherInfo.setDeliveryTime("2024-11-13 14:08");//发货时间
//        otherInfo.setReceivingTime("2024-12-13 11:08");//收货时间
        otherInfo.setOperationTime("2024-11-13 11:08:20");//开工时间
//        otherInfo.setItemAddress("安徽省合肥市蜀山区正大广场");//项目地址
        otherInfo.setContractCost("");//EPC合同造价
        otherInfo.setCompleteTime("2025-01-05 11:08:02");//完工时间
        list3.add(otherInfo);
        extraInfo.put("40",list3);
        //发包人信息
//        List<PolicyholderInfo> list4 = new ArrayList<>();
//        PolicyholderInfo info2 = new PolicyholderInfo();
//        info2.setInsuredType(InsuranceConst.INSURE_TYPE_ENTERPRISE); // 单位
//        info2.setMobile("18656153956");
//        info2.setIdentifyType("01");
//        info2.setIdentifyNumber("340826200002011250");
//        info2.setInsuredNature(InsuranceConst.INSURE_NATURE_PERSON); // 自然人
//        info2.setInsuredName("张三");
//        info2.setEmail(null);
//        list4.add(info2);
//        extraInfo.put("110", list4);
//        //承包人信息
//        List<PolicyholderInfo> list5 = new ArrayList<>();
//        PolicyholderInfo info3 = new PolicyholderInfo();
//        info3.setInsuredType(InsuranceConst.INSURE_TYPE_ENTERPRISE); // 单位
//        info3.setMobile("186561539575");
//        info3.setIdentifyType(InsuranceConst.ID_TYPE_BIZ_LICENSE);
//        info3.setIdentifyNumber("91340104MA2T0QDQ33(1-1)");
//        info3.setInsuredNature(InsuranceConst.INSURE_NATURE_LEGAL_PERSON); // 法人
//        info3.setInsuredName("安徽思方众联网络科技有限公司");
//        info3.setEmail(null);
//        list5.add(info3);
//        extraInfo.put("120", list5);
        req.setExtraInfo(extraInfo);
        System.out.println("insure submit : "+new Gson().toJson(req));
        return apiService.insureSubmit(req);
    }


    @RequestMapping("/endorse/submit")
    public Object endorseSubmit(@RequestBody EndorseReq req) {
        String channelCode = Global.getConfig("insurance.channelCode");
        req.setRequestNo(IdGen.uuid());
        req.setChannelCode(channelCode);
        req.setSign(HashKit.md5(req.getRequestNo() + channelCode + Global.getConfig("insurance.key")));
        req.setEndorseType("1|2|5");
        req.setPolicyNo("ASHZ10702424EAAA79UP");

        EndorseInsured insured1 = new EndorseInsured();
        insured1.setIdentifyNumber("91340104MA2T24AE73");
        insured1.setInsuredFlag(InsuranceConst.INSURE_FLAG_INSURED);
        insured1.setInsuredName("合肥思方网聚科技发展有限公司");
        insured1.setIdentifyType(InsuranceConst.ID_TYPE_BIZ_LICENSE);
        insured1.setAddress(null);

//        EndorseInsured insured2 = new EndorseInsured();
//        insured2.setIdentifyNumber("91340104MA2T24AE73");
//        insured2.setInsuredFlag(InsuranceConst.INSURE_FLAG_INSURE_PAYER);
//        insured2.setInsuredName("91340104MA2T0QDQ33(1-1)");
//        insured2.setIdentifyType(InsuranceConst.ID_TYPE_BIZ_LICENSE);
//        insured2.setAddress(null);

//        req.setInsuredList(ImmutableList.of(insured1, insured2));
        req.setInsuredList(ImmutableList.of(insured1));
        req.setAddressName("安徽省经开区");
        req.setRemark("合肥思方网聚科技发展有限公司");
        return apiService.endorse(req);
    }

    @RequestMapping("/endorse/query")
    public Object endorseQuery(@RequestBody EndorseQueryReq req) {
        req.setCurrent(1);
        String channelCode = Global.getConfig("insurance.channelCode");
        req.setRequestNo(IdGen.uuid());
        req.setChannelCode(channelCode);
        req.setSign(HashKit.md5(req.getRequestNo() + req.getChannelCode() + Global.getConfig("insurance.key")));
        return apiService.endorseQuery(req);
    }

    @RequestMapping("/order/query")
    public Object orderQuery(@RequestBody OrderQueryReq req) {
        String channelCode = Global.getConfig("insurance.channelCode");
        req.setCurrent(1);
        req.setRequestNo(IdGen.uuid());
        req.setChannelCode(channelCode);
        req.setSign(HashKit.md5(req.getRequestNo() + req.getChannelCode() + Global.getConfig("insurance.key")));
        return apiService.orderQuery(req);
    }

    @RequestMapping("file/upload")
    public Object upload() throws IOException {
//        FileUploadReq req = new FileUploadReq();
//        req.setRequestNo(IdGen.uuid());
//        req.setChannelCode(Global.getConfig("insurance.channelCode"));
//        File file = new File("/home/gaols/Pictures/cat.jpg");
//        req.setFileName(file.getName());
//        byte[] bytes = FileUtils.readFileToByteArray(file);
//        req.setFileBase64(Base64.getEncoder().encodeToString(bytes));
//        //=MD5(requestNo+channelCode+key)
//        req.setSign(HashKit.md5(req.getRequestNo() + req.getChannelCode() + Global.getConfig("insurance.key")));
        FileUploadReq req = createReq("/home/gaols/Pictures/cat.jpg");
        return apiService.fileUpload(req);
    }

    @RequestMapping("/order/cancel")
    public Object orderCancel(String requestNo) throws IOException {
        InsuranceConfig config = InsuranceConfig.load();
//        OrderCancelReq req = new OrderCancelReq();
//        req.setRequestNo("2c96190d8e7a403d018e7e71daaa009b");
//        req.setChannelCode(config.getChannelCode());
//        req.setSign(HashKit.md5(req.getRequestNo() + req.getChannelCode() + config.getKey()));
//        req.setPolicyNo("ASHZF0202424EAAALP5Z");
//        req.setApplicant("上海能辉科技股份有限公司");
//        req.setInsured("广州越秀融资租赁有限公司及广州越晖光伏科技有限公司");
//        req.setReason("正式环境测试");
//        apiService.orderCancel(req);

        String sign = HashKit.md5(requestNo + config.getChannelCode() + Global.getConfig("insurance.key"));
        System.out.println("sign is:" + sign);

//        OrderCancelReq req1 = new OrderCancelReq();
//        req1.setRequestNo("2c96190d8e7a403d018e7a4366c20005");
//        req1.setChannelCode(config.getChannelCode());
//        req1.setSign(HashKit.md5(req1.getRequestNo() + req1.getChannelCode() + Global.getConfig("insurance.key")));
//        req1.setPolicyNo("ASHZF0202424EAAALPQ9");
//        req1.setApplicant("上海能辉科技股份有限公司");
//        req1.setInsured("广州越秀融资租赁有限公司及广州越晖光伏科技有限公司");
//        req1.setReason("正式环境测试");
//        apiService.orderCancel(req1);
        return "ok";
    }

    private static FileUploadReq createReq(String path) throws IOException {
        FileUploadReq req = new FileUploadReq();
        req.setRequestNo(IdGen.uuid());
        req.setChannelCode(Global.getConfig("insurance.channelCode"));
        File file = new File(path);
        req.setFileName(file.getName());
        byte[] bytes = FileUtils.readFileToByteArray(file);
        req.setFileBase64(Base64.getEncoder().encodeToString(bytes));
        //=MD5(requestNo+channelCode+key)
        req.setSign(HashKit.md5(req.getRequestNo() + req.getChannelCode() + Global.getConfig("insurance.key")));
        return req;
    }

}
