package com.fs.app.controller;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.store.vo.PrescribeV2VO;
import com.fs.common.core.domain.R;
import com.fs.common.event.TemplateBean;
import com.fs.common.event.TemplateEvent;
import com.fs.common.event.TemplateListenEnum;
import com.fs.common.utils.ParseUtils;
import com.fs.store.domain.FsStoreOrder;
import com.fs.wx.pay.config.WxPayProperties;
import com.fs.store.domain.FsPrescribe;
import com.fs.store.param.*;
import com.fs.store.service.IFsPrescribeService;
import com.fs.store.service.IFsStoreOrderItemService;
import com.fs.store.service.IFsStoreOrderService;
import com.fs.store.vo.FsPrescribeVO;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


@Slf4j
@Api("处方接口")
@RestController
@RequestMapping(value="/app/prescribe")
public class PrescribeController extends  AppBaseController {
    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private IFsStoreOrderService orderService;

    @Autowired
    private ApplicationEventPublisher publisher;

    @Autowired
    private IFsStoreOrderItemService itemService;

    @Autowired
    private IFsPrescribeService prescribeService;


    @Login
    @ApiOperation("获取我的处方列表")
    @GetMapping("/getMyPrescribeList")
    public R getMyPrescribeList(FsPrescribeQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        param.setUserId(Long.parseLong(getUserId()));
        List<FsPrescribeVO> list=prescribeService.selectFsPrescribeListQuery(param);
        for(FsPrescribeVO vo : list){
            vo.setUserPhone(ParseUtils.parsePhone(vo.getUserPhone()));
            vo.setPatientTel(ParseUtils.parsePhone(vo.getPatientTel()));
        }
        PageInfo<FsPrescribeVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("开处方")
    @PostMapping("/doPrescribe")
    public R doPrescribe(@Validated @RequestBody FsPrescribeParam param, HttpServletRequest request){
        return prescribeService.doPrescribe(Long.parseLong(getUserId()),param);
    }

    @ApiOperation("通知地址")
    @PostMapping(value="/presribeNotify")
    public String presribeNotify(HttpServletRequest request,@RequestBody String jsonBody) throws Exception
    {
        // 封装JSON请求
        //{"msg":"成功","code":1000,"data":{"rp_id":"202203151003300001","order_id":null,"depart_name":"内科","doctor_name":"测试账号","pharmacist_name":null,"rp_url":"https://asset.nxk520.com/202203-go/C2203151057038646.png","diagnose":"眼睑带状疱疹","rp_msg":"已开方","audit_reason":null,"drugInfo":[{"drug_name":"维力青 恩替卡韦分散片 0.5mg*7片","sale_amount":1,"drug_specification":"0.5mg*7片"}],"create_date":"2022-03-15 10:03:30","pharmacy_code":"00001","pharmacy_name":"测试门店","doctor_id":"383"}}
        log.info("处方回调数据:{}",jsonBody);
        JSONObject json = JSON.parseObject(jsonBody);
        PrescribeV2VO vo= JSONUtil.toBean(jsonBody, PrescribeV2VO.class);
        if(vo.getCode().equals("1000")){
            if(vo.getData().getStatus().equals("已开方")){
                FsPrescribe fsPrescribe=prescribeService.selectFsPrescribeByRpId(vo.getData().getOnlyId());
                fsPrescribe.setRpUrl(vo.getData().getPrescriptionUrl());
                fsPrescribe.setRpCreateTime(new Date());
                fsPrescribe.setDoctorName(vo.getData().getDoctorName());
                fsPrescribe.setDiagnose(vo.getData().getDiagnose());
                fsPrescribe.setDrugs(JSONUtil.toJsonStr(vo.getData().getDrugInfo()));
                fsPrescribe.setStatus(1);
                fsPrescribe.setAuditReason(vo.getData().getAuditReason());
                prescribeService.updateFsPrescribe(fsPrescribe);
                //创建OMS订单
                FsStoreOrder order= orderService.selectFsStoreOrderById(fsPrescribe.getOrderId());
                if(order!=null&&order.getStatus()>0){
                    orderService.createOmsOrder(fsPrescribe.getOrderId());
                }
                TemplateBean templateBean = TemplateBean.builder()
                        .rpId(fsPrescribe.getRpId())
                        .orderId(fsPrescribe.getOrderId().toString())
                        .rpCreateTime(fsPrescribe.getRpCreateTime())
                        .rpStatus("已开方")
                        .userId(fsPrescribe.getUserId())
                        .templateType(TemplateListenEnum.TYPE_4.getValue())
                        .build();
                publisher.publishEvent(new TemplateEvent(this, templateBean));

            }
            else if(vo.getData().getStatus().equals("已拒绝")){
                FsPrescribe fsPrescribe=prescribeService.selectFsPrescribeByRpId(vo.getData().getOnlyId());
                fsPrescribe.setRpUrl(vo.getData().getPrescriptionUrl());
                fsPrescribe.setRpCreateTime(new Date());
                fsPrescribe.setDoctorName(vo.getData().getDoctorName());
                fsPrescribe.setDiagnose(vo.getData().getDiagnose());
                fsPrescribe.setDrugs(JSONUtil.toJsonStr(vo.getData().getDrugInfo()));
                fsPrescribe.setStatus(2);
                fsPrescribe.setAuditReason(vo.getData().getAuditReason());
                prescribeService.updateFsPrescribe(fsPrescribe);
                //自动退款
                orderService.refundPrescribeOrder(fsPrescribe.getOrderId());
                TemplateBean templateBean = TemplateBean.builder()
                        .rpId(fsPrescribe.getRpId())
                        .orderId(fsPrescribe.getOrderId().toString())
                        .rpCreateTime(fsPrescribe.getRpCreateTime())
                        .rpStatus("已拒绝")
                        .userId(fsPrescribe.getUserId())
                        .templateType(TemplateListenEnum.TYPE_4.getValue())
                        .build();
                publisher.publishEvent(new TemplateEvent(this, templateBean));
            }
        }

        return "success";

    }


}
