package com.yihu.wlyy.web.doctor.team;

import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabelInfo;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.patient.PatientDiseaseDao;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.service.app.statistics.StatisticsAllService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.util.IdCardUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/doctor/admin-teams", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生行政团队")
public class AdminTeamController extends BaseController {
    @Autowired
    private PatientDiseaseDao patientDiseaseDao;
    @Autowired
    private AdminTeamService teamService;
    @Autowired
    private AdminTeamService memberService;
    @Autowired
    private SignPatientLabelInfoService signPatientLabelInfoService;
    @Autowired
    private StatisticsAllService statisticsAllService;


    @RequestMapping(value = "/count", method = RequestMethod.GET)
    @ApiOperation(value = "团队数量")
    public String teamCount() {
        try {
            long count = teamService.getTeamCount();

            JSONObject json = new JSONObject();
            json.put("count", count);
            return write(200, "OK", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    /**
     * pc端im使用
     * @return
     */
    @RequestMapping(value = "/doctorTeamMembers", method = RequestMethod.GET)
    @ApiOperation(value = "根据医生code返回所有团队的医生")
    public String getTeamMembersByDoctorCode(){
        try {
            JSONArray jsonArray = teamService.getTeamMembersByDoctorCode(getUID());
            return write(200, "OK", "data", jsonArray);
        }catch (Exception e){
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(method = RequestMethod.POST)
    @ApiOperation(value = "创建团队")
    @ObserverRequired
    public String createTeam(@RequestParam("team_name") String teamName,
                             @RequestParam("leader_id") String leaderCode,
                             @RequestParam("org_code") String orgCode) {
        try {
            AdminTeam team = teamService.createTeam(teamName, leaderCode, orgCode);

            teamService.addMember(team.getId(), leaderCode);

            return write(200, "OK", "data", team);
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ApiOperation(value = "删除团队信息")
    @ObserverRequired
    public String deleteTeam(@RequestParam("teamId") long teamId) {
        try {
            teamService.deleteTeam(teamId);

            return write(200, "OK");
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/{team_id}/name", method = RequestMethod.POST)
    @ApiOperation(value = "更新团队名称")
    @ObserverRequired
    public String updateTeamName(@PathVariable("team_id") long teamId,
                                 @RequestParam("team_name") String teamName) {
        try {
            AdminTeam team = teamService.updateTeamName(teamId, teamName);

            return write(200, "OK", "data", team);
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/{team_id}/leader", method = RequestMethod.POST)
    @ApiOperation(value = "更新团队领导")
    @ObserverRequired
    public String updateTeamLeader(@PathVariable("team_id") long teamId,
                                   @RequestParam("doctor_code") String doctorCode) {
        try {
            AdminTeam team = teamService.updateTeamLeader(teamId, doctorCode);

            return write(200, "OK", "data", team);
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/{team_id}", method = RequestMethod.GET)
    @ApiOperation(value = "团队信息")
    public String getTeam(@PathVariable("team_id") long teamId) {
        try {
            AdminTeam team = teamService.getTeam(teamId);

            return write(200, "OK", "data", team);
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/{team_id}/members", method = RequestMethod.POST)
    @ApiOperation(value = "添加团队成员，批量添加使用逗号分隔列表")
    @ObserverRequired
    public String addMember(@PathVariable("team_id") long teamId,
                            @RequestParam("doctor_code") String doctorCodeList) {
        try {
            String doctorCodes[] = doctorCodeList.split(",");
            for (String doctorCode : doctorCodes) {
                teamService.addMember(teamId, doctorCode);
            }

            return write(200, "OK", "data", "");
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/{team_id}/members", method = RequestMethod.GET)
    @ApiOperation(value = "获取团队成员")
    public String getTeamMembers(@PathVariable("team_id") long teamId) {
        try {
            List<Doctor> members = memberService.getMembers(teamId);

            return write(200, "OK", "data", new JSONArray(copyBeans(members, "id", "code", "name", "hospital",
                    "jobName", "level", "sex", "photo")));
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    //目前没用到，之后可能会用到
//  @RequestMapping(value = "/{team_id}/members/excludedThisAndLevel3", method = RequestMethod.GET)
//  @ApiOperation(value = "获取团队成员,排除自己和专科医生")
    public String getTeamMembersExcludedThisAndLevel3(@PathVariable("team_id") long teamId) {
        try {
            List<Doctor> members = memberService.getMembers(teamId, super.getUID());

            return write(200, "OK", "data", new JSONArray(copyBeans(members, "id", "code", "name", "hospital",
                    "jobName", "level", "sex", "photo")));
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/{team_id}/members/excluded", method = RequestMethod.GET)
    @ApiOperation(value = "获取机构内不在特定团队的医生")
    public String getExcludedTeamMembers(@RequestParam("org_code") String orgCode,
                                         @RequestParam(value = "doctor_name", required = false) String doctorName,
                                         @PathVariable("team_id") long teamId,
                                         @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                         @RequestParam(value = "size", required = false, defaultValue = "10") int size) {
        try {
            page = page <= 0 ? 0 : page - 1;
            List<Doctor> members = memberService.getExcludedMembers(orgCode, doctorName, teamId, page, size);

            return write(200, "OK", "data", new JSONArray(members));
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/{team_id}/members/{doctor_code}/remove", method = RequestMethod.POST)
    @ApiOperation(value = "移除成员")
    @ObserverRequired
    public String removeMember(@PathVariable("team_id") long teamId,
                               @PathVariable("doctor_code") String doctorCode) {

        try {
            Pair<Integer, String> result = memberService.removeMember(teamId, doctorCode);

            return write(result.getLeft(), "OK", "data", result.getRight());
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/team/{doctor_code}/team", method = RequestMethod.GET)
    @ApiOperation(value = "获取团队长团队")
    @ResponseBody
    public String getLeaderTeam(@PathVariable("doctor_code") String doctorCode) {
        try {
            AdminTeam team = teamService.findByLeaderCode(doctorCode);
            if (team == null) {
                return error(-2, "没有找到数据！");
            }
            return write(200, "OK", "data", new JSONObject(team));
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/team/{doctor_code}/teams", method = RequestMethod.GET)
    @ApiOperation(value = "获取医生团队列表")
    public String getDoctorTeams(@PathVariable("doctor_code") String doctorCode) {
        try {
            List<AdminTeam> teamList = teamService.getDoctorTeams(doctorCode);

            return write(200, "OK", "data", new JSONArray(teamList));
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/team/members/{patient_code}", method = RequestMethod.GET)
    @ApiOperation(value = "根据患者代码，获取医生团队信息")
    public String getTeam(@PathVariable("patient_code") String patientCode) {
        try {
            Map<String, Object> team = teamService.getPatientSigningTeam(patientCode, super.getUID());

            return write(200, "OK", "data", new JSONObject(team));
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/teams/{team_id}/signing/count", method = RequestMethod.GET)
    @ApiOperation(value = "获取团队医生的队内签约数量")
    public String getDoctorSignPatientCount(@PathVariable("team_id") long teamId) {
        try {
            List<Doctor> members = memberService.getMembers(teamId);
            Map<String, Integer> counts = memberService.getMemberSigningCount(teamId, members);

            return write(200, "OK", "data", new JSONObject(counts));
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/teams/{team_id}/members/{doctor_code}/signing", method = RequestMethod.GET)
    @ApiOperation(value = "获取团队医生的队内签约患者列表")
    public String getDoctorSignPatients(@PathVariable("team_id") long teamId,
                                        @ApiParam(value = "健康管理师代码")
                                        @PathVariable("doctor_code") String healthDoctorCode,
                                        @RequestParam(value = "page", defaultValue = "0", required = false) int page,
                                        @RequestParam(value = "size", defaultValue = "0", required = false) int size) {
        try {
            page = page <= 0 ? 0 : page - 1;
            List<Patient> patients = memberService.getMemberSigningPatients(teamId, healthDoctorCode, page, size);
            List<Map<String, Object>> simplifiedPatients = new ArrayList<>();
            for (Patient patient : patients) {
                Map<String, Object> simplified = new HashMap<>();
                simplified.put("code", patient.getCode());
                simplified.put("name", patient.getName());
                simplified.put("sex", patient.getSex());
                simplified.put("photo", patient.getPhoto());
                simplified.put("age", IdCardUtil.getAgeForIdcard(patient.getIdcard()));

                List<SignPatientLabelInfo> diseases = signPatientLabelInfoService.getPatientLabelByLabelType(patient.getCode(), "3");

                List<String> simplifiedDisease = diseases.stream().map(SignPatientLabelInfo::getLabelName).collect(Collectors.toList());

                simplified.put("disease", simplifiedDisease);

                simplifiedPatients.add(simplified);
            }

            return write(200, "OK", "data", new JSONArray(simplifiedPatients));
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/teams/patient", method = RequestMethod.GET)
    @ApiOperation(value = "查询居民与当前医生的签约团队")
    public String getPatientAndDoctorTeam(@RequestParam String patient) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "居民不能为空");
            }

            JSONArray result = teamService.findPatientDoctorTeam(patient, getUID());

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    @RequestMapping(value = "/teams/info", method = RequestMethod.GET)
    @ApiOperation(value = "查询机构下的团队")
    public String getTeamInfo( @RequestParam(value = "teamId", defaultValue = "0", required = true) int teamId){
        try{
            JSONObject result =  teamService.getTeamInfo(teamId);
            return write(200,"查询成功","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");
        }
    }


    @RequestMapping(value = "/teams/{hospital}", method = RequestMethod.GET)
    @ApiOperation(value = "查询机构下的团队")
    public String getHospitalTeams(@PathVariable  String hospital){
        try{
            List<AdminTeam> teams =  teamService.findHospitalTeams(hospital);

            statisticsAllService.translateAdminTeamLeaderName(teams);
            return write(200,"查询成功","data",teams);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");
        }
    }
}
