package com.glxp.mipsdl.controller;

import cn.hsa.zephyr.apisdk.ZephyrMedicalClient;
import cn.hsa.zephyr.apisdk.internal.exception.ZephyrApiException;
import cn.hsa.zephyr.apisdk.internal.util.encrypt.EncryptionModeEnum;
import cn.hsa.zephyr.apisdk.internal.util.encrypt.SignTypeEnum;
import cn.hsa.zephyr.apisdk.request.ZephyrMedicalRequest;
import cn.hsa.zephyr.apisdk.response.ChsMedicalResponse;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.glxp.mipsdl.dao.basic.BasicUdirelDao;
import com.glxp.mipsdl.entity.basic.BasicUdirelEntity;
import com.glxp.mipsdl.entity.ctqyy.VInsurNationGoodsPhysic;
import com.glxp.mipsdl.entity.inout.CollectOrderBizResponse;
import com.glxp.mipsdl.entity.inout.IoCollectOrder;
import com.glxp.mipsdl.req.post.PostCollectOrderRequest;
import com.glxp.mipsdl.req.yb.*;
import com.glxp.mipsdl.res.BaseResponse;
import com.glxp.mipsdl.service.yb.YbClient;
import com.glxp.mipsdl.thirddao.ctqyy.VInsurNationGoodsPhysicMapper;
import com.glxp.mipsdl.util.ResultVOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
public class YbApiController {
    @Resource
    YbClient ybClient;

    /**
     * 【1201】医药机构信息获取
     *
     * @param baseYljg1201Request
     * @return
     */
    @PostMapping("/udiwms/erp/yb/1201")
    public BaseResponse getYb1201(@RequestBody BaseYljg1201Request baseYljg1201Request) {
        String jsonStr = JSONUtil.toJsonStr(baseYljg1201Request);
        log.error("【1201】医药机构信息获取请求参数：" + jsonStr);
        JSONObject dataJson = JSONObject.parseObject(jsonStr);
        return ResultVOUtils.success(ybClient.ybPost("1201", dataJson));
    }


    /**
     * 通用字典下载接口
     */
    @PostMapping("/udiwms/erp/yb/dict")
    public BaseResponse getYb1301(@RequestBody DictRequest dictRequest) {
        String jsonStr = JSONUtil.toJsonStr(dictRequest.getData());
        log.error("【1301】通用字典下载接口请求参数：" + jsonStr);
        JSONObject dataJson = JSONObject.parseObject(jsonStr);
        return ResultVOUtils.success(ybClient.ybPost(dictRequest.getApiCode(), dataJson));
    }


    /**
     * 单据试上传
     */
    @PostMapping("/udiwms/erp/yb/order/upload/test")
    public BaseResponse testUpload(@RequestBody DictRequest dictRequest) {
        String jsonStr = JSONUtil.toJsonStr(dictRequest.getOrder());
        JSONObject dataJson = JSONObject.parseObject(jsonStr);
//        JSONArray jsonObject = dataJson.getJSONArray("selinfoDetail");
        return ResultVOUtils.success(ybClient.ybPost(dictRequest.getApiCode(), dataJson));
    }


    @PostMapping("/udiwms/erp/yb/sign")
    public BaseResponse signNo(@RequestBody BaseYbRequest baseYbRequest) {
        SignRequest signRequest = baseYbRequest.getSignIn();
//        signRequest.setCurrenttime(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN));
//        String password = signRequest.getCurrenttime() + signRequest.getPassword();
//        // 该字符串通过32位的MD5算法加密（字母大写）生成密文86B31EDFE60F7BA28765DF860D56B7B2
//        password = SecureUtil.md5(password).toUpperCase();
//        signRequest.setPassword(password);
        String jsonStr = JSONUtil.toJsonStr(baseYbRequest);
        log.error("【9001】医药机构信息获取请求参数：" + jsonStr);
        JSONObject dataJson = JSONObject.parseObject(jsonStr);
        return ResultVOUtils.success(ybClient.ybPost("9001", dataJson));
    }

    @PostMapping("/udiwms/erp/yb/test")
    public ChsMedicalResponse test() {
        String url = "http://api.fj.hsip.gov.cn/sias/base/api/gafe/rest";
        String appId = "H35062500006";
        String appSecret = "2156B331D45F53B02BFF05C3942E60D7";
        String infno = "9001";
        SignTypeEnum signType = SignTypeEnum.SM3;
        String signKey = "C9C9F54F74BD35DE5242885762E99E8E";
        EncryptionModeEnum encType = EncryptionModeEnum.SM4;
        String encKey = "D9C9F54F74BD35DE5242885762E99E8E";
        try {
            ZephyrMedicalClient client = new ZephyrMedicalClient(url, infno, appId, appSecret, signType, signKey, encType, encKey);
            ZephyrMedicalRequest req = new ZephyrMedicalRequest();
            req.setMsgid("H35062500006202405301706277464");
            req.setMdtrtAreaAdmdvs("350625");
            req.setInsuplcAdmdvs("350625");
            req.setOpter("测试");
            req.setOpterType("1");
            req.setOpterName("测试");
            req.setInfTime("2024-05-30 17:17:11");
            req.setFixmedinsCode("H35062500006");
            req.setFixmedinsName("漳州市长泰区医院");
            JSONObject data = new JSONObject();
            JSONObject params = new JSONObject();
            data.put("opter_no", "178823");
            data.put("opterNo", "178823");
            data.put("ip", "10.3.53.4");
            data.put("mac", "40-A5-EF-22-93-A9");
            params.put("signIn", data);
            req.setInput(params);
            ChsMedicalResponse resp = client.execute(req);
            log.error(resp.getInfCode());//错误码
            log.error(resp.getErrMsg()); // 错误信息
            log.error(resp.getOutput()); //回参对象
            return resp;
        } catch (ZephyrApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Resource
    VInsurNationGoodsPhysicMapper goodsPhysicMapper;
    @Resource
    private BasicUdirelDao basicUdirelDao;

    /**
     * 销售提交
     */
    @PostMapping("/udiwms/erp/yb/postOrder")
    public BaseResponse postOrder(@RequestBody PostCollectOrderRequest postCollectOrderRequest) {


        List<IoCollectOrder> collectOrderList = postCollectOrderRequest.getCollectOrderList();

        if (CollUtil.isNotEmpty(collectOrderList)) {
            for (IoCollectOrder ioCollectOrder : collectOrderList) {
                //摆药流水号
                String stoout_no = ioCollectOrder.getBackupOrderRemark1();
                List<VInsurNationGoodsPhysic> vInsurNationGoodsPhysics = goodsPhysicMapper.selectList(new LambdaQueryWrapper<VInsurNationGoodsPhysic>().eq(VInsurNationGoodsPhysic::getSTOOUT_NO, stoout_no));

                if (CollUtil.isNotEmpty(vInsurNationGoodsPhysics)) {
                    List<CollectOrderBizResponse> collectOrderBizResponseList = ioCollectOrder.getCollectOrderBizResponseList();
                    List<Xsck3505Request> xsck3505Requests = new ArrayList<>();
                    for (CollectOrderBizResponse collectOrderBizResponse : collectOrderBizResponseList) {
                        BasicUdirelEntity basicUdirelEntity = basicUdirelDao.selectById(collectOrderBizResponse.getRelId());
                        String itemCode = basicUdirelEntity.getMainId();
                        for (VInsurNationGoodsPhysic vInsurNationGoodsPhysic : vInsurNationGoodsPhysics) {
                            if (vInsurNationGoodsPhysic.getFIXMEDINS_HILIST_ID().equals(itemCode)) {
                                String[] codes = collectOrderBizResponse.getFinishUdiCode().split(",");
                                List<DrugInfoRequest> drugTraceList = new ArrayList<>();
                                // 遍历fruits数组
                                for (String code : codes) {
                                    DrugInfoRequest request = new DrugInfoRequest();
                                    request.setDrug_trac_codg(code);
                                    drugTraceList.add(request);
                                }
                                Xsck3505Request xsck3505Request = Xsck3505Request.builder()
                                        .med_list_codg(vInsurNationGoodsPhysic.getMED_LIST_CODG())
                                        .fixmedins_hilist_id(vInsurNationGoodsPhysic.getFIXMEDINS_HILIST_ID())
                                        .fixmedins_hilist_name(vInsurNationGoodsPhysic.getFIXMEDINS_HILIST_NAME())
                                        .fixmedins_bchno(vInsurNationGoodsPhysic.getFIXMEDINS_BCHNO())
                                        .prsc_dr_cert_type(vInsurNationGoodsPhysic.getPRSC_DR_CERT_TYPE())
                                        .prsc_dr_certno(vInsurNationGoodsPhysic.getPRSC_DR_CERTNO())
                                        .prsc_dr_name(vInsurNationGoodsPhysic.getPRSC_DR_NAME())
                                        .phar_cert_type(vInsurNationGoodsPhysic.getPHAR_CERT_TYPE())
                                        .phar_certno(vInsurNationGoodsPhysic.getPHAR_CERTNO())
                                        .phar_name(vInsurNationGoodsPhysic.getPHAR_NAME())
                                        .phar_prac_cert_no(vInsurNationGoodsPhysic.getPHAR_PRAC_CERT_NO())
                                        .hi_feesetl_type(vInsurNationGoodsPhysic.getHI_FEESETL_TYPE())
                                        .setl_id(vInsurNationGoodsPhysic.getSETL_ID())
                                        .mdtrt_sn(vInsurNationGoodsPhysic.getMDTRT_SN())
                                        .psn_no(vInsurNationGoodsPhysic.getPSN_NO())
                                        .psn_cert_type(vInsurNationGoodsPhysic.getPSN_CERT_TYPE())
                                        .certno(vInsurNationGoodsPhysic.getCERTNO())
                                        .psn_name(vInsurNationGoodsPhysic.getPSN_NAME())
                                        .manu_lotnum(vInsurNationGoodsPhysic.getMANU_LOTNUM())
                                        .manu_date(vInsurNationGoodsPhysic.getMANU_DATE())
                                        .expy_end(vInsurNationGoodsPhysic.getEXPY_END())
                                        .rx_flag(vInsurNationGoodsPhysic.getRX_FLAG())
                                        .trdn_flag(vInsurNationGoodsPhysic.getTRDN_FLAG())
                                        .finl_trns_pric(vInsurNationGoodsPhysic.getFINL_TRNS_PRIC())
                                        .rxno(vInsurNationGoodsPhysic.getRXNO())
                                        .rx_circ_flag(vInsurNationGoodsPhysic.getRX_CIRC_FLAG())
                                        .rtal_docno(vInsurNationGoodsPhysic.getRTAL_DOCNO())
                                        .stoout_no(vInsurNationGoodsPhysic.getSTOOUT_NO())
                                        .bchno(vInsurNationGoodsPhysic.getBCHNO())
                                        .drug_prod_barc(vInsurNationGoodsPhysic.getRUG_PROD_BARC())
                                        .shelf_posi(vInsurNationGoodsPhysic.getSHELF_POSI())
                                        .sel_retn_cnt(vInsurNationGoodsPhysic.getSEL_RETN_CNT())
                                        .sel_retn_time(vInsurNationGoodsPhysic.getSEL_RETN_TIME())
                                        .sel_retn_opter_name(vInsurNationGoodsPhysic.getSEL_RETN_OPTER_NAME())
                                        .memo(vInsurNationGoodsPhysic.getMEMO())
                                        .mdtrt_setl_type(vInsurNationGoodsPhysic.getMDTRT_SETL_TYPE())
                                        .drugtracinfo(drugTraceList).build();
                                xsck3505Requests.add(xsck3505Request);
                            }
                        }
                    }
                    BaseXsck3505Request baseXsck3505Request = new BaseXsck3505Request();
                    baseXsck3505Request.setSelinfoDetail(xsck3505Requests);
                    String jsonStr = JSONUtil.toJsonStr(baseXsck3505Request);
                    JSONObject dataJson = JSONObject.parseObject(jsonStr);
                    ybClient.ybPost("3505A", dataJson);
                }
            }
        }
//ybClient.ybPost(dictRequest.getApiCode(), jsonStr)
        return ResultVOUtils.success();
    }


}
