package com.jojubanking.boot.module.system.controller.app.xytjinfo;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.jojubanking.boot.framework.common.enums.CommonStatusEnum;
import com.jojubanking.boot.framework.common.pojo.CommonResult;
import com.jojubanking.boot.framework.common.pojo.PageResult;
import com.jojubanking.boot.framework.operatelog.core.annotations.OperateLog;
import com.jojubanking.boot.module.infra.service.file.FileService;
import com.jojubanking.boot.module.system.controller.admin.childitem.vo.ChilditemPageReqVO;
import com.jojubanking.boot.module.system.controller.admin.deptxq.vo.DeptXqListReqVO;
import com.jojubanking.boot.module.system.controller.admin.deptxq.vo.DeptXqSimpleRespVO;
import com.jojubanking.boot.module.system.controller.admin.item.vo.ItemExportReqVO;
import com.jojubanking.boot.module.system.controller.admin.item.vo.ItemRespVO;
import com.jojubanking.boot.module.system.controller.admin.mzdm.vo.MzdmExportReqVO;
import com.jojubanking.boot.module.system.controller.admin.mzdm.vo.MzdmPageReqVO;
import com.jojubanking.boot.module.system.controller.admin.order.vo.OrderExportReqVO;
import com.jojubanking.boot.module.system.controller.admin.refundapply.vo.RefundApplyCreateReqVO;
import com.jojubanking.boot.module.system.controller.admin.refundapply.vo.RefundApplyExportReqVO;
import com.jojubanking.boot.module.system.controller.admin.student.vo.StudentCreateReqVO;
import com.jojubanking.boot.module.system.controller.admin.student.vo.StudentExportReqVO;
import com.jojubanking.boot.module.system.controller.admin.student.vo.StudentRespVO;
import com.jojubanking.boot.module.system.controller.admin.student.vo.StudentUpdateReqVO;
import com.jojubanking.boot.module.system.controller.admin.xymain.vo.xyMainCreateReqVO;
import com.jojubanking.boot.module.system.controller.admin.xymain.vo.xyMainExportReqVO;
import com.jojubanking.boot.module.system.controller.admin.xymain.vo.xyMainRespVO;
import com.jojubanking.boot.module.system.controller.admin.xymain.vo.xyMainUpdateReqVO;
import com.jojubanking.boot.module.system.controller.admin.xyrw.vo.XyrwRespVO;
import com.jojubanking.boot.module.system.controller.app.xytjinfo.vo.*;
import com.jojubanking.boot.module.system.convert.deptxq.DeptXqConvert;
import com.jojubanking.boot.module.system.convert.item.ItemConvert;
import com.jojubanking.boot.module.system.convert.student.StudentConvert;
import com.jojubanking.boot.module.system.convert.xymain.xyMainConvert;
import com.jojubanking.boot.module.system.convert.xyrw.XyrwConvert;
import com.jojubanking.boot.module.system.dal.dataobject.childitem.ChilditemDO;
import com.jojubanking.boot.module.system.dal.dataobject.deptxq.DeptXqDO;
import com.jojubanking.boot.module.system.dal.dataobject.item.ItemDO;
import com.jojubanking.boot.module.system.dal.dataobject.mzdm.MzdmDO;
import com.jojubanking.boot.module.system.dal.dataobject.order.OrderDO;
import com.jojubanking.boot.module.system.dal.dataobject.refundapply.RefundApplyDO;
import com.jojubanking.boot.module.system.dal.dataobject.student.StudentDO;
import com.jojubanking.boot.module.system.dal.dataobject.xymain.xyMainDO;
import com.jojubanking.boot.module.system.dal.dataobject.xyrw.XyrwDO;
import com.jojubanking.boot.module.system.framework.tjfiles.TjfilesProperties;
import com.jojubanking.boot.module.system.service.childitem.ChilditemService;
import com.jojubanking.boot.module.system.service.deptxq.DeptXqService;
import com.jojubanking.boot.module.system.service.item.ItemService;
import com.jojubanking.boot.module.system.service.mzdm.MzdmService;
import com.jojubanking.boot.module.system.service.order.OrderService;
import com.jojubanking.boot.module.system.service.refundapply.RefundApplyService;
import com.jojubanking.boot.module.system.service.student.StudentService;
import com.jojubanking.boot.module.system.service.xymain.xyMainService;
import com.jojubanking.boot.module.system.service.xyrw.XyrwService;
import com.jojubanking.boot.module.system.util.xytj.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.DecimalFormat;
import java.util.*;

import static com.jojubanking.boot.framework.common.pojo.CommonResult.error;
import static com.jojubanking.boot.framework.common.pojo.CommonResult.success;
import static com.jojubanking.boot.module.system.enums.ErrorCodeConstants.*;

@Api(tags = "APP - 机构信息")
@RestController
@RequestMapping("/member/dept-info")
@Validated
@Slf4j
public class AppDeptInfoController {
    @Resource
    private DeptXqService deptXqService;

    @Resource
    private xyMainService xyMainService;
    @Resource
    private ItemService itemService;
    @Resource
    private ChilditemService childitemService;
    @Resource
    private StudentService studentService;

    @Resource
    private XyrwService xyrwService;
    @Resource
    private MzdmService mzdmService;

    @Resource
    private RefundApplyService refundApplyService;
    @Resource
    private OrderService orderService;
    @Resource
    private TjfilesProperties tjfilesProperties;

    @Resource
    private FileService fileService;

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件附件", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "path", value = "文件路径", example = "jojuyuanma.png", dataTypeClass = String.class)
    })
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
    public CommonResult<String> uploadFile(@RequestParam("file") MultipartFile file,
                                           @RequestParam(value = "path", required = false) String path) throws Exception {
        return success(fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream())));
    }


    @PostMapping("/createRefund")
    @ApiOperation("创建就诊卡退费申请")
    public CommonResult<Long> createRefundApply(@Valid @RequestBody RefundApplyCreateReqVO createReqVO) {

        //查询姓名+身份证号相同的资料
        RefundApplyExportReqVO exportReqVO = new RefundApplyExportReqVO();
        exportReqVO.setRefname(createReqVO.getRefname());
        exportReqVO.setRefidcard(createReqVO.getRefidcard());
        List<RefundApplyDO> list = refundApplyService.getRefundApplyList(exportReqVO);
        if(list.size() != 0){
            return error(REFUND_APPLY_SYSTEM_CARDNO_ERROR);
        }
        return success(refundApplyService.createRefundApply(createReqVO));
    }
    @PostMapping("/create")
    @ApiOperation("创建体检信息")
    public CommonResult<String> createxyMain(@Valid @RequestBody StudentCreateReqVO createReqVO) throws Exception {
        String cardtype;
        //每个身份证只能一条记录
        //第一步查档
        HashMap<Object,Object> map = WSUtil.getPatient(createReqVO.getNationId(), "1");
        String errCode = StringDUtil.changeNullToEmpty(map.get("errCode"));

        if("0".equals(errCode)) {
            HashMap<Object,Object> patientMap = (HashMap<Object, Object>) ((List)map.get("list")).get(0);

            if(patientMap.get("brzt").equals("R")){
                log.info("new user");
                //第二步如果新用户，则自动身份证建档

                //获取民族代码
                MzdmExportReqVO exportReqVO = new MzdmExportReqVO();
                exportReqVO.setName(createReqVO.getSqName());
                List<MzdmDO> list = mzdmService.getMzdmList(exportReqVO);
                String mzdm = "";
                if(list.size() != 0){
                    mzdm = list.get(0).getMzdm().toString();
                }
                HashMap<Object,Object> map1 =  WSUtil.addUser(createReqVO.getName(), createReqVO.getNationId(),
                        createReqVO.getMobile(), mzdm);
                String errCode1 = StringDUtil.changeNullToEmpty(map1.get("errCode"));
                if("0".equals(errCode1)) {
                    HashMap<Object,Object> newpatientMap = (HashMap<Object, Object>) ((List)map1.get("list")).get(0);
                    createReqVO.setPatid(newpatientMap.get("patid").toString());
                    //cardtype = newpatientMap.get("cardtype").toString();
                    cardtype = "1";
                }else {
                    return error(TJ_SYSTEM_CREATEUSR_ERROR);
                }

            }else{
                log.info("exist user");
                createReqVO.setPatid(patientMap.get("patid").toString());
                cardtype = patientMap.get("cardtype").toString();
            }

        }else {
            return error(TJ_SYSTEM_CARDNO_ERROR);
        }
        //第三步更新学生信息
        //return success(xyMainService.createxyMain(createReqVO));
        //return success(studentService.createStudent(createReqVO));
        StudentUpdateReqVO updateReqVO = new StudentUpdateReqVO();
        updateReqVO.setPatid(createReqVO.getPatid());
        updateReqVO.setOpenid(createReqVO.getOpenid());

        //从身份证号计算年龄和性别
        String idCardNumber = createReqVO.getNationId();
        IDCardParser parser = new IDCardParser(idCardNumber);
        parser.parse();

        String birthDate = parser.getBirthDate();
        int gender = parser.getGender();

        AgeCalculator calculator = new AgeCalculator(birthDate);
        int age = calculator.calculateAge();

        updateReqVO.setAge(Long.valueOf(age));
        updateReqVO.setSex(gender);
        updateReqVO.setName(createReqVO.getName());
        updateReqVO.setId(createReqVO.getDeptId()); //deptid 已经不用，给id复用一下
        updateReqVO.setNationId(createReqVO.getNationId());

        studentService.updateStudent(updateReqVO);
        return success(cardtype);
    }

    @PostMapping("/update")
    @ApiOperation("更新体检信息")
    public CommonResult<Boolean> updatexyMain(@Valid @RequestBody StudentUpdateReqVO updateReqVO) {
        //已有缴费记录不允许修改

//        xyMainService.updatexyMain(updateReqVO);
        studentService.updateStudent(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除体检信息")
    public CommonResult<Boolean> deletexyMain(@RequestParam Long id) {
        ////已有缴费记录不允许删除
//        Long xid = Long.getLong(id);
        //xyMainService.deletexyMain(id);
        studentService.deleteStudent(id);
        return success(true);
    }

    @GetMapping("/list-simple-student")
    @ApiOperation("获得体检信息")
    public CommonResult<List<studentJfListVO>> getSimplexyMain(@RequestParam("openid") String openid, @RequestParam("batchno") String batchno) {
        //通过家长的openid 获取体检人信息
//        StudentExportReqVO reqVO = new StudentExportReqVO();
//        reqVO.setOpenid(openid);
        List<studentJfListVO> list = studentService.getStudentListSimple(openid, batchno);

        //通过list中的patid去order表查orderno和paystatus
        for(int i = 0; i < list.size(); i++){
            String patid = list.get(i).getPatid();

            OrderExportReqVO exportReqVO = new OrderExportReqVO();
            exportReqVO.setPatid(patid);
            List<OrderDO> lstOrder = orderService.getOrderList(exportReqVO);
            if(lstOrder.size() != 0){
                for(int j = 0; j < lstOrder.size(); j++){
                    if(lstOrder.get(j).getPaystatus() != null) {
                        if (lstOrder.get(j).getPaystatus().equals("0") && !lstOrder.get(j).getOrderno().equals("")) {
                            log.info("tj 查询订单号:" + lstOrder.get(j).getOrderno());
                            //paystatus 如果是0，就去微信复核一下，如果已支付就更新student和order表的标识，并更新list的feeflag
                            String ipport = tjfilesProperties.getIpport();
                            JSONObject jsonParam = new JSONObject();
                            jsonParam.put("out_trade_no", lstOrder.get(j).getOrderno());
                            String res = HttpClientUtil.doPost(ipport + "/api/wxpay/findWxPayResult", jsonParam);
                            log.info("tj 查询订单号返回:" + res);
                            JSONObject jsonResult = JSONObject.parseObject(res);
                            if (jsonResult.get("errCode").equals("0")) {
                                JSONObject data = jsonResult.getJSONObject("data");
                                if (data.get("tradeState").equals("SUCCESS")) {
                                    log.info("确认该学生已付款");
                                    list.get(i).setFeeflag("1");

                                    //更新student表的feeflag和order表的paystatus
                                    //根据收据号更新支付状态
                                    //获取下园批次，只取开始状态的批次
                                    XyrwListReqVO xyrwListReqVO = new XyrwListReqVO();
                                    xyrwListReqVO.setBatchStatus(1);
                                    List<XyrwDO> listXyrw = xyrwService.getXyrwSimpleList(xyrwListReqVO);

                                    OrderDO orderDO = new OrderDO();
                                    orderDO.setOrderno(lstOrder.get(j).getOrderno());

                                    orderDO.setPaystatus("1");
                                    orderService.updateOrderByNotify(orderDO);

                                    //更新学生表的缴费标识
                                    StudentDO studenDO = new StudentDO();
                                    studenDO.setOrderno(lstOrder.get(j).getOrderno());
                                    studenDO.setBatchno(listXyrw.get(0).getBatchno());

                                    studenDO.setFeeflag(1);
                                    studentService.updateOrderByNotify(studenDO);
                                }
                            }
                        } else {
                            log.info("该学生已付款");
                        }
                    }
                    else{
                        log.info("该学生还无订单");
                    }
                }
            }else{
                log.info("该学生还未选项目");
            }
        }



        return success(list);
    }
    @GetMapping("/list-init-student")
    @ApiOperation("获得体检信息")
    public CommonResult<StudentDO> getInitStudent(@RequestParam("nationid") String nationid, @RequestParam("batchno") String batchno) {
        //通过家长的openid 获取体检人信息
//        StudentExportReqVO reqVO = new StudentExportReqVO();
//        reqVO.setOpenid(openid);
        StudentDO list = studentService.getStudentListInit(nationid, batchno);

        return success(list);
    }

    @GetMapping("/list-student")
    @ApiOperation("获得体检信息列表")
    public CommonResult<List<xyMainRespVO>> getxyMainList(@RequestParam Long deptid) {
        xyMainExportReqVO reqVO = new xyMainExportReqVO();
        reqVO.setDeptId(deptid);
        List<xyMainDO> list = xyMainService.getxyMainListSimple(reqVO);
        return success(xyMainConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/list-xyrw")
    @ApiOperation("获得批次信息列表")
    public CommonResult<List<XyrwRespVO>> getXyrwList() {
        //获取下园批次，只取开始状态的批次
        XyrwListReqVO xyrwListReqVO = new XyrwListReqVO();
        xyrwListReqVO.setBatchStatus(1);
        List<XyrwDO> list = xyrwService.getXyrwSimpleList(xyrwListReqVO);
        return success(XyrwConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获取部门精简信息列表", notes = "只包含被开启的部门，主要用于前端的下拉选项")
    public CommonResult<List<DeptXqSimpleRespVO>> getSimpleDepts(@RequestParam Long parentid) {
        // 获得部门列表，只要开启状态的
        DeptXqtjListReqVO reqVO = new DeptXqtjListReqVO();
        reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
        reqVO.setParentId(parentid);
        List<DeptXqDO> list = deptXqService.getSimpleXqtjDepts(reqVO);
        // 排序后，返回给前端
        list.sort(Comparator.comparing(DeptXqDO::getSort));
        return success(DeptXqConvert.INSTANCE.convertList03(list));
    }


    @GetMapping("/list-item")
    @ApiOperation("获得检查项目列表")
    public CommonResult<List<ItemRespVO>> getItemList(@RequestParam String packageno, @RequestParam String patid) {
        DecimalFormat df = new DecimalFormat("0.00");
        Double packnumber = 0.00;

        //获取下园批次，只取开始状态的批次
        XyrwListReqVO xyrwListReqVO = new XyrwListReqVO();
        xyrwListReqVO.setBatchStatus(1);
        List<XyrwDO> listXyrw = xyrwService.getXyrwSimpleList(xyrwListReqVO);

        //使用packageno 是否非0来获取不同列表
        ItemListReqVO itemListReqVO = new ItemListReqVO();
        itemListReqVO.setPackageno(packageno);

        //如果是package，更新itemno为明细,后期还要优化
        String packContent = "";
        if(packageno.equals("666")){
            ItemListReqVO pageReqVO = new ItemListReqVO();
            pageReqVO.setPackageno(packageno);
            List<ChilditemDO> list1 = childitemService.getSimpleItemList(pageReqVO);
            for(int i=0; i<list1.size(); i++){
                packContent = packContent.concat(list1.get(i).getItemname());
                packnumber = packnumber + Double.parseDouble(list1.get(i).getItemprice())/100;

                if(i != list1.size() -1 )
                    packContent = packContent.concat("、");
            }
        }

        List<ItemDO> list = itemService.getSimpleItemList(patid, packageno, listXyrw.get(0).getBatchno());
        for(int i=0; i<list.size(); i++){
            Double number = Double.parseDouble(list.get(i).getItemprice())/100;
            list.get(i).setItemprice(df.format(number));
            if(list.get(i).getPackageno().equals("666")){
                list.get(i).setItemno(packContent);
                list.get(i).setItemprice(df.format(packnumber));
            }
        }

        //基础和可选分开来，为了前端显示
        //增加showflag，用来控制前端是否禁用
        ItemExportReqVO itemExportReqVO = new ItemExportReqVO();
        itemExportReqVO.setPackageno(packageno);
        List<ItemDO> listBase = itemService.getItemList(itemExportReqVO);
        for(int j=0; j<listBase.size(); j++){
            //默认设置为不显示,1 - 不显示，0 - 显示
            listBase.get(j).setShowflag(1);
            Double number = Double.parseDouble(listBase.get(j).getItemprice())/100;
            listBase.get(j).setItemprice(df.format(number));

            for(int k=0; k<list.size(); k++) {
                if (listBase.get(j).getItemname().equals(list.get(k).getItemname())) {
                    //如果项目不包含在订单表里面，则设置为显示
                    listBase.get(j).setShowflag(0);
//                    listBase.get(j).setItemprice(list.get(k).getItemprice());
//                    listBase.get(j).setItemno(list.get(k).getItemno());
                }
            }
            if(listBase.get(j).getPackageno().equals("666")){
                listBase.get(j).setItemno(packContent);
                listBase.get(j).setItemprice(df.format(packnumber));
            }
        }

        return success(ItemConvert.INSTANCE.convertList(listBase));
    }


    /**
     * @description 建档(患者基本信息登记)
     */
    @RequestMapping("/his/addUser")
    public HashMap<Object,Object> addUser(@RequestParam String hzxm, @RequestParam String sfzh,
                                          @RequestParam String lxdh, @RequestParam String mzdm) throws Exception {
        return WSUtil.addUser(hzxm, sfzh, lxdh, mzdm);
    }

}
