package com.ywt.alipaympapi.web.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.util.generic.models.AlipayOpenApiGenericResponse;
import com.ywt.alipaympapi.core.utils.BizUtil;
import com.ywt.alipaympapi.core.utils.CheckUtil;
import com.ywt.alipaympapi.core.utils.Checker;
import com.ywt.alipaympapi.core.utils.StringHelper;
import com.ywt.alipaympapi.models.Constants;
import com.ywt.alipaympapi.models.auth.AlipayMpCfg;
import com.ywt.alipaympapi.models.dev.*;
import com.ywt.core.Anonymous;
import com.ywt.core.exception.AppMessageException;
import com.ywt.model.Code;
import com.ywt.model.PageVO;
import com.ywt.model.Pagination;
import com.ywt.model.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Walker
 * Created on 2022/9/19
 */
@Slf4j
@RestController("/dev")
@RequestMapping({"/dev"})
public class DevController {
    @Anonymous(enable = true)
    @RequestMapping(value = {"/eptPageList"}, method = RequestMethod.POST)
    public @ResponseBody ResponseVO<PageVO<String>> eptPageList() {
        Pagination pagination = new Pagination(1, 1, 0);
        PageVO<String> page = new PageVO<>(pagination, new ArrayList<>());
        return ResponseVO.success(page);
    }

    @Anonymous(enable = true)
    @RequestMapping(value = {"/eptList"}, method = RequestMethod.POST)
    public @ResponseBody ResponseVO<List<String>> eptList() {
        return ResponseVO.success(new ArrayList<>());
    }

    /**
     * <a href="https://opendocs.alipay.com/pre-apis/02x1v3">医疗行业医院数据上传</a>
     * 单次上传最多支持100条记录，如果超过请分批上传
     */
    @Anonymous(enable = true)
    @RequestMapping(value = {"/uploadHospInfo"}, method = RequestMethod.POST)
    public @ResponseBody ResponseVO<String> uploadHospInfo(@RequestBody UploadInfoReq<UploadHospitalInfo> data) {
        try {
            int terminal = data.getTerminal();
            AlipayMpCfg cfg = BizUtil.getCfg(terminal);
            String appId = cfg.getAppId();
            String isvPid = cfg.getIsvPid();
            CheckUtil.ensureNotEmpty(appId, "appId 不能为空");
            CheckUtil.ensureNotEmpty(isvPid, "isvPid 不能为空");
            Map<String, Object> bizParam = new HashMap<>();
            bizParam.put("hospital_list", data.getList().stream()
                    .map(d -> {
                        Map<String, String> map = new HashMap<>();
                        map.put("hospital_name", Checker.getStringValue(d.getHospitalName()));
                        map.put("hospital_id", Checker.getStringValue(d.getHospitalId()));
                        map.put("hospital_alias", Checker.getStringValue(d.getHospitalAlias()));
                        map.put("hospital_province", Checker.getStringValue(d.getHospitalProvince()));
                        map.put("hospital_city", Checker.getStringValue(d.getHospitalCity()));
                        map.put("hospital_district", Checker.getStringValue(d.getHospitalDistrict()));
                        map.put("hospital_addr", Checker.getStringValue(d.getHospitalAddr()));
                        map.put("hospital_lgt", Checker.getStringValue(d.getHospitalLgt()));
                        map.put("hospital_lat", Checker.getStringValue(d.getHospitalLat()));
                        map.put("hospital_type", Checker.getStringValue(d.getHospitalType()));
                        map.put("hospital_grade", Checker.getStringValue(d.getHospitalGrade()));
                        map.put("hospital_logo", Checker.getStringValue(d.getHospitalLogo()));
                        return map;
                    })
                    .collect(Collectors.toList()));
            bizParam.put("isv_pid", isvPid);
            bizParam.put("request_id", UUID.randomUUID().toString());
            log.info("DevController#uploadHospInfo Request: {}", bizParam);
            BizUtil.initAlipayEasySdk(terminal);
            AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute("alipay.commerce.medical.industrydata.hospital.upload", null, bizParam);
            log.info("DevController#uploadHospInfo Response: {}", JSON.toJSONString(response));
            if (Constants.ALIPAY_SUCCESS_CODE.equals(response.getCode()))
                return ResponseVO.success(Checker.getStringValue(response.getMsg()));
            return ResponseVO.fail(Code.RESP_CODE_PARAM_ERROR, StringHelper.isNullOrEmpty(response.getSubMsg()) ? Checker.getStringValue(response.getMsg()) : response.getSubMsg());
        } catch (AppMessageException e) {
            log.error("DevController#uploadHospInfo(): {}", e.getMessage());
            return ResponseVO.fail(Code.RESP_CODE_PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            log.error("DevController#uploadHospInfo(): {}", e.getMessage(), e);
            return ResponseVO.fail(Code.RESP_CODE_APP_EXCEPTION, e.getMessage());
        }
    }

    /**
     * <a href="https://opendocs.alipay.com/pre-apis/02x1v2">医院科室信息上传接口</a>
     * 单次上传最多支持100条记录，如果超过请分批上传
     */
    @Anonymous(enable = true)
    @RequestMapping(value = {"/uploadDeptInfo"}, method = RequestMethod.POST)
    public @ResponseBody ResponseVO<String> uploadDeptInfo(@RequestBody UploadInfoReq<UploadDeptInfo> data) {
        Map<String, Object> bizParam = new HashMap<>();
        try {
            int terminal = data.getTerminal();
            AlipayMpCfg cfg = BizUtil.getCfg(terminal);
            String appId = cfg.getAppId();
            String isvPid = cfg.getIsvPid();
            CheckUtil.ensureNotEmpty(appId, "appId 不能为空");
            CheckUtil.ensureNotEmpty(isvPid, "isvPid 不能为空");
            List<UploadDeptInfo> list = data.getList();
            if (Checker.isNone(list)) throw new AppMessageException("数据为空");
            bizParam.put("department_list", list.stream()
                    .map(d -> {
                        Map<String, String> map = new HashMap<>();
                        String deptCode = Checker.getStringValue(d.getDeptCode());
                        String departmentName = Checker.getStringValue(d.getDepartmentName());
                        String departmentId = Checker.getStringValue(d.getDepartmentId());
                        String departmentType = Checker.getStringValue(d.getDepartmentType());
                        String hospitalName = Checker.getStringValue(d.getHospitalName());
                        String subHospitalName = Checker.getStringValue(d.getSubHospitalName());
                        String hospitalId = Checker.getStringValue(d.getHospitalId());
                        map.put("department_name", departmentName);
                        map.put("department_id", departmentId);
                        map.put("department_type", departmentType); // 一级二级科室
                        map.put("hospital_name", hospitalName); // 科室所属医院名称
                        String pathParam = "";
                        try {
                            pathParam = URLEncoder.encode(String.format("?depCode=%s&departmentId=%s&header=show&hospitalId=%s&pageType=hospital-num-source&title=%s（%s）",
                                    deptCode, departmentId, hospitalId, departmentName, subHospitalName), "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            log.error("DevController#uploadDeptInfo UnsupportedEncodingException: {}", e.getMessage(), e);
                        }
                        map.put("department_url", String.format("alipays://platformapi/startapp?appId=%s&page=antbuilder/industry/hospitalV2/pages/page-no-pull/index%s", appId, pathParam)); // 科室挂号服务跳转
                        return map;
                    })
                    .collect(Collectors.toList()));
            bizParam.put("isv_pid", isvPid);
            bizParam.put("request_id", UUID.randomUUID().toString());
            log.info("DevController#uploadDeptInfo Request: {}", bizParam);
            BizUtil.initAlipayEasySdk(terminal);
            AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute("alipay.commerce.medical.industrydata.department.upload", null, bizParam);
            log.info("DevController#uploadDeptInfo Response: {}", JSON.toJSONString(response));
            if (Constants.ALIPAY_SUCCESS_CODE.equals(response.getCode()))
                return ResponseVO.success(Checker.getStringValue(response.getMsg()));
            return ResponseVO.fail(Code.RESP_CODE_PARAM_ERROR, StringHelper.isNullOrEmpty(response.getSubMsg()) ? Checker.getStringValue(response.getMsg()) : response.getSubMsg());
        } catch (AppMessageException e) {
            log.error("DevController#uploadDeptInfo(): {}", e.getMessage());
            return ResponseVO.fail(Code.RESP_CODE_PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            log.error("DevController#uploadDeptInfo(): {}", e.getMessage(), e);
            return ResponseVO.fail(Code.RESP_CODE_APP_EXCEPTION, e.getMessage());
        }
    }
    /**
     * <a href="https://opendocs.alipay.com/pre-apis/02x1v1">医生信息上传接口</a>
     * 单次上传最多支持100条记录，如果超过请分批上传
     */
    @Anonymous(enable = true)
    @RequestMapping(value = {"/uploadDoctorInfo"}, method = RequestMethod.POST)
    public @ResponseBody ResponseVO<String> uploadDoctorInfo(@RequestBody UploadInfoReq<UploadDoctorInfo> data) {
        Map<String, Object> bizParam = new HashMap<>();
        try {
            int terminal = data.getTerminal();
            AlipayMpCfg cfg = BizUtil.getCfg(terminal);
            String appId = cfg.getAppId();
            String isvPid = cfg.getIsvPid();
            CheckUtil.ensureNotEmpty(appId, "appId 不能为空");
            CheckUtil.ensureNotEmpty(isvPid, "isvPid 不能为空");
            List<UploadDoctorInfo> list = data.getList();
            if (Checker.isNone(list)) throw new AppMessageException("数据为空");
            bizParam.put("doctor_list", list.stream()
                    .map(d -> {
                        Map<String, String> map = new HashMap<>();
                        String doctorName = Checker.getStringValue(d.getDoctorName());
                        String doctorId = Checker.getStringValue(d.getDoctorId());
                        String doctorTitle = Checker.getStringValue(d.getDoctorTitle());
                        String doctorIntro = Checker.getStringValue(d.getDoctorIntro());
                        String doctorSpecialty = Checker.getStringValue(d.getDoctorSpecialty());
                        String doctorCode = Checker.getStringValue(d.getDoctorCode());
                        String deptId = Checker.getStringValue(d.getDeptId());
                        String deptCode = Checker.getStringValue(d.getDeptCode());
                        String hospitalId = Checker.getStringValue(d.getHospitalId());
                        map.put("doctor_name", doctorName);
                        map.put("doctor_id", doctorId);
                        map.put("academic_title", doctorTitle);
                        map.put("doctor_introduction", doctorIntro);
                        map.put("skilled_disease_desc", doctorSpecialty);
                        String pathParam = "";
                        try {
                            pathParam = URLEncoder.encode(String.format("?depCode=%s&depId=%s&doctorCode=%s&doctorId=%s&header=show&hospitalId=%s&pageType=doctor-page&title=医生主页",
                                    deptCode, deptId, doctorCode, doctorId, hospitalId), "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            log.error("DevController#uploadDoctorInfo UnsupportedEncodingException: {}", e.getMessage(), e);
                        }
                        map.put("doctor_url", String.format("alipays://platformapi/startapp?appId=%s&page=antbuilder/industry/hospitalV2/pages/page-no-pull/index%s", appId, pathParam));
                        return map;
                    })
                    .collect(Collectors.toList()));
            bizParam.put("isv_pid", isvPid);
            bizParam.put("request_id", UUID.randomUUID().toString());
            log.info("DevController#uploadDoctorInfo Request: {}", bizParam);
            BizUtil.initAlipayEasySdk(terminal);
            AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute("alipay.commerce.medical.industrydata.doctor.upload", null, bizParam);
            log.info("DevController#uploadDoctorInfo Response: {}", JSON.toJSONString(response));
            if (Constants.ALIPAY_SUCCESS_CODE.equals(response.getCode()))
                return ResponseVO.success(Checker.getStringValue(response.getMsg()));
            return ResponseVO.fail(Code.RESP_CODE_PARAM_ERROR, StringHelper.isNullOrEmpty(response.getSubMsg()) ? Checker.getStringValue(response.getMsg()) : response.getSubMsg());
        } catch (AppMessageException e) {
            log.error("DevController#uploadDoctorInfo(): {}", e.getMessage());
            return ResponseVO.fail(Code.RESP_CODE_PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            log.error("DevController#uploadDoctorInfo(): {}", e.getMessage(), e);
            return ResponseVO.fail(Code.RESP_CODE_APP_EXCEPTION, e.getMessage());
        }
    }


}
