package com.hys.app.controller.erp.use;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hys.app.framework.context.user.AdminUserContext;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.model.erp.configs.KuangShiConfig;
import com.hys.app.model.erp.entity.*;
import com.hys.app.model.support.LogClient;
import com.hys.app.model.support.validator.annotation.Log;
import com.hys.app.service.erp.CompanyErpManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "公司")
@RestController
@RequestMapping("/admin/erp/company")
@AllArgsConstructor
public class CompanyController {


    private CompanyErpManager companyManager;
    private KuangShiConfig kuangShiConfig;

    @PostMapping("createCompany")
    @ApiOperation(value = "创建公司")
//    @Log(client = LogClient.admin, detail = "创建名称为[${companyDO.name}]的公司信息")
    public String createCompany(@Valid @RequestBody CompanyDO companyDO) {
        return companyManager.createCompany(companyDO);
    }

    @PostMapping("updateCompany/{id}")
    @ApiOperation(value = "更新公司")
    @Log(client = LogClient.admin, detail = "修改名称为[${companyDO.name}]的公司信息")
    public Long updateCompany(@Valid @RequestBody CompanyDO companyUpdateDO, @PathVariable Long id) {
        return companyManager.updateCompany(companyUpdateDO, id);
    }

    @PostMapping("renewCompany/difference/{id}")
    @ApiOperation(value = "公司续费未到期更换套餐获取差价")
    @Log(client = LogClient.admin, detail = "名称为[${companyDO.name}]的公司进行了续费")
    public BigDecimal renewCompanyDifference(@PathVariable Long id) {
        return companyManager.renewCompanyDifference(id);
    }

    @PostMapping("renewCompany/{id}/{packageId}")
    @ApiOperation(value = "公司续费")
    @Log(client = LogClient.admin, detail = "名称为[${companyDO.name}]的公司进行了续费")
    public Long renewCompany(@PathVariable Long id, @PathVariable Long packageId) {
        AdminUserContext.hasCompany();
        return companyManager.renewCompany(id, packageId);
    }

    @PostMapping("superUpdateStatus/{id}")
    @ApiOperation(value = "公司审核")
    @Log(client = LogClient.admin, detail = "名称为[${companyDO.name}]的公司进行了续费")
    public Long renewCompany(@PathVariable Long id, @RequestBody CompanyStatusDO companyStatusDO) {
        AdminUserContext.hasFound();
        return companyManager.superUpdateStatus(id, companyStatusDO);
    }


    @GetMapping("getOne/{id}")
    @ApiOperation(value = "获取公司详情")
    public CompanyVO getOneCompany(@PathVariable Long id) {
        return companyManager.getOneCompany(id);
    }

    @GetMapping("getPage")
    @ApiOperation(value = "分页")
    public IPage<CompanyVO> getPage(CompanyQuery query) {
        return companyManager.getPage(query);
    }


    @PostMapping("/createCompany/checkIdCardOpposite/{type}")
    @ApiOperation(value = "校验身份证是否合法")
    public Object checkIdCardOpposite(@RequestBody  CompanyQuery query, @PathVariable String type) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image_url", query.getImageUrl());
            map.put("api_key", kuangShiConfig.getApikey());
            map.put("api_secret", kuangShiConfig.getApiSecret());
            String post = HttpUtil.post(kuangShiConfig.getIdCardUrl(), map);
            Map map1 = JSON.parseObject(post, Map.class);
            if (ObjectUtil.isNull(map1.get("cards"))){
                if ("front".equals(type)) {
                    throw new ServiceException("身份证正面未识别到相关信息，请重新上传");
                } else if ("opposite".equals(type)) {
                    throw new ServiceException("身份证反面未识别到相关信息，请重新上传");
                }
            }
            List<Map> maps = JSON.parseArray(JSON.toJSONString(map1.get("cards")), Map.class);
            return maps.get(0);
        } catch (Exception e) {
            if ("front".equals(type)) {
                throw new ServiceException("身份证正面未识别到相关信息，请重新上传");
            } else if ("opposite".equals(type)) {
                throw new ServiceException("身份证反面未识别到相关信息，请重新上传");
            }
        }
        throw new ServiceException("非法请求");
    }

    @PostMapping("/createCompany/checkLicense")
    @ApiOperation(value = "校验营业执照是否合法")
    public Object checkLicense(@RequestBody  CompanyQuery query) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image_url", query.getImageUrl());
            map.put("api_key", kuangShiConfig.getApikey());
            map.put("api_secret", kuangShiConfig.getApiSecret());
            String post = HttpUtil.post(kuangShiConfig.getLicenseUrl(), map);
            Map map1 = JSON.parseObject(post, Map.class);
            if (ObjectUtil.isNull(map1.get("business_license_content"))){
                throw new ServiceException("未识别到营业执照相关内容，请重新上传");
            }
            Map<String, Object> map2 = new HashMap<>();
            map2.put("username","{}");
            map2.put("password","{}");
            map2.put("time","{}");
            map2.put("phone","{}");
            System.out.println(JSONUtil.toJsonStr(map2)+"---------------------------");
            return JSON.parseObject(JSON.toJSONString(map1.get("business_license_content")), Map.class);
        } catch (Exception e) {
            throw new ServiceException("未识别到营业执照相关内容，请重新上传");
        }
    }

}
