package thyyxxk.webserver.controller.medicalinsurance;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.medicalinsurance.SiInjuryDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.medicalinsurance.injury.AdmissRegistration;
import thyyxxk.webserver.entity.medicalinsurance.injury.InjurySiPatInfo;
import thyyxxk.webserver.entity.inpatient.dismiss.MedinsSettleFee;
import thyyxxk.webserver.entity.inpatient.patient.Patient;
import thyyxxk.webserver.service.externalhttp.SiInjuryFeeUpld;
import thyyxxk.webserver.service.externalhttp.SiInjurySystem;
import thyyxxk.webserver.service.inpatient.DismissService;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/siInjury")
public class SiInjuryController {
    private final SiInjuryDao dao;
    private final DismissService dismissService;
    private final SiInjurySystem injurySystem;
    private final SiInjuryFeeUpld injuryFeeUpld;
    @Value("${si-injury-fee-url}")
    private String siInjuryFeeUrl;
    @Value("${si-injury-systm-url}")
    private String siInjurySystmUrl;

    @Autowired
    public SiInjuryController(SiInjuryDao dao, DismissService dismissService, SiInjurySystem injurySystem, SiInjuryFeeUpld injuryFeeUpld) {
        this.dao = dao;
        this.dismissService = dismissService;
        this.injurySystem = injurySystem;
        this.injuryFeeUpld = injuryFeeUpld;
    }

    @PostMapping("/getPersonBaseinfo")
    public ResultVo<List<InjurySiPatInfo>> getPersonBaseinfo(@RequestBody Patient p) {
        if (null == p.getInjuryArea()) {
            return ResultVoUtil.fail(ExceptionEnum.NULL_POINTER, "请选择工伤参保地！");
        }
        p.setStaffId(TokenUtil.getTokenUserId());
        ResultVo<JSONObject> resultVo = injurySystem.getPersonBaseinfo(siInjurySystmUrl, p);
        if (null == resultVo) {
            return ResultVoUtil.fail(ExceptionEnum.INTERNAL_SERVER_ERROR);
        }
        if (resultVo.getCode() != ExceptionEnum.SUCCESS.getCode()) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, resultVo.getMessage());
        }
        JSONObject result = resultVo.getData();
        if (dao.selectCount(p.getInpatientNo(), p.getAdmissTimes(), p.getLedgerSn()) == 0) {
            JSONArray personinfos = result.getJSONArray("personinfo");
            JSONObject item = personinfos.getJSONObject(0);
            dao.insertNewInjurybase(p.getInpatientNo(), p.getAdmissTimes(), p.getLedgerSn(), item.getString("indi_id"),
                    item.getString("center_id"), item.getString("pers_type"), p.getInjuryArea());
        } else {
            JSONArray personinfos = result.getJSONArray("personinfo");
            JSONObject item = personinfos.getJSONObject(0);
            dao.updateInjurybase(p.getInpatientNo(), p.getAdmissTimes(), p.getLedgerSn(), item.getString("indi_id"),
                    item.getString("center_id"), item.getString("pers_type"), p.getInjuryArea());
        }
        if (null == result.get("injuryorbirthinfo")) {
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, "没有查询到工伤认定信息！");
        }
        JSONArray injuries = result.getJSONArray("injuryorbirthinfo");
        List<InjurySiPatInfo> list = new ArrayList<>();
        for (int i = 0; i < injuries.size(); i++) {
            InjurySiPatInfo info = JSONObject.parseObject(injuries.getJSONObject(i).toJSONString(), InjurySiPatInfo.class);
            list.add(info);
        }
        return ResultVoUtil.success(list);
    }

    @PostMapping("/admissRegistration")
    public ResultVo<String> admissRegistration(@RequestBody AdmissRegistration admreg) {
        admreg.getBaseinfo().setStaffId(TokenUtil.getTokenUserId());
        admreg.getInjuryinfo().setPatNo(admreg.getBaseinfo().getInpatientNo());
        admreg.getInjuryinfo().setTimes(admreg.getBaseinfo().getAdmissTimes());
        admreg.getInjuryinfo().setLedgerSn(admreg.getBaseinfo().getLedgerSn());
        dao.updateInjuryinfo(admreg.getInjuryinfo());
        CodeName maindiag = dao.selectMainDiag(admreg.getBaseinfo().getInpatientNo(), admreg.getBaseinfo().getAdmissTimes());
        if (null == maindiag) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保入院诊断不能为空！");
        }
        admreg.getBaseinfo().setIcdCode(maindiag.getCode());
        admreg.getBaseinfo().setIcdText(maindiag.getName());
        admreg.setInjuryinfo(dao.selectInjuryinfo(admreg.getBaseinfo().getInpatientNo(), admreg.getBaseinfo().getAdmissTimes(),
                admreg.getBaseinfo().getLedgerSn()));
        return injurySystem.admissRegistration(siInjurySystmUrl, admreg);
    }

    @PostMapping("/getRegisterInfo")
    public ResultVo<Map<String, String>> getRegisterInfo(@RequestBody Patient p) {
        p.setStaffId(TokenUtil.getTokenUserId());
        return injurySystem.getRegisterInfo(siInjurySystmUrl, p);
    }

    @PostMapping("/uploadFees")
    public ResultVo<String> uploadFees(@RequestBody Patient p) {
        p.setStaffId(TokenUtil.getTokenUserId());
        return injuryFeeUpld.uploadFees(siInjuryFeeUrl, p);
    }

    @PostMapping("/cancelRegister")
    public ResultVo<String> cancelRegister(@RequestBody Patient p) {
        p.setStaffId(TokenUtil.getTokenUserId());
        return injurySystem.cancelRegister(siInjurySystmUrl, p);
    }

    @PostMapping("/cancelUploadFee")
    public ResultVo<String> cancelUploadFee(@RequestBody Patient p) {
        p.setStaffId(TokenUtil.getTokenUserId());
        return injurySystem.cancelUploadFee(siInjurySystmUrl, p);
    }

    @PostMapping("/preCalculateCost")
    public ResultVo<String> preCalculateCost(@RequestBody Patient p) {
        p.setStaffId(TokenUtil.getTokenUserId());
        return injurySystem.preCalculateCost(siInjurySystmUrl, p);
    }

    @PostMapping("/calculateCost")
    public synchronized ResultVo<String> calculateCost(@RequestBody Patient p) {
        p.setStaffId(TokenUtil.getTokenUserId());
        ResultVo<MedinsSettleFee> resultVo = injurySystem.calculateCost(siInjurySystmUrl, p);
        if (null == resultVo) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "获取医保结算费用失败。");
        }
        if (resultVo.getCode() != ExceptionEnum.SUCCESS.getCode()) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, resultVo.getMessage());
        }
        MedinsSettleFee settleFee = resultVo.getData();
        if (p.getMidSetl()) {
            settleFee.setZjdzDatetime(p.getZjdzDatetime());
        }
        settleFee.setMidSetl(p.getMidSetl());
        settleFee.setStaffId(TokenUtil.getTokenUserId());
        settleFee.setInpatientNo(p.getInpatientNo());
        settleFee.setAdmissTimes(p.getAdmissTimes());
        settleFee.setBedNo(p.getBedNo());
        settleFee.setWardCode(p.getAdmissWard());
        settleFee.setDeptCode(p.getAdmissDept());
        return dismissService.executeDischarging(settleFee);
    }

    @PostMapping("/cancelCalculate")
    public ResultVo<String> cancelCalculate(@RequestBody Patient p) {
        p.setStaffId(TokenUtil.getTokenUserId());
        return injurySystem.cancelCalculate(siInjurySystmUrl, p);
    }
}
