package com.xinelu.web.controller.applet;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xinelu.common.core.controller.BaseController;
import com.xinelu.common.core.domain.R;
import com.xinelu.common.core.page.TableDataInfo;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.http.HttpService;
import com.xinelu.common.utils.spring.SpringUtils;
import com.xinelu.familydoctor.applet.pojo.body.ResidentServiceApplyBody;
import com.xinelu.familydoctor.applet.pojo.entity.PatientInfo;
import com.xinelu.familydoctor.applet.pojo.query.ApplyQuery;
import com.xinelu.familydoctor.applet.pojo.query.ServiceRecordQuery;
import com.xinelu.familydoctor.applet.pojo.vo.*;
import com.xinelu.familydoctor.applet.service.IResidentPatientInfoService;
import com.xinelu.familydoctor.applet.service.IResidentServiceAppletService;
import com.xinelu.manage.domain.orderevaluateinfo.OrderEvaluateInfo;
import com.xinelu.manage.service.orderevaluateinfo.IOrderEvaluateInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author mengkuiliang
 * @Description 居民小程序服务申请控制器
 * @Date 2023-10-07 007 11:30
 * @Param
 * @return
 **/
@Api(tags = "服务申请控制器")
@RestController
@RequestMapping("/applet/service/apply")
public class ResidentServiceApplyController extends BaseController {

    @Resource
    private IResidentServiceAppletService residentServiceAppletService;
    @Resource
    private HttpService httpService;
    @Resource
    private IResidentPatientInfoService residentPatientInfoService;
    @Resource
    private IOrderEvaluateInfoService orderEvaluateInfoService;

    @ApiOperation("提交服务申请")
    @PostMapping("/save")
    public R<?> save(@RequestBody ResidentServiceApplyBody body) {
        if (body == null || StringUtils.isBlank(body.getPackageNo()) || StringUtils.isBlank(body.getFormNo())) {
            return R.fail("请求参数不能为空");
        }
        if (StringUtils.isBlank(body.getIdentity())) {
            return R.fail("居民身份证号不能为空");
        }
        residentServiceAppletService.insert(body);
        return R.ok();
    }

    @ApiOperation("取消服务申请")
    @GetMapping("/cancel/{bookingNo}")
    public R<?> cancel(@PathVariable String bookingNo) {
        residentServiceAppletService.cancel(bookingNo);
        return R.ok();
    }

    @ApiOperation("服务申请列表")
    @PostMapping("/list")
    public TableDataInfo performanceBookingList(@RequestBody ApplyQuery query) {
        if (StringUtils.isBlank(query.getIdentity())) {
            throw new ServiceException("居民身份证号不能为空");
        }
        try {
            startPage();
            return getDataTable(residentServiceAppletService.findList(query));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    @ApiOperation("服务申请详情")
    @GetMapping("/detail/{bookingNo}")
    public R<ResidentServiceApplyVo> performanceBookingDetail(@PathVariable String bookingNo) {
        return R.ok(residentServiceAppletService.detail(bookingNo));
    }

    @ApiOperation(value = "获取服务申请项目列表", notes = "获取家医个性服务包和筛查项目")
    @GetMapping("/getForm/{identity}")
    public R<List<ScreeningProjectVo>> getForm(@PathVariable String identity, String projectName, @RequestHeader("region") String region) {
        return R.ok(residentServiceAppletService.getForm(identity, projectName, region));
    }

    @ApiOperation("服务记录列表")
    @GetMapping("/record/{identity}")
    public R<List<ResidentServiceRecordVo>> performanceBookingRecord(@PathVariable String identity, ServiceRecordQuery query, @RequestHeader("region") String region) {
        query.setIdentity(identity);
        if (query.getPageNum() == null) {
            query.setPageNum(1);
        }
        if (query.getPageSize() == null) {
            query.setPageSize(1000);
        }
        JSONObject result = httpService.post(SpringUtils.getFdUrl(region) + "/performance/recordV1", null, JSONObject.parseObject(JSONObject.toJSONString(query)));
        if (result.get("code").toString().equals("0")) {
            throw new ServiceException(result.get("msg").toString());
        }
        if (result.get("data") != null) {
            List<ResidentServiceRecordVo> perRecordList = JSONArray.parseArray(result.getJSONObject("data").getJSONArray("list").toJSONString()).toJavaList(ResidentServiceRecordVo.class);
            if (perRecordList != null && perRecordList.size() > 0) {
                // 查询评价
                List<OrderEvaluateInfo> list = orderEvaluateInfoService.selectOrderEvaluateByServiceNos(perRecordList.stream().map(ResidentServiceRecordVo::getPerformanceNo).collect(Collectors.toList()), "FAMILY_DOCTOR");
                if (list != null && list.size() > 0) {
                    List<OrderEvaluateInfo> orderEvaluateInfoTempList;
                    for (ResidentServiceRecordVo record : perRecordList) {
                        orderEvaluateInfoTempList = list.stream().filter(o -> o.getOrderNo().equals(record.getPerformanceNo())).collect(Collectors.toList());
                        if (orderEvaluateInfoTempList.size() > 0) {
                            record.setOrderEvaluateInfo(orderEvaluateInfoTempList.get(0));
                        }
                    }
                }
            }
            return R.ok(perRecordList);
        }
        return R.ok();
    }

    @ApiOperation("获取服务记录详情")
    @GetMapping("/serviceRecordDetail/{identity}/{performanceNo}")
    public R<ResidentServiceRecordVo> serviceRecordDetail(@PathVariable String identity, @PathVariable String performanceNo, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/performance/detail/" + identity + "/" + performanceNo, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code") != 1) {
            throw new ServiceException(jsonObject.getString("msg"));
        }
        if (jsonObject.get("data") != null) {
            return R.ok(JSONObject.parseObject(jsonObject.getJSONObject("data").toJSONString(), ResidentServiceRecordVo.class));
        }
        return R.ok();
    }

    @ApiOperation("服务评价列表")
    @GetMapping("/evaluateRecord/{identity}")
    public R<List<OrderEvaluateVo>> performanceEvaluateRecord(@PathVariable String identity, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/performance/recordV2/" + identity, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code") == 1) {
            if (jsonObject.get("data") != null && jsonObject.getJSONArray("data").size() > 0) {
                return R.ok(JSONArray.parseArray(jsonObject.getJSONArray("data").toJSONString()).toJavaList(OrderEvaluateVo.class));
            }
        }
        return R.ok();
    }
}
