package com.yihu.jw.base.endpoint.patient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yihu.jw.base.dao.servicePackage.ServicePackageRecordDao;
import com.yihu.jw.base.dao.servicePackage.ServicePackageSignRecordDao;
import com.yihu.jw.base.dao.sign.ArchiveDao;
import com.yihu.jw.base.dao.team.BaseTeamDao;
import com.yihu.jw.base.dao.team.WlyyPatientLabelDao;
import com.yihu.jw.base.util.ConstantUtils;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageRecordDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageSignRecordDO;
import com.yihu.jw.entity.base.team.BaseTeamDO;
import com.yihu.jw.entity.care.archive.ArchiveDO;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.label.WlyyPatientLabelDO;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.restmodel.base.patient.BasePatientVO;
import com.yihu.jw.restmodel.web.*;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.utils.date.DateUtil;
import com.yihu.utils.security.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 居民信息控制器
 *
 * @version <pre>
 * Author	Version		Date		Changes
 * litaohong 	1.0  		2018年08月31日 	Created
 *
 * </pre>
 * @since 1.
 */
@RestController
@RequestMapping(value = BaseRequestMapping.BasePatient.PREFIX)
@Api(value = "居民信息管理", description = "居民信息管理服务接口", tags = {"wlyy基础服务 - 居民信息管理服务接口"})
public class BasePatientEndpoint extends EnvelopRestEndpoint {

    @Autowired
    private BasePatientService basePatientService;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private ServicePackageSignRecordDao servicePackageSignRecordDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BaseTeamDao baseTeamDao;
    @Autowired
    private ServicePackageRecordDao servicePackageRecordDao;
    @Autowired
    private ArchiveDao archiveDao;
    @Autowired
    private WlyyPatientLabelDao patientLabelDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostMapping(value = BaseRequestMapping.BasePatient.CREATE)
    @ApiOperation(value = "创建")
    public Envelop create(
            @ApiParam(name = "jsonData", value = "Json数据", required = true)
            @RequestParam String jsonData) throws Exception {
       String msg = basePatientService.createPatient(jsonData);
       if(!StringUtils.equalsIgnoreCase(ConstantUtils.SUCCESS,msg)){
           return success(msg);
       }
        return failed(msg);
    }

    @PostMapping(value = BaseRequestMapping.BasePatient.DELETE)
    @ApiOperation(value = "删除")
    public Envelop delete(
            @ApiParam(name = "ids", value = "id串，中间用,分隔", required = true)
            @RequestParam(value = "ids") String ids) {
        basePatientService.delete(ids.split(","));
        return success("删除成功");
    }

    @PostMapping(value = BaseRequestMapping.BasePatient.UPDATE)
    @ApiOperation(value = "更新")
    public Envelop update(
            @ApiParam(name = "jsonData", value = "Json数据", required = true)
            @RequestParam String jsonData) throws Exception {
        String msg = basePatientService.updatePatient(jsonData);
        if(!StringUtils.equalsIgnoreCase(ConstantUtils.SUCCESS,msg)){
            return failed(msg);
        }
        return success(msg);
    }

    @GetMapping(value = BaseRequestMapping.BasePatient.getPatientById)
    @ApiOperation(value = "获取列表")
    public Envelop getPatientById(
            @ApiParam(name = "id", value = "居民id")
            @RequestParam(value = "id", required = true) String id) throws Exception {

        return success(basePatientService.getPatientById(id));
    }

    @GetMapping(value = "findPatientById")
    @ApiOperation(value = "根据id获取")
    public ObjEnvelop findPatientById(
            @ApiParam(name = "id", value = "居民id")
            @RequestParam(value = "id", required = true) String id) throws Exception {
        return ObjEnvelop.getSuccess("获取成功",basePatientService.findPatientById(id));
    }

    @GetMapping(value = BaseRequestMapping.BasePatient.PAGE)
    @ApiOperation(value = "获取分页")
    public PageEnvelop<BasePatientVO> page(
            @ApiParam(name = "fields", value = "返回的字段，为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器，为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序，规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        List<BasePatientDO> basePatients = basePatientService.search(fields, filters, sorts, page, size);
        int count = (int) basePatientService.getCount(filters);
        return success(basePatients, count, page, size, BasePatientVO.class);
    }

    @GetMapping(value = "pageByCondition")
    @ApiOperation(value = "获取分页")
    public PageEnvelop<BasePatientVO> pageByCondition(
            @ApiParam(name = "name", value = "手机号/姓名/身份证")
            @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "archiveStatus", value = "档案状态")
            @RequestParam(value = "archiveStatus", required = false) Integer archiveStatus,
            @ApiParam(name = "archiveType", value = "档案类型")
            @RequestParam(value = "archiveType", required = false) Integer archiveType,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        try {
            return basePatientService.pageByCondition(name, archiveType , archiveStatus, page, size);
        }catch (Exception e){
            return PageEnvelop.getError(e.getMessage(),-1);
        }

    }

    @GetMapping(value = BaseRequestMapping.BasePatient.LIST)
    @ApiOperation(value = "获取列表")
    public ListEnvelop<BasePatientVO> list(
            @ApiParam(name = "fields", value = "返回的字段，为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器，为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序，规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        List<BasePatientDO> basePatients = basePatientService.search(fields, filters, sorts);
        return success(basePatients, BasePatientVO.class);
    }

    @GetMapping(value = BaseRequestMapping.BasePatient.getBaseInfo)
    @ApiOperation(value = "获取居民基础信息列表")
    public MixEnvelop queryPatientBaseInfo(
            @ApiParam(name = "nameOrIdcard", value = "居民姓名或身份证")
            @RequestParam(value = "nameOrIdcard", required = false) String nameOrIdcard,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size,
            @ApiParam(name = "sorts", value = "排序，规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {

        return basePatientService.queryPatientBaseInfo(nameOrIdcard, page,size,sorts);

    }

    @PostMapping(value = "createArchive")
    @ApiOperation(value = "创建档案")
    public Envelop createArchive(
            @ApiParam(name = "jsonData", value = "Json数据", required = true)
            @RequestParam String jsonData) throws Exception {
        String msg = basePatientService.createArchive(jsonData);
        if(!StringUtils.equalsIgnoreCase(ConstantUtils.SUCCESS,msg)){
            return success(msg);
        }
        return failed(msg);
    }

    @PostMapping(value = "updateArchive")
    @ApiOperation(value = "更新档案")
    public Envelop updateArchive(
            @ApiParam(name = "jsonData", value = "Json数据", required = true)
            @RequestParam String jsonData) throws Exception {
        String msg = basePatientService.updateArchive(jsonData);
        if(!StringUtils.equalsIgnoreCase(ConstantUtils.SUCCESS,msg)){
            return failed(msg);
        }
        return success(msg);
    }


    /**
     *   如果添加失败，注释MultipartConfig配置
     *   如果导入失败，将Excel修改为97-2003版本.xls
     *   签约服务包id固定
     *   签约日期 开始时间为当前时间，结束时间为2023-12-31 23:59:59
     *   patientLabelDO.setLabelType("1");  居民标签类型 固定为能力完好
     *   patientLabelDO.setLabelCode("0");  居民标签类型 固定为能力完好
     *   姓名	性别	年龄	身份证号	      联系方式	   小区	            地址	                 签约团队	        能力类型
     * 沈xxx	女	    88	330103xxxxxxxx0720	1525xxxx711	朝晖九区	朝晖九区10幢4单元103	    虹园/稻香园服务团队	    能力完好
     * 沈xxx	女	    86	330103xxxxxxxx0720	1525xxxx711	朝晖九区	朝晖九区天盛居４幢1202室	  大木桥服务团队	    能力完好
     * @return
     */
    @RequestMapping(value = "/open/importPatientFromTmp" ,method = RequestMethod.POST)
    @ResponseBody
    public ObjEnvelop importPatientFromTmp() {
        Calendar cal = Calendar.getInstance();
        int year= 100;
        List correctLs = new ArrayList<>();
        List idcardList = new ArrayList<>();
        Map<String, String> errorMsgMap = new HashMap<>();
        try {
            String sql = "select * from patient_tmp";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);

            String name;//用户姓名
            String sex; //性别
            String age; //年龄
            String idcard;  //身份证号
            String mobile;  //联系方式
            String residentialArea; //居住小区
            String address; //居住地址
            String signTeam; //签约团队
            String label; //能力类型
            for (Map<String,Object> map:list) {
                BasePatientDO basePatientVO = new BasePatientDO();
                JSONObject infoMap = new JSONObject();
                name = map.get("name")+"";    //0 用户姓名
                sex = map.get("sex")+"";  //1 性别
                age = map.get("age")+"";   //2 年龄
                idcard = map.get("idcard")+""; //3 身份证号
                mobile = map.get("mobile")+"";  //4 联系方式
                residentialArea = map.get("area")+""; //5 居住小区
                address = map.get("address")+""; //6 居住地址
                signTeam = map.get("sign")+""; //签约团队
                label = map.get("label")+""; //能力类型
                if (StringUtils.isBlank(idcard)){
                    continue;
                }
                if (StringUtils.isBlank(name)){
                    errorMsgMap.put(idcard,"姓名不能为空");
                    continue;
                }
                if (basePatientService.findByIdCard(idcard)){
                    errorMsgMap.put(idcard,"身份证号重复");
                    continue;
                }
                if (StringUtils.isBlank(sex)){
                    sex = "3";
                } else {
                    if (sex.equals("男")) {
                        sex = "1";
                    } else {
                        sex = "2";
                    }
                }
                if (StringUtils.isBlank(signTeam)){
                    errorMsgMap.put(idcard,"签约团队不能为空");
                    continue;
                }

                if (StringUtils.isBlank(label)){
                    errorMsgMap.put(idcard,"能力类型不能为空");
                    continue;
                }
                basePatientVO.setAddress(address);
                basePatientVO.setDel("1");
                basePatientVO.setEnabled(1);
                basePatientVO.setIdcard(idcard);
                basePatientVO.setSex(new Integer(sex));
                basePatientVO.setName(name);
                basePatientVO.setMobile(mobile);
                basePatientVO.setArchiveStatus(3);
                basePatientVO.setArchiveType(1); //默认添加老人
                String pw = idcard.substring(idcard.length()-6);
                String salt = UUID.randomUUID().toString().substring(0,5);
                basePatientVO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                basePatientVO.setSalt(salt);
                basePatientVO.setResidentialArea(residentialArea);
                infoMap.put("idcard",idcard);
                infoMap.put("signTeam",signTeam);
                infoMap.put("label",label);
                correctLs.add(basePatientVO);
                idcardList.add(infoMap);
            }
            basePatientDao.save(correctLs);
            String patient= "";
            /**
             * 添加签约数据
             */
            if (idcardList.size() > 0) {
                for (int i=0;i<idcardList.size();i++) {
                    ServicePackageSignRecordDO signRecordDO = new ServicePackageSignRecordDO();
                    BasePatientDO basePatientVO = new BasePatientDO();
                    try {
                        idcard = retOne(idcardList.get(i).toString(),"idcard").toString();
                        signTeam = retOne(idcardList.get(i).toString(),"signTeam").toString();
                        label = retOne(idcardList.get(i).toString(),"label").toString();
                        basePatientVO = basePatientDao.findByIdcardAndDel(idcard,"1");
                        if (basePatientVO == null) {
                            errorMsgMap.put(idcard,"居民信息获取失败");
                            continue;
                        }
                        patient = basePatientVO.getId();
                        name = basePatientVO.getName();
                        signRecordDO.setPatient(patient);
                        signRecordDO.setName(name);
                        signRecordDO.setStatus(1);
                        signRecordDO.setStartTime(new Date());
                        cal.add(Calendar.YEAR,year);
                        signRecordDO.setEndTime(cal.getTime());
                        BaseTeamDO teamDO = baseTeamDao.findByName(signTeam);
                        if (teamDO == null) {
                            errorMsgMap.put(idcard,"团队信息获取失败");
                            continue;
                        }
                        BaseDoctorDO doctorDO = baseDoctorDao.findById(teamDO.getLeaderCode());
                        if (doctorDO == null) {
                            errorMsgMap.put(idcard,"医生信息获取失败");
                            continue;
                        }
                        signRecordDO.setSignDoctor(doctorDO.getId());
                        signRecordDO.setSignDoctorName(doctorDO.getName());
                        signRecordDO = servicePackageSignRecordDao.save(signRecordDO);
                        ServicePackageRecordDO packageRecordDO = new ServicePackageRecordDO();
                        packageRecordDO.setSignId(signRecordDO.getId());
                        packageRecordDO.setServicePackageId("8a92aba97b48824a017b56c5ee710019");
                        packageRecordDO.setPatient(patient);
                        packageRecordDO.setCreateTime(new Date());
                        packageRecordDO.setTeamCode(teamDO.getId());
                        servicePackageRecordDao.save(packageRecordDO);
                        //建档状态
                        ArchiveDO archiveDO = new ArchiveDO();
                        archiveDO.setCreateTime(new Date());
                        archiveDO.setArchiveOperatorName(doctorDO.getName());
                        archiveDO.setDoctorCode(doctorDO.getId());
                        archiveDO.setPatient(patient);
                        archiveDO.setSickName(name);
                        archiveDO.setIdcard(idcard);
                        archiveDO.setSignStatus(1);
                        archiveDao.save(archiveDO);
                        //居民标签
                        WlyyPatientLabelDO patientLabelDO = new WlyyPatientLabelDO();
                        patientLabelDO.setCzrq(new Date());
                        patientLabelDO.setLabelType("1");
                        patientLabelDO.setPatient(patient);
                        patientLabelDO.setLabelCode("0");
                        patientLabelDO.setLabelName(label);
                        patientLabelDao.save(patientLabelDO);
                        basePatientVO.setSignStatus(1);
                        basePatientDao.save(basePatientVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }


            //包装导入结果（导入成功数量、错误对象集合）
            Map<String, Object> map = new HashMap<>();
            map.put("successNum", correctLs.size());
            map.put("failedNum", list.size() - correctLs.size() );
            map.put("errorData", JSON.toJSONString(errorMsgMap, SerializerFeature.WriteMapNullValue));
            System.out.println(map);
            return ObjEnvelop.getSuccess("获取成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return failedObjEnvelopException(e);
        }
    }

    public Object retOne(String str,String name){
        JSONObject object = JSONObject.parseObject(str);
        return object.get(""+name+"");
    }

}
