package com.xinelu.web.controller.applet;

import com.alibaba.fastjson2.JSONObject;
import com.xinelu.common.config.XinELuConfig;
import com.xinelu.common.core.controller.BaseController;
import com.xinelu.common.core.domain.AjaxResult;
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.file.FileUploadUtils;
import com.xinelu.common.utils.file.FileUtils;
import com.xinelu.common.utils.file.MimeTypeUtils;
import com.xinelu.common.utils.http.HttpService;
import com.xinelu.common.utils.spring.SpringUtils;
import com.xinelu.familydoctor.applet.pojo.body.FileUploadBody;
import com.xinelu.familydoctor.applet.pojo.body.ResidentSignApplyBody;
import com.xinelu.familydoctor.applet.pojo.query.ApplyQuery;
import com.xinelu.familydoctor.applet.pojo.vo.ResidentSignApplyVo;
import com.xinelu.familydoctor.applet.service.IResidentSignAppletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.List;

/**
 * @Author mengkuiliang
 * @Description 居民小程序签约申请控制器
 * @Date 2023-09-26 026 10:10
 * @Param
 * @return
 **/
@Api(tags = "签约申请控制器")
@RestController
@RequestMapping("/applet/sign/apply")
public class ResidentSignApplyController extends BaseController {

    @Resource
    private IResidentSignAppletService residentSignAppletService;
    @Resource
    private HttpService httpService;

    @ApiOperation("提交签约申请")
    @PostMapping("/save")
    public R<String> save(@RequestBody ResidentSignApplyBody body, @RequestHeader("region") String region) {
        if (StringUtils.isBlank(body.getIdentity())) {
            return R.fail("身份证号不能为空");
        }
        if (body.getCrowdList() == null || body.getCrowdList().size() == 0) {
            return R.fail("人群不能为空");
        }
        if (body.getPackageList() == null || body.getPackageList().size() == 0) {
            return R.fail("服务包不能为空");
        }
        residentSignAppletService.insert(body, region);
        return R.ok();
    }

    @ApiOperation("取消签约申请")
    @PostMapping("/cancel/{bookingNo}")
    public R<String> cancel(@PathVariable String bookingNo) {
        residentSignAppletService.cancel(bookingNo);
        return R.ok();
    }

    @ApiOperation(value = "是否已签约", notes = "data(01: 已申请签约 02：已签约 0: 未签约)")
    @GetMapping("/checkSignApply/{identity}")
    public R<?> save(@PathVariable String identity, @RequestHeader("region") String region) {
        try {
            return R.ok(residentSignAppletService.checkSignApply(identity, region));
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "获取签约申请列表")
    @GetMapping("/getList")
    public TableDataInfo getList(ApplyQuery query) {
        try {
            startPage();
            List<ResidentSignApplyVo> list = residentSignAppletService.findList(query);
            return getDataTable(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    @ApiOperation(value = "获取签约申请详情")
    @GetMapping("/detail/{bookingNo}")
    public R<ResidentSignApplyVo> getSignApply(@PathVariable String bookingNo) {
        try {
            return R.ok(residentSignAppletService.detail(bookingNo));
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }


    @ApiOperation("居民签字上传")
    @PostMapping(value = "/residentSignatureUpload")
    public AjaxResult headPictureUpload(MultipartFile file, @RequestHeader("region") String region) throws Exception {
        if (StringUtils.isBlank(file.getOriginalFilename())) {
            return AjaxResult.error("请选择所要上传的居民签字！");
        }
        FileUploadBody body = new FileUploadBody();
        body.setOriginalFilename(file.getOriginalFilename());
        body.setCode("1001");
        body.setContentType(file.getContentType());
        body.setSuffix(body.getOriginalFilename().substring(body.getOriginalFilename().lastIndexOf(".") + 1));
        body.setFile(Base64.getEncoder().encodeToString(file.getBytes()));
        // 上传家医
        JSONObject result = httpService.post(SpringUtils.getFdUrl(region) + "/resident/signinfo/uploadBase64", null, JSONObject.parseObject(JSONObject.toJSONString(body)));
        if ("0".equals(result.get("code"))) {
            return AjaxResult.error(result.get("msg").toString());
        }
        AjaxResult ajax = AjaxResult.success("上传成功！");
        ajax.put("imgUrl", result.getString("data"));
        return ajax;
    }

    @ApiOperation("获取居民签字")
    @GetMapping(value = "/getResidentSignature/{fileNo}")
    public AjaxResult getResidentSignature(@PathVariable String fileNo, @RequestHeader("region") String region) {
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/getSignBase64/" + fileNo, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!"1".equals(jsonObject.get("code"))) {
            return AjaxResult.error(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            return AjaxResult.success();
        }
        return AjaxResult.success("查询成功", jsonObject.getString("data"));
    }

}
