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.query.DoctorListQuery;
import com.xinelu.familydoctor.applet.pojo.query.NearbyOrgQuery;
import com.xinelu.familydoctor.applet.pojo.query.PackageQuery;
import com.xinelu.familydoctor.applet.pojo.query.TeamListQuery;
import com.xinelu.familydoctor.applet.pojo.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author mengkuiliang
 * @Description 签约控制器
 * @Date 2023-09-26 026 14:25
 * @Param
 * @return
 **/
@Api(tags = "签约控制器")
@RestController
@RequestMapping("/applet/signinfo")
public class SignInfoController extends BaseController {
    @Resource
    private HttpService httpService;
    @Value("${fd.distance}")
    private BigDecimal DISTANCE;

    @ApiOperation(value = "获取签约详情")
    @GetMapping("/detail/{identity}")
    public R<SignInfoDetailVo> detail(@PathVariable String identity, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/detail/" + identity, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!"1".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            return R.fail("未查询到签约信息");
        }
        return R.ok(JSONObject.parseObject(jsonObject.getJSONObject("data").toJSONString(), SignInfoDetailVo.class));
    }

    @ApiOperation(value = "获取居民公卫健康档案")
    @GetMapping("/archive/{identity}")
    public R<ArchiveReviewVo> archive(@PathVariable String identity, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/archive/" + identity, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!"1".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data")) {
            return R.fail("未查询到居民公卫档案");
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (data == null) {
            return R.fail("未查询到居民公卫档案");
        }
        return R.ok(JSONObject.parseObject(data.toJSONString(), ArchiveReviewVo.class));
    }

    @ApiOperation(value = "获取已签约服务包")
    @GetMapping("/getSignPackage/{identity}")
    public R<List<SignedPackageVo>> getSignPackage(@PathVariable("identity") String identity, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/getSignPackage/" + identity, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!"1".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        JSONArray array = jsonObject.getJSONArray("data");
        List<SignedPackageVo> signedPackageVoList = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            signedPackageVoList.add(JSONObject.parseObject(object.toJSONString(), SignedPackageVo.class));
        }
        return R.ok(signedPackageVoList);
    }

    @ApiOperation("获取可选择的服务包（个性包）")
    @GetMapping("/getPackageList/{identity}")
    public R<List<PackageDetailVo>> getPackageList(@PathVariable("identity") String identity, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/getPackageList/" + identity, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!"1".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            return null;
        }
        return R.ok(JSONArray.parseArray(jsonObject.getJSONArray("data").toJSONString()).toJavaList(PackageDetailVo.class));
    }

    @ApiOperation(value = "获取区县列表")
    @PostMapping("/getCounty")
    public R<List<NearOrgVo>> getCounty(@RequestBody NearbyOrgQuery query, @RequestHeader("region") String region) {
        JSONObject result = httpService.post(SpringUtils.getFdUrl(region) + "/org/getCounty", null, JSONObject.parseObject(JSONObject.toJSONString(query)));
        if ("0".equals(result.get("code"))) {
            return R.fail(result.get("msg").toString());
        }
        if (!result.containsKey("data") || result.get("data") == null) {
            return R.ok();
        }
        return R.ok(JSONArray.parseArray(result.getJSONArray("data").toJSONString()).toJavaList(NearOrgVo.class));
    }

    @ApiOperation(value = "获取区划列表", notes = "山东省： 370000000000  德州市： 371400000000 东营市：370500000000")
    @GetMapping("/area/list/{pid}")
    public R<List<AreaListVo>> getPhArea(@PathVariable Long pid, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/area/ph/list/" + pid, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("0".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            return R.ok();
        }
        return R.ok(JSONArray.parseArray(jsonObject.getJSONArray("data").toJSONString()).toJavaList(AreaListVo.class));
    }

    @ApiOperation("获取区划详情")
    @GetMapping("/area/getAreaById/{id}")
    public R<AreaListVo> getAreaById(@PathVariable Long id, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/area/ph/getAreaById/" + id, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("0".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            return R.ok();
        }
        return R.ok(JSONObject.parseObject(jsonObject.getJSONObject("data").toJSONString(), AreaListVo.class));
    }

    @ApiOperation(value = "获取附近机构列表", notes = "lng：经度 lat：纬度")
    @GetMapping("/getNearbyOrg")
    public TableDataInfo getNearbyOrg(NearbyOrgQuery query, @RequestHeader("region") String region) {
        if (query.getDistance() != null && query.getDistance().compareTo(new BigDecimal("0")) < 0) {
            query.setDistance(DISTANCE);
        }
        JSONObject result = httpService.post(SpringUtils.getFdUrl(region) + "/org/getNearbyOrg/", null, JSONObject.parseObject(JSONObject.toJSONString(query)));
        if ("0".equals(result.get("code"))) {
            throw new ServiceException(result.get("msg").toString());
        }
        if (result.containsKey("data") && result.get("data") != null) {
            JSONObject jsonObject = result.getJSONObject("data");
            return getDataTable(jsonObject.getJSONArray("list"), jsonObject.getInteger("total"));
        }
        return getDataTable(null, 0);
    }

    @ApiOperation(value = "获取团队列表")
    @GetMapping("/getTeamList")
    public TableDataInfo getTeamList(TeamListQuery query, @RequestHeader("region") String region) {
        JSONObject result = httpService.post(SpringUtils.getFdUrl(region) + "/resident/signinfo/getTeamList", null, JSONObject.parseObject(JSONObject.toJSONString(query)));
        if ("0".equals(result.get("code"))) {
            throw new ServiceException(result.get("msg").toString());
        }
        if (result.containsKey("data") && result.get("data") != null) {
            JSONObject jsonObject = result.getJSONObject("data");
            return getDataTable(jsonObject.getJSONArray("list"), jsonObject.getInteger("total"));
        }
        return getDataTable(null, 0);
    }

    @ApiOperation(value = "获取团队详情")
    @GetMapping("/getTeam/{teamNo}")
    public R<List<TeamDetailVo>> getTeamList(@PathVariable String teamNo, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/getTeam/" + teamNo, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("0".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            return R.ok();
        }
        return R.ok(JSONArray.parseArray(jsonObject.getJSONArray("data").toJSONString()).toJavaList(TeamDetailVo.class));
    }

    @ApiOperation("获取医生列表")
    @GetMapping("/getDoctorList")
    public TableDataInfo getDoctorList(DoctorListQuery query, @RequestHeader("region") String region) {
        JSONObject result = httpService.post(SpringUtils.getFdUrl(region) + "/doctor/getDoctorList", 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) {
            JSONObject jsonObject = result.getJSONObject("data");
            return getDataTable(jsonObject.getJSONArray("list"), jsonObject.getInteger("total"));
        }
        return getDataTable(null, 0);
    }

    @ApiOperation(value = "获取签约协议模版内容", notes = "协议模版内容、机构公章照片base64、签约医生签名照片base64")
    @GetMapping("/getContent/{userNo}")
    public R<ProtocolContentVo> getAreaById(@PathVariable String userNo, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/getContent/" + userNo, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("0".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            return R.ok();
        }
        return R.ok(JSONObject.parseObject(jsonObject.getJSONObject("data").toJSONString(), ProtocolContentVo.class));
    }

    @ApiOperation(value = "获取居民履约情况")
    @GetMapping("/getPerformance/{identity}")
    public R<List<PerformancePackageVo>> getPerformance(@PathVariable String identity, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/performance/getPerPackage/" + identity + "/0", null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("0".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            return R.ok();
        }
        return R.ok(JSONArray.parseArray(jsonObject.getJSONArray("data").toJSONString()).toJavaList(PerformancePackageVo.class));
    }

    @ApiOperation(value = "获取家医人群")
    @GetMapping("/getCrowd/{identity}")
    public R<List<CrowdVo>> getCrowd(@PathVariable String identity, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/getCrowd/" + identity, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("0".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            return R.ok();
        }
        return R.ok(JSONArray.parseArray(jsonObject.getJSONArray("data").toJSONString()).toJavaList(CrowdVo.class));
    }

    @ApiOperation("根据人群获取服务包")
    @PostMapping("/getPackageByCrowdNo")
    public R<List<PackageDetailVo>> getPackageByCrowdNo(@RequestBody PackageQuery query, @RequestHeader("region") String region) {
        if (query == null) {
            return R.fail("请求参数不能为空");
        }
        if (StringUtils.isBlank(query.getOrgNo())) {
            return R.fail("机构编号不能为空");
        }
        if (query.getCrowdNoList() == null || query.getCrowdNoList().size() == 0) {
            return R.fail("人群编号不能为空");
        }
        JSONObject result = httpService.post(SpringUtils.getFdUrl(region) + "/package/getPackageByCrowdNoList", null, JSONObject.parseObject(JSONObject.toJSONString(query)));
        if ("0".equals(result.get("code"))) {
            return R.fail(result.get("msg").toString());
        }
        if (result.containsKey("data") && result.get("data") != null) {
            return R.ok(JSONArray.parseArray(result.getJSONArray("data").toJSONString()).toJavaList(PackageDetailVo.class));
        }
        return R.ok();
    }

    @ApiOperation(value = "获取签约协议")
    @GetMapping("/getSignProtocol/{cardNo}")
    public R<SignInfoDataVo> getSignProtocol(@PathVariable String cardNo, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/getSignProtocol/" + cardNo, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("0".equals(jsonObject.get("code"))) {
            return R.fail(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            return R.ok();
        }
        return R.ok(JSONObject.parseObject(jsonObject.getJSONObject("data").toJSONString(), SignInfoDataVo.class));
    }

}
